You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5897 lines
200 KiB

  1. #!/bin/bash
  2. ##
  3. ## TODO:
  4. ## - subordinate container should really be able to modify base image of their master
  5. ## - this could be done through docker-update
  6. ## - I'm not happy with the current build using 'build/' directory, this should be
  7. ## changed to:
  8. ## - always have a base image (specified in metadata), and always have hooks/install
  9. ## executed and merge in image (like docker-build-charm).
  10. ## - container base image is ALWAYS the image of the master container... this brings
  11. ## questions about a double way to express inheritage (through relations as it is
  12. ## implemented now, or through this base-image ?)
  13. ## - the name of the scripts for relation (aka relation_name-relation-joined) is bad as
  14. ## reading the name in a hooks/ dir, there are no way to know if we are the target or
  15. ## the base of the relation.
  16. ## - we could leverage a 'relations/' dir on the root of the charm, with both:
  17. ## 'relations/provide/relation_name' and 'relations/receive/relation_name'
  18. ## - a very bad point with the actual naming is that we can't have a providing AND
  19. ## receiving a relation with same name.
  20. ## - The cache system should keep md5 of docker-compose and other things between runs
  21. ## - The cache system should use underlying function that have only arguments inputs.
  22. ## This will allow to cache completely without issues function in time.
  23. ## - would probably need instrospection in charm custom action to know if these need
  24. ## init or relations to be set up.
  25. ## - Be clear about when the SERVICE name is used and the CHARM name is used.
  26. ## - in case of service contained in another container
  27. ## - in normal case
  28. ## - in docker-compose, can't use charm name: if we want 2 instances of the same charm
  29. ## we are stuck. What will be unique is the name of the service.
  30. ## - some relations are configured in compose.yml but should not trigger the loading
  31. ## of necessary component (for instance, apache --> log-rotate), if log-rotate is
  32. ## not there, this link should considered optional.
  33. ## - Could probably allow an unexistent charm to be populated with only "docker-image:"
  34. ## of the same name. Although this should trigger a visible warning.
  35. #:-
  36. [ -e /etc/shlib ] && . /etc/shlib || {
  37. echo "Unsatisfied dependency. Please install 'kal-shlib-core'."
  38. exit 1
  39. }
  40. #:-
  41. include common
  42. include pretty
  43. include parse
  44. include charm
  45. include array
  46. include cla
  47. include docker
  48. depends shyaml docker
  49. exname="compose"
  50. version=0.1
  51. usage="$exname [COMPOSE_OPTS] [ACTION [ACTION_OPTS]]"
  52. help="\
  53. $WHITE$exname$NORMAL jobs is to run various shell scripts to build
  54. a running orchestrated and configured docker containers. These shell
  55. scripts will have the opportunity to build a 'docker-compose.yml'.
  56. Once init script and relations scripts are executed, $WHITE$exname$NORMAL
  57. delegate the launching to ${WHITE}docker-compose${NORMAL} by providing it
  58. the final 'docker-compose.yml'.
  59. $WHITE$exname$NORMAL also leverage charms to offer some additional custom
  60. actions per charm, which are simply other scripts that can be
  61. run without launching ${WHITE}docker-compose${NORMAL}.
  62. In compose message, color coding is enforced as such:
  63. - ${DARKCYAN}action$NORMAL,
  64. - ${DARKBLUE}relation$NORMAL,
  65. - ${DARKPINK}charm${NORMAL},
  66. - ${DARKYELLOW}service${NORMAL},
  67. - ${WHITE}option-name${NORMAL}/${WHITE}command-name${NORMAL}/${WHITE}Section-Title${NORMAL}
  68. $WHITE$exname$NORMAL reads '/etc/compose.conf' for global variables, and
  69. '/etc/compose.local.conf' for local host adjustements.
  70. "
  71. time_now() { date +%s.%3N; }
  72. time_elapsed() { echo "scale=3; $2 - $1" | bc; }
  73. ## XXXvlab: this doesn't seem to work when 'compose' is called in
  74. ## a hook of a charm.
  75. #[[ "${BASH_SOURCE[0]}" == "" ]] && SOURCED=true
  76. $(return >/dev/null 2>&1) && SOURCED=true
  77. errlvl() { return "${1:-1}"; }
  78. export -f errlvl
  79. if [ "$UID" == 0 ]; then
  80. CACHEDIR=${CACHEDIR:-/var/cache/compose}
  81. VARDIR=${VARDIR:-/var/lib/compose}
  82. else
  83. [ "$XDG_CONFIG_HOME" ] && CACHEDIR=${CACHEDIR:-$XDG_CONFIG_HOME/compose}
  84. [ "$XDG_DATA_HOME" ] && VARDIR=${VARDIR:-$XDG_DATA_HOME/compose}
  85. CACHEDIR=${CACHEDIR:-$HOME/.cache/compose}
  86. VARDIR=${VARDIR:-$HOME/.local/share/compose}
  87. fi
  88. export VARDIR CACHEDIR
  89. export SERVICE_STATE_PATH=${SERVICE_STATE_PATH:-/var/lib/compose/state}
  90. md5_compat() { md5sum | cut -c -32; }
  91. quick_cat_file() { quick_cat_stdin < "$1"; }
  92. quick_cat_stdin() { local IFS=''; while read -r line; do echo "$line"; done ; }
  93. export -f quick_cat_file quick_cat_stdin md5_compat
  94. p-err() {
  95. "$@"
  96. echo "$?"
  97. }
  98. export -f p-err
  99. wyq() {
  100. local exp="$1"
  101. yq e -e -0 "$1"
  102. printf "%s" "$?"
  103. }
  104. wyq-r() {
  105. local exp="$1"
  106. yq e -e -0 -r=false "$1"
  107. printf "%s" "$?"
  108. }
  109. err-d () {
  110. local msg="$*"
  111. shift
  112. err "$msg"
  113. print:traceback 1
  114. }
  115. export -f err-d
  116. print:traceback() {
  117. local omit_level="${1:-0}"
  118. if [ -z "$DEBUG" ]; then
  119. echo " Note: traceback available if you provide {--debug|-d} option." >&2
  120. return 0
  121. fi
  122. echo "${WHITE}Traceback (most recent call last):${NORMAL}" >&2
  123. local i
  124. for ((i=${#FUNCNAME[@]} - 1; i > "$omit_level"; i--)); do
  125. local file="${BASH_SOURCE[$i]}"
  126. local line="${BASH_LINENO[$i - 1]}"
  127. local func="${FUNCNAME[$i]}"
  128. if [[ -f "$file" ]]; then
  129. # Get total number of lines in the file
  130. local total_lines
  131. total_lines=$(wc -l < "$file")
  132. # Calculate start and end lines for context
  133. local start_line=$((line - 2))
  134. local end_line=$((line + 2))
  135. [[ $start_line -lt 1 ]] && start_line=1
  136. [[ $end_line -gt $total_lines ]] && end_line=$total_lines
  137. # Extract context lines
  138. mapfile -s $((start_line - 1)) -n $((end_line - start_line + 1)) context_lines < "$file"
  139. # Calculate minimal indentation
  140. local min_indent=9999
  141. for line_text in "${context_lines[@]}"; do
  142. if [[ -n "$line_text" ]]; then
  143. # Get leading whitespace
  144. local leading_whitespace="${line_text%%[![:space:]]*}"
  145. local indent=${#leading_whitespace}
  146. if [[ $indent -lt $min_indent ]]; then
  147. min_indent=$indent
  148. fi
  149. fi
  150. done
  151. # Remove minimal indentation from each line
  152. for idx in "${!context_lines[@]}"; do
  153. context_lines[$idx]="${context_lines[$idx]:$min_indent}"
  154. done
  155. else
  156. context_lines=("<source unavailable>")
  157. min_indent=0
  158. start_line=1
  159. end_line=1
  160. fi
  161. # Print the traceback frame
  162. echo " File \"$file\", line $line, in ${WHITE}$func${NORMAL}:"
  163. # Print the context with line numbers
  164. local current_line=$start_line
  165. for context_line in "${context_lines[@]}"; do
  166. context_line="${context_line%$'\n'}"
  167. if [[ $current_line -eq $line ]]; then
  168. echo " ${DARKYELLOW}$current_line${NORMAL} ${context_line}"
  169. else
  170. echo " ${DARKGRAY}$current_line${NORMAL} ${context_line}"
  171. fi
  172. ((current_line++))
  173. done
  174. done >&2
  175. }
  176. export -f print:traceback
  177. clean_cache() {
  178. local i=0
  179. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  180. ((i++))
  181. rm -f "$f"
  182. done
  183. if (( i > 0 )); then
  184. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  185. fi
  186. }
  187. export DEFAULT_COMPOSE_FILE
  188. ##
  189. ## Merge YAML files
  190. ##
  191. export _merge_yaml_common_code="
  192. import sys
  193. import yaml
  194. try:
  195. from yaml import CSafeLoader as SafeLoader, CSafeDumper as SafeDumper
  196. except ImportError: ## pragma: no cover
  197. sys.stderr.write('YAML code in pure python\n')
  198. exit(1)
  199. from yaml import SafeLoader, SafeDumper
  200. class MySafeLoader(SafeLoader): pass
  201. class MySafeDumper(SafeDumper): pass
  202. try:
  203. # included in standard lib from Python 2.7
  204. from collections import OrderedDict
  205. except ImportError:
  206. # try importing the backported drop-in replacement
  207. # it's available on PyPI
  208. from ordereddict import OrderedDict
  209. ## Ensure that there are no collision with legacy OrderedDict
  210. ## that could be used for omap for instance.
  211. class MyOrderedDict(OrderedDict):
  212. pass
  213. MySafeDumper.add_representer(
  214. MyOrderedDict,
  215. lambda cls, data: cls.represent_dict(data.items()))
  216. def construct_omap(cls, node):
  217. cls.flatten_mapping(node)
  218. return MyOrderedDict(cls.construct_pairs(node))
  219. MySafeLoader.add_constructor(
  220. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  221. construct_omap)
  222. ##
  223. ## Support local and global objects
  224. ##
  225. class EncapsulatedNode(object): pass
  226. def mk_encapsulated_node(s, node):
  227. method = 'construct_%s' % (node.id, )
  228. data = getattr(s, method)(node)
  229. class _E(data.__class__, EncapsulatedNode):
  230. pass
  231. _E.__name__ = str(node.tag)
  232. _E._node = node
  233. return _E(data)
  234. def represent_encapsulated_node(s, o):
  235. value = s.represent_data(o.__class__.__bases__[0](o))
  236. value.tag = o.__class__.__name__
  237. return value
  238. MySafeDumper.add_multi_representer(EncapsulatedNode,
  239. represent_encapsulated_node)
  240. MySafeLoader.add_constructor(None, mk_encapsulated_node)
  241. def fc(filename):
  242. with open(filename) as f:
  243. return f.read()
  244. def merge(*args):
  245. # sys.stderr.write('%r\n' % (args, ))
  246. args = [arg for arg in args if arg is not None]
  247. if len(args) == 0:
  248. return None
  249. if len(args) == 1:
  250. return args[0]
  251. if all(isinstance(arg, (int, basestring, bool, float)) for arg in args):
  252. return args[-1]
  253. elif all(isinstance(arg, list) for arg in args):
  254. res = []
  255. for arg in args:
  256. for elt in arg:
  257. if elt in res:
  258. res.remove(elt)
  259. res.append(elt)
  260. return res
  261. elif all(isinstance(arg, dict) for arg in args):
  262. keys = set()
  263. for arg in args:
  264. keys |= set(arg.keys())
  265. dct = {}
  266. for key in keys:
  267. sub_args = []
  268. for arg in args:
  269. if key in arg:
  270. sub_args.append(arg)
  271. try:
  272. dct[key] = merge(*(a[key] for a in sub_args))
  273. except NotImplementedError as e:
  274. raise NotImplementedError(
  275. e.args[0],
  276. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  277. e.args[2])
  278. if dct[key] is None:
  279. del dct[key]
  280. return dct
  281. else:
  282. raise NotImplementedError(
  283. 'Unsupported types: %s'
  284. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  285. return None
  286. def merge_cli(*args):
  287. try:
  288. c = merge(*args)
  289. except NotImplementedError as e:
  290. sys.stderr.write('Merging Failed: %s.\n%s\n'
  291. ' Values are:\n %s\n'
  292. % (e.args[0],
  293. ' Conflicting key is %r.' % e.args[1] if e.args[1] else
  294. ' Conflict at base of structure.',
  295. '\\n '.join('v%d: %r' % (i, a)
  296. for i, a in enumerate(e.args[2]))))
  297. exit(1)
  298. if c is not None:
  299. print '%s' % yaml.dump(c, default_flow_style=False, Dumper=MySafeDumper)
  300. "
  301. merge_yaml() {
  302. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  303. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  304. $_merge_yaml_common_code
  305. merge_cli(*(yaml.load(fc(f), Loader=MySafeLoader) for f in sys.argv[1:]))
  306. EOF
  307. fi
  308. python "$state_tmpdir/merge_yaml.py" "$@"
  309. }
  310. export -f merge_yaml
  311. merge_yaml_str() {
  312. local entries="$@"
  313. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  314. cat <<EOF > "$state_tmpdir/merge_yaml_str.py" || return 1
  315. $_merge_yaml_common_code
  316. merge_cli(*(yaml.load(f, Loader=MySafeLoader) for f in sys.argv[1:]))
  317. EOF
  318. fi
  319. if ! python "$state_tmpdir/merge_yaml_str.py" "$@"; then
  320. err "Failed to merge yaml strings:"
  321. local s
  322. for s in "$@"; do
  323. printf " - \n"
  324. printf "%s\n" "$s" | prefix " ${GRAY}|$NORMAL "
  325. done >&2
  326. return 1
  327. fi
  328. }
  329. export -f merge_yaml_str
  330. yaml_get_values() {
  331. local sep=${1:-$'\n'} value input type first elt
  332. input=$(cat -)
  333. if [ -z "$input" ] || [[ "$input" =~ ^None|null$ ]]; then
  334. return 0
  335. fi
  336. type=$(e "$input" | shyaml get-type)
  337. value=
  338. case "$type" in
  339. "sequence")
  340. first=1
  341. while read-0 elt; do
  342. elt="$(e "$elt" | yaml_get_interpret)" || return 1
  343. [ "$elt" ] || continue
  344. if [ "$first" ]; then
  345. first=
  346. else
  347. value+="$sep"
  348. fi
  349. first=
  350. value+="$elt"
  351. done < <(e "$input" | shyaml -y get-values-0)
  352. ;;
  353. "struct")
  354. while read-0 val; do
  355. value+=$'\n'"$(e "$val" | yaml_get_interpret)" || return 1
  356. done < <(e "$input" | shyaml -y values-0)
  357. ;;
  358. "NoneType")
  359. value=""
  360. ;;
  361. "str"|*)
  362. value+="$(e "$input" | yaml_get_interpret)"
  363. ;;
  364. esac
  365. e "$value"
  366. }
  367. export -f yaml_get_values
  368. yaml_key_val_str() {
  369. local entries="$@"
  370. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  371. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  372. $_merge_yaml_common_code
  373. print '%s' % yaml.dump(
  374. {
  375. yaml.load(sys.argv[1], Loader=MySafeLoader):
  376. yaml.load(sys.argv[2], Loader=MySafeLoader)
  377. },
  378. default_flow_style=False,
  379. Dumper=MySafeDumper,
  380. )
  381. EOF
  382. fi
  383. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  384. }
  385. export -f yaml_key_val_str
  386. ##
  387. ## Docker
  388. ##
  389. docker_has_image() {
  390. local image="$1"
  391. images=$(docker images -q "$image" 2>/dev/null) || {
  392. err "docker images call has failed unexpectedly."
  393. return 1
  394. }
  395. [ -n "$images" ]
  396. }
  397. export -f docker_has_image
  398. docker_image_id() {
  399. local image="$1"
  400. image_id=$(docker inspect "$image" --format='{{.Id}}') || return 1
  401. echo "$image_id" # | tee "$cache_file"
  402. }
  403. export -f docker_image_id
  404. cached_cmd_on_image() {
  405. local image="$1" cache_file
  406. image_id=$(docker_image_id "$image") || return 1
  407. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  408. if [ -e "$cache_file" ]; then
  409. # debug "$FUNCNAME: cache hit ($*)"
  410. quick_cat_stdin < "$cache_file"
  411. return 0
  412. fi
  413. shift
  414. out=$(docker run -i --rm --entrypoint /bin/sh "$image_id" -c "$*") || return 1
  415. echo "$out" | tee "$cache_file"
  416. }
  417. export -f cached_cmd_on_image
  418. cmd_on_base_image() {
  419. local service="$1" base_image
  420. shift
  421. base_image=$(service_ensure_image_ready "$service") || return 1
  422. docker run -i --rm --entrypoint /bin/bash "$base_image" -c "$*"
  423. }
  424. export -f cmd_on_base_image
  425. cached_cmd_on_base_image() {
  426. local service="$1" base_image cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  427. shift
  428. if [ -e "$cache_file" ]; then
  429. # debug "$FUNCNAME: cache hit ($*)"
  430. quick_cat_stdin < "$cache_file"
  431. return 0
  432. fi
  433. base_image=$(service_ensure_image_ready "$service") || return 1
  434. result=$(cached_cmd_on_image "$base_image" "$@") || return 1
  435. echo "$result" | tee "$cache_file"
  436. }
  437. export -f cached_cmd_on_base_image
  438. docker_update() {
  439. ## YYY: warning, we a storing important information in cache, cache can
  440. ## be removed.
  441. ## We want here to cache the last script on given service whatever that script was
  442. local service="$1" script="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$1" \
  443. previous_base_image stored_image_id
  444. shift
  445. shift
  446. ## this will build it if necessary
  447. base_image=$(service_ensure_image_ready "$service") || return 1
  448. ## XXXvlab: there are probably ways to avoid rebuilding that each time
  449. image_id="$(docker_image_id "$base_image")" || return 1
  450. if [ -e "$cache_file" ]; then
  451. info "Cache file exists"
  452. read-0 previous_base_image stored_image_id < <(cat "$cache_file")
  453. info "previous: $previous_base_image"
  454. info "stored: $stored_image_id"
  455. else
  456. info "No cache file $cache_file"
  457. previous_base_image=""
  458. fi
  459. if [ "$previous_base_image" -a "$stored_image_id" == "$image_id" ]; then
  460. info "Resetting $base_image to $previous_base_image"
  461. docker tag "$previous_base_image" "$base_image" || return 1
  462. image_id="$(docker_image_id "$base_image")" || return 1
  463. else
  464. previous_base_image="$image_id"
  465. fi
  466. info "Updating base image: $base_image (hash: $image_id)"
  467. echo "$script" | dupd --debug -u "$base_image" -- "$@" || {
  468. err "Failed updating base image"
  469. return 1
  470. }
  471. new_image_id="$(docker_image_id "$base_image")"
  472. [ "$new_image_id" == "$previous_base_image" ] && {
  473. err "Image was not updated correctly (same id)."
  474. return 1
  475. }
  476. printf "%s\0" "$previous_base_image" "$new_image_id" > "$cache_file"
  477. info "Wrote cache file $cache_file"
  478. }
  479. export -f docker_update
  480. image_exposed_ports_0() {
  481. local image="$1"
  482. docker inspect --format='{{range $p, $conf := .Config.ExposedPorts}}{{$p}}{{"\x00"}}{{end}}' "$image"
  483. }
  484. export -f image_exposed_ports_0
  485. ## feature not yet included in docker: https://github.com/moby/moby/issues/16079
  486. docker_image_export_dir() {
  487. local image="$1" src="$2" dst="$3" container_id
  488. (
  489. container_id=$(docker create "$image") || exit 1
  490. trap_add EXIT,ERR "docker rm \"$container_id\" >/dev/null"
  491. docker cp "$container_id":"$src" "$dst"
  492. )
  493. }
  494. export -f docker_image_export_dir
  495. service_base_image_export_dir() {
  496. local service="$1" src="$2" dst="$3" base_image
  497. shift
  498. base_image=$(service_ensure_image_ready "$service") || return 1
  499. docker_image_export_dir "$base_image" "$src" "$dst"
  500. }
  501. export -f service_base_image_export_dir
  502. service_base_image_id() {
  503. local service="$1" src="$2" dst="$3" base_image
  504. shift
  505. base_image=$(service_ensure_image_ready "$service") || return 1
  506. docker inspect "$base_image" --format="{{ .Id }}"
  507. }
  508. export -f service_base_image_id
  509. ##
  510. ## Generic
  511. ##
  512. fn.exists() {
  513. declare -F "$1" >/dev/null
  514. }
  515. str_pattern_matches() {
  516. local str="$1"
  517. shift
  518. for pattern in "$@"; do
  519. eval "[[ \"$str\" == $pattern ]]" && return 0
  520. done
  521. return 1
  522. }
  523. str_matches() {
  524. local str="$1"
  525. shift
  526. for pattern in "$@"; do
  527. [[ "$str" == "$pattern" ]] && return 0
  528. done
  529. return 1
  530. }
  531. gen_password() {
  532. local l=( {a..z} {A..Z} {0..9} ) nl="${#l[@]}" size=${1:-16}
  533. while ((size--)); do
  534. echo -n "${l[$((RANDOM * nl / 32768))]}"
  535. done
  536. echo
  537. }
  538. export -f gen_password
  539. file_put() {
  540. local TARGET="$1"
  541. mkdir -p "$(dirname "$TARGET")" &&
  542. cat - > "$TARGET"
  543. }
  544. export -f file_put
  545. file_put_0() {
  546. local TARGET="$1"
  547. mkdir -p "$(dirname "$TARGET")" &&
  548. cat > "$TARGET"
  549. }
  550. export -f file_put_0
  551. fetch_file() {
  552. local src="$1"
  553. case "$src" in
  554. *"://"*)
  555. err "Unsupported target scheme."
  556. return 1
  557. ;;
  558. *)
  559. ## Try direct
  560. if ! [ -r "$src" ]; then
  561. err "File '$src' not found/readable."
  562. return 1
  563. fi
  564. cat "$src" || return 1
  565. ;;
  566. esac
  567. }
  568. export -f fetch_file
  569. ## receives stdin content to decompress on stdout
  570. ## stdout content should be tar format.
  571. uncompress_file() {
  572. local filename="$1"
  573. ## Warning, the content of the file is already as stdin, the filename
  574. ## is there to hint for correct decompression.
  575. case "$filename" in
  576. *".gz")
  577. gunzip
  578. ;;
  579. *".bz2")
  580. bunzip2
  581. ;;
  582. *)
  583. cat
  584. ;;
  585. esac
  586. }
  587. export -f uncompress_file
  588. get_file() {
  589. local src="$1"
  590. fetch_file "$src" | uncompress_file "$src"
  591. }
  592. export -f get_file
  593. ##
  594. ## Common database lib
  595. ##
  596. _clean_docker() {
  597. local _DB_NAME="$1" container_id="$2"
  598. (
  599. set +e
  600. debug "Removing container $_DB_NAME"
  601. docker stop "$container_id"
  602. docker rm "$_DB_NAME"
  603. docker network rm "${_DB_NAME}"
  604. rm -vf "$state_tmpdir/${_DB_NAME}.state"
  605. ) >&2
  606. }
  607. export -f _clean_docker
  608. get_service_base_image_dir_uid_gid() {
  609. local service="$1" dir="$2" uid_gid
  610. uid_gid=$(cached_cmd_on_base_image "$service" "stat -c '%u %g' '$dir'") || {
  611. debug "Failed to query '$dir' uid in ${DARKYELLOW}$service${NORMAL} base image."
  612. return 1
  613. }
  614. info "uid and gid from ${DARKYELLOW}$service${NORMAL}:$dir is '$uid_gid'"
  615. echo "$uid_gid"
  616. }
  617. export -f get_service_base_image_dir_uid_gid
  618. get_service_type() {
  619. if [ -z "$CHARM_STORE_HASH" ]; then
  620. err-d "Expected \$CHARM_STORE_HASH to be set."
  621. return 1
  622. fi
  623. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH"
  624. if [ -z "$service" ]; then
  625. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  626. return 1
  627. fi
  628. if [ -e "$cache_file" ]; then
  629. # debug "$FUNCNAME: cache hit ($*)"
  630. cat "$cache_file"
  631. return 0
  632. fi
  633. master_target_service="$(get_top_master_service_for_service "$service")" || return 1
  634. charm=$(get_service_charm "$master_target_service") || return 1
  635. metadata=$(charm.metadata "$charm") || return 1
  636. printf "%s" "$metadata" | shyaml get-value type service 2>/dev/null |
  637. tee "$cache_file"
  638. }
  639. export -f get_service_type
  640. are_files_locked_in_dir() {
  641. local dir="$1" device hdev ldev
  642. device=$(stat -c %d "$dir") || {
  643. err "Can't stat '$dir'."
  644. return 1
  645. }
  646. device=$(printf "%04x" $device)
  647. hdev=${device:0:2}
  648. ldev=${device:2:2}
  649. inodes=$(find "$dir" -printf ':%i:\n')
  650. found=
  651. while read -r inode; do
  652. debug "try inode:$inode"
  653. if [[ "$inodes" == *":$inode:"* ]]; then
  654. found=1
  655. break
  656. fi
  657. done < <(cat /proc/locks | grep " $hdev:$ldev:" | sed -r "s/^.*$hdev:$ldev:([0-9]+).*$/\1/g")
  658. [ "$found" ]
  659. }
  660. export -f are_files_locked_in_dir
  661. set_db_params() {
  662. local docker_ip="$1" docker_network="$2"
  663. if [ -z "$DB_PARAMS_LOADED" ]; then
  664. DB_PARAMS_LOADED=1
  665. _set_db_params "$docker_ip" "$docker_network"
  666. fi
  667. }
  668. export -f set_db_params
  669. export _PID="$$"
  670. ensure_db_docker_running () {
  671. local _STATE_FILE errlvl project
  672. _DB_NAME="db_${DB_NAME}_${_PID}"
  673. _STATE_FILE="$state_tmpdir/${_DB_NAME}.state"
  674. if [ -e "$_STATE_FILE" ]; then
  675. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$(cat "$_STATE_FILE")"
  676. debug "Re-using previous docker/connection '$DOCKER_IP'."
  677. set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  678. return 0
  679. fi
  680. if [ -e "$state_tmpdir/${_DB_NAME}.working" ]; then
  681. ## avoid recursive calls.
  682. if [ -z "$DOCKER_IP" ]; then
  683. err "Currently figuring up DOCKER_IP, please set it yourself before this call if needed."
  684. return 1
  685. else
  686. debug "ignoring recursive call of 'ensure_db_docker_running'."
  687. fi
  688. return 0
  689. fi
  690. touch "$state_tmpdir/${_DB_NAME}.working"
  691. docker rm "$_DB_NAME" 2>/dev/null || true
  692. host_db_working_dir="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR"
  693. if is_db_locked; then
  694. info "Some process is using '$host_db_working_dir'. Trying to find a docker that would do this..."
  695. found=
  696. for docker_id in $(docker ps -q); do
  697. has_volume_mounted=$(
  698. docker inspect \
  699. --format "{{range .Mounts}}{{if eq .Destination \"$DB_DATADIR\"}}{{.Source}}{{end}}{{end}}" \
  700. "$docker_id")
  701. if [ "$has_volume_mounted" == "$host_db_working_dir" ]; then
  702. info "docker '$docker_id' uses '$has_volume_mounted'."
  703. project=$(docker inspect "$docker_id" \
  704. --format "{{index .Config.Labels \"compose.project\" }}") || continue
  705. info "docker '$docker_id' is from project '$project' (current project is '$PROJECT_NAME')."
  706. [ "$project" == "$PROJECT_NAME" ] || continue
  707. found="$docker_id"
  708. break
  709. fi
  710. done
  711. if [ -z "$found" ]; then
  712. err "Please shutdown any other docker using this directory."
  713. return 1
  714. fi
  715. export container_id="$found"
  716. info "Found docker $docker_id is already running."
  717. else
  718. verb "Database is not locked."
  719. if ! docker_has_image "$DOCKER_BASE_IMAGE"; then
  720. err "Unexpected missing docker image $DOCKER_BASE_IMAGE."
  721. return 1
  722. fi
  723. _set_server_db_params || return 1
  724. debug docker network create "$_DB_NAME"
  725. if ! network_id=$(docker network create "$_DB_NAME"); then
  726. err "'docker network create $_DB_NAME' failed !"
  727. _clean_docker "$_DB_NAME" "$container_id"
  728. rm "$state_tmpdir/${_DB_NAME}.working"
  729. return 1
  730. fi
  731. debug docker run -d \
  732. --name "$_DB_NAME" \
  733. "${server_docker_opts[@]}" \
  734. --network "$_DB_NAME" \
  735. -v "$host_db_working_dir:$DB_DATADIR" \
  736. "$DOCKER_BASE_IMAGE"
  737. if ! container_id=$(
  738. docker run -d \
  739. --name "$_DB_NAME" \
  740. "${server_docker_opts[@]}" \
  741. --network "$_DB_NAME" \
  742. -v "$host_db_working_dir:$DB_DATADIR" \
  743. "$DOCKER_BASE_IMAGE"
  744. ); then
  745. err "'docker run' failed !"
  746. _clean_docker "$_DB_NAME" "$container_id"
  747. rm "$state_tmpdir/${_DB_NAME}.working"
  748. return 1
  749. fi
  750. trap_add EXIT,ERR "_clean_docker \"$_DB_NAME\" \"$container_id\""
  751. fi
  752. if docker_ip=$(wait_for_docker_ip "$container_id"); then
  753. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  754. echo "$docker_ip" > "$_STATE_FILE"
  755. debug "written '$_STATE_FILE'"
  756. rm "$state_tmpdir/${_DB_NAME}.working"
  757. set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  758. return 0
  759. else
  760. errlvl="$?"
  761. err "Db not found (errlvl: $errlvl). Tail of docker logs follows:"
  762. docker logs --tail=5 "$container_id" 2>&1 | prefix " | " >&2
  763. rm "$state_tmpdir/${_DB_NAME}.working"
  764. return "$errlvl"
  765. fi
  766. }
  767. export -f ensure_db_docker_running
  768. ## Require to set $db_docker_opts if needed, and $DB_PASSFILE
  769. ##
  770. _dcmd() {
  771. local docker_opts command="$1"
  772. shift
  773. debug "Db> $command $@"
  774. if [ "$HOST_DB_PASSFILE" -a -f "$LOCAL_DB_PASSFILE" -a "$CLIENT_DB_PASSFILE" ]; then
  775. verb "Found and using '$HOST_DB_PASSFILE' as '$CLIENT_DB_PASSFILE'."
  776. docker_opts=("${db_docker_opts[@]}" "-v" "$HOST_DB_PASSFILE:$CLIENT_DB_PASSFILE")
  777. else
  778. docker_opts=("${db_docker_opts[@]}")
  779. fi
  780. ## XXXX was here: actualy, we need only connection between this version and the client version
  781. debug docker run -i --rm \
  782. "${docker_opts[@]}" \
  783. --entrypoint "$command" "$DOCKER_BASE_IMAGE" "${db_cmd_opts[@]}" "$@"
  784. docker run -i --rm \
  785. "${docker_opts[@]}" \
  786. --entrypoint "$command" "$DOCKER_BASE_IMAGE" "${db_cmd_opts[@]}" "$@"
  787. }
  788. export -f _dcmd
  789. ## Executes code through db
  790. dcmd() {
  791. local fun
  792. [ "$DB_NAME" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_NAME."
  793. [ "$DB_DATADIR" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_DATADIR."
  794. # [ "$DB_PASSFILE" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_PASSFILE."
  795. [ "$_PID" ] || print_syntax_error "$FUNCNAME: You must provide \$_PID."
  796. for fun in is_db_locked _set_db_params ddb; do
  797. [ "$(type -t "$fun")" == "function" ] ||
  798. print_syntax_error "$FUNCNAME: You must provide function '$fun'."
  799. done
  800. ensure_db_docker_running </dev/null || return 1
  801. _dcmd "$@"
  802. }
  803. export -f dcmd
  804. get_docker_ips() {
  805. local name="$1" ip format network_id
  806. if ! docker inspect --format='{{ .NetworkSettings.Networks }}' "$name" >/dev/null 2>&1; then
  807. echo "default:$(docker inspect --format='{{ .NetworkSettings.IPAddress }}' "$name" 2>/dev/null)"
  808. else
  809. format='{{range $name, $conf := .NetworkSettings.Networks}}{{$name}}{{"\x00"}}{{$conf.IPAddress}}{{"\x00"}}{{end}}'
  810. while read-0 network_id ip; do
  811. printf "%s:%s\n" "$network_id" "$ip"
  812. done < <(docker inspect --format="$format" "$name")
  813. fi
  814. }
  815. export -f get_docker_ips
  816. get_docker_ip() {
  817. local name="$1"
  818. get_docker_ips "$name"
  819. }
  820. export -f get_docker_ip
  821. wait_docker_ip() {
  822. local name="$1" timeout="${2:-15}" timeout_count=0 docker_ip=
  823. start=$SECONDS
  824. while [ -z "$docker_ip" ]; do
  825. sleep 0.5
  826. docker_ip=$(get_docker_ip "$name") && break
  827. elapsed=$((SECONDS - start))
  828. if ((elapsed > timeout)); then
  829. err "${RED}timeout error${NORMAL}(${timeout}s):" \
  830. "Could not find '$name' docker container's IP."
  831. return 1
  832. fi
  833. [ "$elapsed" == "$old_elapsed" ] ||
  834. verb "Waiting for docker $name... ($elapsed/$timeout)"
  835. old_elapsed="$elapsed"
  836. done
  837. verb "Found docker $name network and IP: $docker_ip"
  838. echo "$docker_ip"
  839. }
  840. export -f wait_docker_ip
  841. wait_for_tcp_port() {
  842. local network=$1 host_port=$2 timeout=${3:-60}
  843. verb "Trying to connect to $host_port"
  844. bash_image=${DEFAULT_BASH_IMAGE:-docker.0k.io/bash}
  845. #echo docker run --rm -i --network "$network" "$bash_image" >&2
  846. docker run --rm -i --network "$network" "$bash_image" <<EOF
  847. start=\$SECONDS
  848. while true; do
  849. timeout 1 bash -c "</dev/tcp/${host_port/://}" >/dev/null 2>&1 && break
  850. sleep 0.2
  851. if [ "\$((SECONDS - start))" -gt "$timeout" ]; then
  852. exit 1
  853. fi
  854. done
  855. exit 0
  856. EOF
  857. if [ "$?" != 0 ]; then
  858. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  859. "Could not connect to $host_port."
  860. return 1
  861. fi
  862. return 0
  863. }
  864. export -f wait_for_tcp_port
  865. ## Warning: requires a ``ddb`` matching current database to be checked
  866. wait_for_docker_ip() {
  867. local name=$1 DOCKER_IP= DOCKER_NETWORK= docker_ips= docker_ip= elapsed timeout=10
  868. docker_ip=$(wait_docker_ip "$name" 5) || return 1
  869. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  870. if ! str_is_ipv4 "$DOCKER_IP"; then
  871. err "internal 'wait_docker_ip' did not return a valid IP. Returned IP is '$DOCKER_IP'."
  872. return 1
  873. fi
  874. set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  875. while read-0 port; do
  876. IFS="/" read port type <<<"$port"
  877. [ "$type" == "tcp" ] || continue
  878. wait_for_tcp_port "$DOCKER_NETWORK" "$DOCKER_IP:${port}" || return 17
  879. info "Host/Port $DOCKER_IP:${port} checked ${GREEN}open${NORMAL}."
  880. ## XXXvlab: what to do with more than one port ?
  881. break
  882. done < <(image_exposed_ports_0 "$container_id")
  883. ## Checking direct connection
  884. timeout=120
  885. start=$SECONDS
  886. while true; do
  887. if err=$(echo "$check_command" | ddb 2>&1 >/dev/null); then
  888. break
  889. fi
  890. if ! [[ "$err" == *"the database system is starting up" ]]; then
  891. err "${RED}db connection error${NORMAL}:" \
  892. "Could not connect to db on $DOCKER_IP container's IP."
  893. echo " Note: IP up, TCP ports is(are) open" >&2
  894. if [ "$err" ]; then
  895. echo " Error:" >&2
  896. printf "%s\n" "$err" | prefix " ${RED}!${NORMAL} " >&2
  897. fi
  898. return 18
  899. fi
  900. debug "Got 'database system is starting up' error."
  901. elapsed=$((SECONDS - start))
  902. if ((elapsed > timeout)); then
  903. err "${RED}db connection error${NORMAL}:"\
  904. "Could not connect to db on $DOCKER_IP" \
  905. "container's IP. (IP up, TCP ports is(are) open, sql answer after ${timeout}s)"
  906. return 1
  907. fi
  908. sleep 0.2
  909. done
  910. echo "${DOCKER_NETWORK}:${DOCKER_IP}"
  911. return 0
  912. }
  913. export -f wait_for_docker_ip
  914. docker_add_host_declaration() {
  915. local src_docker=$1 domain=$2 dst_docker=$3 dst_docker_ip= dst_docker_network
  916. dst_docker_ip=$(wait_docker_ip "$dst_docker") || exit 1
  917. IFS=: read dst_docker_ip dst_docker_network <<<"$dst_docker_ip"
  918. docker exec -i "$src_docker" bash <<EOF
  919. if cat /etc/hosts | grep -E "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$" > /dev/null 2>&1; then
  920. sed -ri "s/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$/$dst_docker_ip $domain/g" /etc/hosts
  921. else
  922. echo "$dst_docker_ip $domain" >> /etc/hosts
  923. fi
  924. EOF
  925. }
  926. export -f docker_add_host_declaration
  927. get_running_containers_for_service() {
  928. local service="$1" project="$2"
  929. project=${project:-$PROJECT_NAME}
  930. [ -n "$project" ] || {
  931. err "No project name was defined yet."
  932. return 1
  933. }
  934. docker ps \
  935. --filter label="compose.project=$project" \
  936. --filter label="compose.master-service=$service" \
  937. --format="{{.ID}}"
  938. }
  939. export -f get_running_containers_for_service
  940. get_container_network_ips() {
  941. local container="$1"
  942. docker inspect "$container" \
  943. --format='{{range $key, $val :=.NetworkSettings.Networks}}{{$key}}{{"\x00"}}{{$val.IPAddress}}{{"\x00"}}{{end}}'
  944. }
  945. export -f get_container_network_ips
  946. get_container_network_ip() {
  947. local container="$1"
  948. while read-0 network ip; do
  949. printf "%s\0" "$network" "$ip"
  950. break
  951. done < <(get_container_network_ips "$container")
  952. }
  953. export -f get_container_network_ip
  954. ##
  955. ## Internal Process
  956. ##
  957. get_docker_compose_links() {
  958. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  959. deps master_service master_target_service _relation_name \
  960. target_service _relation_config tech_dep
  961. if [ -z "$service" ]; then
  962. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  963. return 1
  964. fi
  965. if [ -e "$cache_file" ]; then
  966. # debug "$FUNCNAME: cache hit ($*)"
  967. cat "$cache_file"
  968. return 0
  969. fi
  970. master_service=$(get_top_master_service_for_service "$service") || return 1
  971. deps=()
  972. while read-0 _relation_name target_service _relation_config tech_dep; do
  973. master_target_service="$(get_top_master_service_for_service "$target_service")" || return 1
  974. [ "$master_service" == "$master_target_service" ] && continue
  975. type="$(get_service_type "$target_service")" || return 1
  976. [ "$type" == "stub" ] && continue
  977. [ "$type" == "run-once" ] && continue
  978. if [ "$tech_dep" == "reversed" ]; then
  979. deps+=("$(echo -en "$master_target_service:\n links:\n - $master_service")")
  980. elif [[ "$tech_dep" =~ ^(True|true)$ ]]; then
  981. deps+=("$(echo -en "$master_service:\n links:\n - $master_target_service")")
  982. fi
  983. ## XXXvlab: an attempt to add depends_on, but this doesn't work well actually
  984. ## as there's a circular dependency issue. We don't really want the full feature
  985. ## of depends_on, but just to add it as targets when doing an 'up'
  986. # deps+=("$(echo -en "$master_service:\n depends_on:\n - $master_target_service")")
  987. done < <(get_service_relations "$service")
  988. merge_yaml_str "${deps[@]}" | tee "$cache_file" || return 1
  989. if [ "${PIPESTATUS[0]}" != 0 ]; then
  990. rm "$cache_file"
  991. err "Failed to merge YAML from all ${WHITE}links${NORMAL} dependencies."
  992. return 1
  993. fi
  994. }
  995. _get_docker_compose_opts() {
  996. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  997. compose_def master_service docker_compose_opts
  998. if [ -z "$service" ]; then
  999. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  1000. return 1
  1001. fi
  1002. if [ -e "$cache_file" ]; then
  1003. # debug "$FUNCNAME: cache hit ($*)"
  1004. cat "$cache_file"
  1005. return 0
  1006. fi
  1007. compose_def="$(get_compose_service_def "$service")" || return 1
  1008. master_service="$(get_top_master_service_for_service "$service")"
  1009. if docker_compose_opts=$(echo "$compose_def" | shyaml get-value -y "docker-compose" 2>/dev/null); then
  1010. yaml_key_val_str "$master_service" "$docker_compose_opts"
  1011. fi | tee "$cache_file"
  1012. if [ "${PIPESTATUS[0]}" != 0 ]; then
  1013. rm "$cache_file"
  1014. return 1
  1015. fi
  1016. }
  1017. ##
  1018. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  1019. ## Some metadata.yml (of subordinates) will indeed modify other
  1020. ## services than themselves.
  1021. _get_docker_compose_service_mixin() {
  1022. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1023. links_yaml base_mixin links_yaml docker_compose_options \
  1024. charm charm_part
  1025. if [ -z "$service" ]; then
  1026. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  1027. return 1
  1028. fi
  1029. if [ -e "$cache_file" ]; then
  1030. # debug "$FUNCNAME: cache hit ($*)"
  1031. cat "$cache_file"
  1032. return 0
  1033. fi
  1034. type=$(get_service_type "$service") || return 1
  1035. [ "$type" == "stub" ] && return 0
  1036. master_service=$(get_top_master_service_for_service "$service") || {
  1037. err "Failed to get top master service for service $DARKYELLOW$service$NORMAL"
  1038. return 1
  1039. }
  1040. ## The compose part
  1041. base_mixin="$master_service:
  1042. labels:
  1043. - compose.service=$service
  1044. - compose.master-service=${master_service}
  1045. - compose.project=$(get_default_project_name)"
  1046. links_yaml=$(get_docker_compose_links "$service") || return 1
  1047. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  1048. ## the charm part
  1049. charm_part=$(get_docker_compose_mixin_from_metadata "$service") || return 1
  1050. ## Merge results
  1051. if [ "$charm_part" ]; then
  1052. charm_yaml="$(yaml_key_val_str "$master_service" "$charm_part")" || return 1
  1053. merge_yaml_str "$base_mixin" "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  1054. else
  1055. merge_yaml_str "$base_mixin" "$links_yaml" "$docker_compose_options" || return 1
  1056. fi | tee "$cache_file"
  1057. if [ "${PIPESTATUS[0]}" != 0 ]; then
  1058. err "Failed to constitute the base YAML for service '${DARKYELLOW}$service${NORMAL}'"
  1059. rm "$cache_file"
  1060. return 1
  1061. fi
  1062. }
  1063. export -f _get_docker_compose_service_mixin
  1064. ##
  1065. ## Get full `docker-compose.yml` format for all listed services (and
  1066. ## their deps)
  1067. ##
  1068. ## @export
  1069. ## @cache: !system !nofail +stdout
  1070. get_docker_compose () {
  1071. if [ -z "$CHARM_STORE_HASH" ]; then
  1072. err-d "Expected \$CHARM_STORE_HASH to be set."
  1073. return 1
  1074. fi
  1075. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  1076. err-d "Expected \$COMPOSE_YML_CONTENT_HASH to be set."
  1077. return 1
  1078. fi
  1079. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" "$CHARM_STORE_HASH" "$COMPOSE_YML_CONTENT_HASH")" \
  1080. entries services service start docker_compose_services
  1081. if [ -e "$cache_file" ]; then
  1082. # debug "$FUNCNAME: cache hit ($*) $cache_file"
  1083. touch "$cache_file" || return 1
  1084. cp "$cache_file"{,.wip} || return 1
  1085. export _CURRENT_DOCKER_COMPOSE="$cache_file.wip"
  1086. cat "$cache_file" || return 1
  1087. return 0
  1088. fi
  1089. ##
  1090. ## Adding sub services configurations
  1091. ##
  1092. declare -A entries
  1093. start_compilation=$SECONDS
  1094. debug "Compiling 'docker-compose.yml' base for ${DARKYELLOW}$*$NORMAL..."
  1095. for target_service in "$@"; do
  1096. start=$SECONDS
  1097. services=($(get_ordered_service_dependencies "$target_service")) || {
  1098. err "Failed to get dependencies for $DARKYELLOW$target_service$NORMAL"
  1099. return 1
  1100. }
  1101. if [ "$DEBUG" ]; then
  1102. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" \
  1103. "${services[@]::$((${#services[@]} - 1))}" \
  1104. "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  1105. fi
  1106. for service in "${services[@]}"; do
  1107. if [ "${entries[$service]}" ]; then
  1108. ## Prevent double inclusion of same service if this
  1109. ## service is deps of two or more of your
  1110. ## requirements.
  1111. continue
  1112. fi
  1113. ## mark the service as "loaded" as well as it's containers
  1114. ## if this is a subordinate service
  1115. start_service=$SECONDS
  1116. entries[$service]=$(_get_docker_compose_service_mixin "$service") || {
  1117. err "Failed to get service mixin for $DARKYELLOW$service$NORMAL"
  1118. return 1
  1119. }
  1120. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  1121. done
  1122. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  1123. done
  1124. docker_compose_services=$(merge_yaml_str "${entries[@]}") || {
  1125. err "Failed to merge YAML services entries together."
  1126. return 1
  1127. }
  1128. base_v2="version: '2.1'"
  1129. merge_yaml_str "$(yaml_key_val_str "services" "$docker_compose_services")" \
  1130. "$base_v2" > "$cache_file" || return 1
  1131. cp "$cache_file"{,.wip} || return 1
  1132. export _CURRENT_DOCKER_COMPOSE="$cache_file.wip"
  1133. cat "$_CURRENT_DOCKER_COMPOSE" || return 1
  1134. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  1135. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  1136. # debug "$_current_docker_compose"
  1137. }
  1138. export -f get_docker_compose
  1139. _get_compose_service_def_cached () {
  1140. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1141. if [ -e "$cache_file" ]; then
  1142. #debug "$FUNCNAME: STATIC cache hit"
  1143. cat "$cache_file" &&
  1144. touch "$cache_file" || return 1
  1145. return 0
  1146. fi
  1147. value=$(echo "$docker_compose" | shyaml get-value "${service//./\\.}" 2>/dev/null)
  1148. [ "$value" == None ] && value=""
  1149. if ! echo "$value" | shyaml get-value "charm" >/dev/null 2>&1; then
  1150. if charm.exists "$service"; then
  1151. value=$(merge_yaml <(echo "charm: $service") <(echo "$value")) || {
  1152. err "Can't merge YAML infered 'charm: $service' with base ${DARKYELLOW}$service${NORMAL} YAML definition."
  1153. return 1
  1154. }
  1155. else
  1156. err "No ${WHITE}charm${NORMAL} value for service $DARKYELLOW$service$NORMAL" \
  1157. "in compose, nor same name charm found."
  1158. return 1
  1159. fi
  1160. fi
  1161. echo "$value" | tee "$cache_file" || return 1
  1162. # if [ "${PIPESTATUS[0]}" != 0 ]; then
  1163. # rm "$cache_file"
  1164. # return 1
  1165. # fi
  1166. return 0
  1167. # if [ "${PIPESTATUS[0]}" != 0 -o \! -s "$cache_file" ]; then
  1168. # rm "$cache_file"
  1169. # err "PAS OK $service: $value"
  1170. # return 1
  1171. # fi
  1172. }
  1173. export -f _get_compose_service_def_cached
  1174. ## XXXvlab: a lot to be done to cache the results
  1175. get_compose_service_def () {
  1176. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1177. result
  1178. if [ -e "$cache_file" ]; then
  1179. #debug "$FUNCNAME: SESSION cache hit"
  1180. cat "$cache_file" || return 1
  1181. return 0
  1182. fi
  1183. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  1184. docker_compose=$(get_compose_yml_content) || return 1
  1185. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  1186. charm=$(echo "$result" | shyaml get-value charm 2>/dev/null) || return 1
  1187. metadata=$(charm.metadata "$charm") || return 1
  1188. if default_options=$(printf "%s" "$metadata" | shyaml -y -q get-value default-options); then
  1189. default_options=$(yaml_key_val_str "options" "$default_options") || return 1
  1190. result=$(merge_yaml_str "$default_options" "$result") || return 1
  1191. fi
  1192. echo "$result" | tee "$cache_file" || return 1
  1193. }
  1194. export -f get_compose_service_def
  1195. _get_service_charm_cached () {
  1196. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1197. if [ -e "$cache_file" ]; then
  1198. # debug "$FUNCNAME: cache hit $1"
  1199. cat "$cache_file" &&
  1200. touch "$cache_file" || return 1
  1201. return 0
  1202. fi
  1203. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  1204. if [ -z "$charm" ]; then
  1205. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  1206. return 1
  1207. fi
  1208. echo "$charm" | tee "$cache_file" || return 1
  1209. }
  1210. export -f _get_service_charm_cached
  1211. get_service_charm () {
  1212. local service="$1"
  1213. if [ -z "$service" ]; then
  1214. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  1215. return 1
  1216. fi
  1217. service_def=$(get_compose_service_def "$service") || return 1
  1218. _get_service_charm_cached "$service" "$service_def"
  1219. }
  1220. export -f get_service_charm
  1221. ## built above the docker-compose abstraction, so it relies on the
  1222. ## full docker-compose.yml to be already built.
  1223. get_service_def () {
  1224. local service="$1" def
  1225. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  1226. err "${FUNCNAME[0]} is meant to be called after"\
  1227. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  1228. echo " Called by:" >&2
  1229. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  1230. return 1
  1231. fi
  1232. def=$(cat "$_CURRENT_DOCKER_COMPOSE" | shyaml get-value "services.${service//./\\.}" 2>/dev/null)
  1233. if [ -z "$def" ]; then
  1234. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  1235. return 1
  1236. fi
  1237. echo "$def"
  1238. }
  1239. export -f get_service_def
  1240. get_build_hash() {
  1241. local dir="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$1")" hash
  1242. if [ -e "$cache_file" ]; then
  1243. # debug "$FUNCNAME: cache hit ($*)"
  1244. cat "$cache_file"
  1245. return 0
  1246. fi
  1247. ## Check that there's a Dockerfile in this directory
  1248. if [ ! -e "$dir/Dockerfile" ]; then
  1249. err "No 'Dockerfile' found in '$dir'."
  1250. return 1
  1251. fi
  1252. ## use find to md5sum all files in the directory and make a final hash
  1253. hash=$(set -o pipefail; cd "$dir"; env -i find "." -type f -exec md5sum {} \; |
  1254. sort | md5sum | awk '{print $1}') || {
  1255. err "Failed to get hash for '$dir'."
  1256. return 1
  1257. }
  1258. printf "%s" "$hash" | tee "$cache_file"
  1259. return $?
  1260. }
  1261. export -f get_build_hash
  1262. ### Query/Get cached image from registry
  1263. ##
  1264. ## Returns on stdout the name of the image if found, or an empty string if not
  1265. cache:image:registry:get() {
  1266. local charm="$1" hash="$2" service="$3"
  1267. local charm_image_name="cache/charm/$charm"
  1268. local charm_image="$charm_image_name:$hash"
  1269. Elt "pulling ${DARKPINK}$charm${NORMAL} image from $COMPOSE_DOCKER_REGISTRY" >&2
  1270. if out=$(docker pull "$COMPOSE_DOCKER_REGISTRY/$charm_image" 2>&1); then
  1271. docker tag "$COMPOSE_DOCKER_REGISTRY/$charm_image" "$charm_image" || {
  1272. err "Failed set image '$COMPOSE_DOCKER_REGISTRY/$charm_image' as '$charm_image'" \
  1273. "for ${DARKYELLOW}$service${NORMAL}."
  1274. return 1
  1275. }
  1276. print_info "found" >&2
  1277. print_status success >&2
  1278. Feed >&2
  1279. printf "%s" "$charm_image" | tee "$cache_file"
  1280. return $?
  1281. fi
  1282. if [[ "$out" != *"manifest unknown"* ]] && [[ "$out" != *"not found"* ]]; then
  1283. print_status failure >&2
  1284. Feed >&2
  1285. err "Failed to pull image '$COMPOSE_DOCKER_REGISTRY/$charm_image'" \
  1286. "for ${DARKYELLOW}$service${NORMAL}:"
  1287. e "$out"$'\n' | prefix " ${GRAY}|${NORMAL} " >&2
  1288. return 1
  1289. fi
  1290. print_info "not found" >&2
  1291. if test "$type_method" = "long"; then
  1292. __status="[${NOOP}ABSENT${NORMAL}]"
  1293. else
  1294. echo -n "${NOOP}"
  1295. shift; shift;
  1296. echo -n "$*${NORMAL}"
  1297. fi >&2
  1298. Feed >&2
  1299. }
  1300. export -f cache:image:registry:get
  1301. ### Store cached image on registry
  1302. ##
  1303. ## Returns nothing
  1304. cache:image:registry:put() {
  1305. if [ -n "$COMPOSE_DOCKER_REGISTRY" ] && [ -n "$COMPOSE_PUSH_TO_REGISTRY" ]; then
  1306. local charm="$1" hash="$2" service="$3"
  1307. local charm_image_name="cache/charm/$charm"
  1308. local charm_image="$charm_image_name:$hash"
  1309. Wrap -d "pushing ${DARKPINK}$charm${NORMAL} image to $COMPOSE_DOCKER_REGISTRY" <<EOF || return 1
  1310. docker tag "$charm_image" "$COMPOSE_DOCKER_REGISTRY/$charm_image" &&
  1311. docker push "$COMPOSE_DOCKER_REGISTRY/$charm_image"
  1312. EOF
  1313. fi >&2
  1314. }
  1315. export -f cache:image:registry:put
  1316. ### Produce docker cached charm image 'cache/charm/$charm:$hash'
  1317. ##
  1318. ## Either by fetching it from a registry or by building it from a
  1319. ## Dockerfile.
  1320. cache:image:produce() {
  1321. local type="$1" src="$2" charm="$3" hash="$4" service="$5"
  1322. local charm_image_name="cache/charm/$charm"
  1323. local charm_image="$charm_image_name:$hash"
  1324. case "$type" in
  1325. fetch)
  1326. local specified_image="$src"
  1327. ## will not pull upstream image if already present locally
  1328. if ! docker_has_image "${specified_image}"; then
  1329. if ! out=$(docker pull "${specified_image}" 2>&1); then
  1330. err "Failed to pull image '$specified_image' for ${DARKYELLOW}$service${NORMAL}:"
  1331. echo "$out" | prefix " | " >&2
  1332. return 1
  1333. fi
  1334. fi
  1335. # specified_image_id=$(docker_image_id "$specified_image") || return 1
  1336. # charm_image_id=
  1337. # if docker_has_image "${image_dst}"; then
  1338. # charm_image_id=$(docker_image_id "${image_dst}") || return 1
  1339. # fi
  1340. # if [ "$specified_image_id" != "$charm_image_id" ]; then
  1341. docker tag "$specified_image" "${charm_image}" || return 1
  1342. # fi
  1343. ;;
  1344. build)
  1345. local service_build="$src"
  1346. build_opts=()
  1347. if [ "$COMPOSE_ACTION" == "build" ]; then
  1348. while read-0 arg; do
  1349. case "$arg" in
  1350. -t|--tag)
  1351. ## XXXvlab: doesn't seem to be actually a valid option
  1352. if [ -n "$COMPOSE_PUSH_TO_REGISTRY" ]; then
  1353. err "You can't use -t|--tag option when pushing to a registry."
  1354. exit 1
  1355. fi
  1356. has_named_image=true
  1357. read-0 val ## should always be okay because already checked
  1358. build_opts+=("$arg" "$val")
  1359. ;;
  1360. --help|-h)
  1361. docker-compose "$action" --help |
  1362. filter_docker_compose_help_message >&2
  1363. exit 0
  1364. ;;
  1365. --*|-*)
  1366. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  1367. read-0 value
  1368. build_opts+=("$arg" "$value")
  1369. shift
  1370. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  1371. build_opts+=("$arg")
  1372. else
  1373. err "Unexpected error while parsing a second time the build arguments."
  1374. fi
  1375. ;;
  1376. *)
  1377. ## Already parsed
  1378. build_opts+=("$arg")
  1379. ;;
  1380. esac
  1381. done < <(cla.normalize "${action_opts[@]}")
  1382. fi
  1383. if [ -z "$has_named_image" ]; then
  1384. build_opts+=(-t "${charm_image}")
  1385. fi
  1386. Wrap -v -d "Building ${DARKPINK}$charm${NORMAL}:$hash image" -- \
  1387. docker build "$service_build" -t "${charm_image}" "${build_opts[@]}" >&2 || {
  1388. err "Failed to build image '${charm_image}' for ${DARKYELLOW}$service${NORMAL}."
  1389. return 1
  1390. }
  1391. if [ -n "$has_named_image" ]; then
  1392. exit 0
  1393. fi
  1394. ;;
  1395. *)
  1396. err "Unknown type '$type'."
  1397. return 1
  1398. ;;
  1399. esac
  1400. }
  1401. export -f cache:image:produce
  1402. ## Will modify current $_CURRENT_DOCKER_COMPOSE file
  1403. service_ensure_image_ready() {
  1404. if [ -z "$COMBINED_HASH" ]; then
  1405. err "Expected \$COMBINED_HASH to be set."
  1406. return 1
  1407. fi
  1408. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$COMBINED_HASH" \
  1409. master_service service_def service_image service_build service_dockerfile image \
  1410. specified_image specified_image_id charm_image_name hash \
  1411. service_quoted
  1412. if [ -e "$cache_file" ]; then
  1413. #debug "$FUNCNAME: cache hit ($*)"
  1414. touch "$cache_file" || return 1
  1415. cat "$cache_file"
  1416. return 0
  1417. fi
  1418. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  1419. err "${FUNCNAME[0]} is meant to be called after"\
  1420. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  1421. echo " Called by:" >&2
  1422. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  1423. return 1
  1424. fi
  1425. master_service="$(get_top_master_service_for_service "$service")" || {
  1426. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  1427. return 1
  1428. }
  1429. if [ "$master_service" != "$service" ]; then
  1430. image=$(service_ensure_image_ready "$master_service") || return 1
  1431. printf "%s" "$image" | tee "$cache_file"
  1432. return $?
  1433. fi
  1434. ## check if \$_CURRENT_DOCKER_COMPOSE's service def is already correctly setup
  1435. local charm="$(get_service_charm "$service")" || return 1
  1436. local charm_image_name="cache/charm/$charm" || return 1
  1437. local service_def="$(get_service_def "$service")" || {
  1438. err "Could not get docker-compose service definition for $DARKYELLOW$service$NORMAL."
  1439. return 1
  1440. }
  1441. local service_quoted=${service//./\\.}
  1442. if specified_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null); then
  1443. if [ "$specified_image" == "$charm_image_name"* ]; then
  1444. ## Assume we already did the change
  1445. printf "%s" "$specified_image" | tee "$cache_file"
  1446. return 0
  1447. fi
  1448. if [[ "$specified_image" == "${COMPOSE_DOCKER_REGISTRY}/"* ]]; then
  1449. if ! docker_has_image "${specified_image}"; then
  1450. Wrap "${wrap_opts[@]}" \
  1451. -v -d "pulling ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" -- \
  1452. docker pull "${specified_image}" >&2 || return 1
  1453. else
  1454. if [ -n "$DEBUG" ]; then
  1455. Elt "using local ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" >&2
  1456. print_status noop >&2
  1457. Feed >&2
  1458. fi
  1459. fi
  1460. ## Already on the cache server
  1461. printf "%s" "$specified_image" | tee "$cache_file"
  1462. return 0
  1463. fi
  1464. src="$specified_image"
  1465. hash=$(echo "$specified_image" | md5sum | cut -f 1 -d " ") || return 1
  1466. type=fetch
  1467. ## replace image by charm image
  1468. yq -i ".services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1469. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1470. else
  1471. if ! src=$(echo "$service_def" | shyaml get-value build 2>/dev/null); then
  1472. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  1473. echo "$service_def" >&2
  1474. return 1
  1475. fi
  1476. ## According to https://stackoverflow.com/questions/32230577 , if there's a build,
  1477. ## then the built image will get name ${project}_${service}
  1478. hash=$(get_build_hash "$src") || return 1
  1479. type=build
  1480. ## delete build key from service_def and add image to charm_image_name
  1481. yq -i "del(.services.[\"${service_quoted}\"].build) |
  1482. .services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1483. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1484. fi
  1485. if [ "$COMPOSE_ACTION" != "build" ] && docker_has_image "${charm_image_name}:${hash}"; then
  1486. if [ -n "$DEBUG" ]; then
  1487. Elt "using ${DARKPINK}$charm${NORMAL}'s image from local cache" >&2
  1488. print_status noop >&2
  1489. Feed >&2
  1490. fi
  1491. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1492. printf "%s" "${charm_image_name}:${hash}" | tee "$cache_file"
  1493. return $?
  1494. fi
  1495. ## Can we pull it ? Let's check on $COMPOSE_DOCKER_REGISTRY
  1496. if [ "$COMPOSE_ACTION" != "build" ] && [ -n "$COMPOSE_DOCKER_REGISTRY" ]; then
  1497. img=$(cache:image:registry:get "$charm" "$hash" "$service") || {
  1498. err "Failed to get image '$charm_image_name:$hash' from registry for ${DARKYELLOW}$service${NORMAL}."
  1499. return 1
  1500. }
  1501. [ -n "$img" ] && {
  1502. printf "%s" "$img" | tee "$cache_file"
  1503. return $?
  1504. }
  1505. fi
  1506. cache:image:produce "$type" "$src" "$charm" "$hash" "$service" || return 1
  1507. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1508. printf "%s" "${charm_image_name}:$hash" | tee "$cache_file"
  1509. return $?
  1510. }
  1511. export -f service_ensure_image_ready
  1512. get_charm_relation_def () {
  1513. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1514. relation_def metadata
  1515. if [ -e "$cache_file" ]; then
  1516. # debug "$FUNCNAME: cache hit ($*)"
  1517. cat "$cache_file"
  1518. return 0
  1519. fi
  1520. metadata="$(charm.metadata "$charm")" || return 1
  1521. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  1522. echo "$relation_def" | tee "$cache_file"
  1523. }
  1524. export -f get_charm_relation_def
  1525. get_charm_tech_dep_orientation_for_relation() {
  1526. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1527. relation_def value
  1528. if [ -e "$cache_file" ]; then
  1529. # debug "$FUNCNAME: cache hit ($*)"
  1530. cat "$cache_file"
  1531. return 0
  1532. fi
  1533. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  1534. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1535. value=${value:-True}
  1536. printf "%s" "$value" | tee "$cache_file"
  1537. }
  1538. export -f get_charm_tech_dep_orientation_for_relation
  1539. get_service_relation_tech_dep() {
  1540. local service="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1541. charm tech_dep
  1542. if [ -e "$cache_file" ]; then
  1543. # debug "$FUNCNAME: cache hit ($*)"
  1544. cat "$cache_file"
  1545. return 0
  1546. fi
  1547. charm=$(get_service_charm "$service") || return 1
  1548. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$charm" "$relation_name")" || return 1
  1549. printf "%s" "$tech_dep" | tee "$cache_file"
  1550. }
  1551. export -f get_service_relation_tech_dep
  1552. ##
  1553. ## Use compose file to get deps, and relation definition in metadata.yml
  1554. ## for tech-dep attribute.
  1555. get_service_deps() {
  1556. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")"
  1557. if [ -e "$cache_file" ]; then
  1558. # debug "$FUNCNAME: cache hit ($*)"
  1559. cat "$cache_file"
  1560. return 0
  1561. fi
  1562. (
  1563. set -o pipefail
  1564. get_service_relations "$service" | \
  1565. while read-0 relation_name target_service _relation_config tech_dep; do
  1566. echo "$target_service"
  1567. done | tee "$cache_file"
  1568. ) || return 1
  1569. }
  1570. export -f get_service_deps
  1571. ## XXXvlab: cache was disabled because improper. Indeed, this needs to cache
  1572. ## 'depths' full state. Second, it should be
  1573. _rec_get_depth() {
  1574. local elt=$1 dep deps max
  1575. [ "${depths[$elt]}" ] && return 0
  1576. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -pA depths)" "$GLOBAL_ALL_RELATIONS_HASH")"
  1577. if [ -e "$cache_file.depths" ]; then
  1578. #debug "$FUNCNAME: cache hit ($*) - $cache_file.depths"
  1579. while read-0 k v; do
  1580. depths["$k"]="$v"
  1581. done < "$cache_file.depths"
  1582. while read-0 k v; do
  1583. visited["$k"]="$v"
  1584. done < "$cache_file.visited"
  1585. return 0
  1586. fi
  1587. visited[$elt]=1
  1588. #debug "Setting visited[$elt]"
  1589. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1590. deps=$(get_service_deps "$elt") || {
  1591. debug "Failed get_service_deps $elt"
  1592. return 1
  1593. }
  1594. # debug "$elt deps are:" $deps
  1595. max=0
  1596. for dep in $deps; do
  1597. [ "${visited[$dep]}" ] && {
  1598. #debug "Already computing $dep"
  1599. continue
  1600. }
  1601. _rec_get_depth "$dep" || return 1
  1602. #debug "Requesting depth[$dep]"
  1603. if (( ${depths[$dep]} > max )); then
  1604. max="${depths[$dep]}"
  1605. fi
  1606. done
  1607. # debug "Setting depth[$elt] to $((max + 1))"
  1608. depths[$elt]=$((max + 1))
  1609. array_kv_to_stdin depths > "$cache_file.depths"
  1610. array_kv_to_stdin visited > "$cache_file.visited"
  1611. # debug "DEPTHS: $(declare -pA depths)"
  1612. # debug "$FUNCNAME: caching hit ($*) - $cache_file"
  1613. }
  1614. export -f _rec_get_depth
  1615. get_ordered_service_dependencies() {
  1616. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")" \
  1617. i value key heads depths visited
  1618. if [ -e "$cache_file" ]; then
  1619. # debug "$FUNCNAME: cache hit ($*)"
  1620. cat "$cache_file"
  1621. return 0
  1622. fi
  1623. #debug "Figuring ordered deps of $DARKYELLOW${services[@]}$NORMAL"
  1624. if [ -z "${services[*]}" ]; then
  1625. return 0
  1626. # print_syntax_error "$FUNCNAME: no arguments"
  1627. # return 1
  1628. fi
  1629. declare -A depths
  1630. declare -A visited
  1631. heads=("${services[@]}")
  1632. while [ "${#heads[@]}" != 0 ]; do
  1633. array_pop heads head
  1634. _rec_get_depth "$head" || return 1
  1635. done
  1636. i=0
  1637. while [ "${#depths[@]}" != 0 ]; do
  1638. for key in "${!depths[@]}"; do
  1639. value="${depths[$key]}"
  1640. if [ "$value" == "$i" ]; then
  1641. echo "$key"
  1642. unset depths[$key]
  1643. fi
  1644. done
  1645. ((i++))
  1646. done | tee "$cache_file"
  1647. }
  1648. export -f get_ordered_service_dependencies
  1649. ## Modify $_CURRENT_DOCKER_COMPOSE file, and fills cache
  1650. run_service_acquire_images () {
  1651. local service subservice subservices loaded
  1652. _CURRENT_DOCKER_COMPOSE_HASH=$(hash_get < "$_CURRENT_DOCKER_COMPOSE")
  1653. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" "$_CURRENT_DOCKER_COMPOSE_HASH")"
  1654. if [ -e "$cache_file" ]; then
  1655. # debug "$FUNCNAME: cache hit ($*)"
  1656. touch "$cache_file" || return 1
  1657. cp "$cache_file" "$_CURRENT_DOCKER_COMPOSE" || return 1
  1658. return 0
  1659. fi
  1660. declare -A loaded
  1661. for service in "$@"; do
  1662. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1663. for subservice in $subservices; do
  1664. if [ "${loaded[$subservice]}" ]; then
  1665. ## Prevent double inclusion of same service if this
  1666. ## service is deps of two or more of your
  1667. ## requirements.
  1668. continue
  1669. fi
  1670. type=$(get_service_type "$subservice") || return 1
  1671. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1672. if [ "$type" != "stub" ]; then
  1673. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1674. fi
  1675. loaded[$subservice]=1
  1676. done
  1677. done
  1678. cp "$_CURRENT_DOCKER_COMPOSE" "$cache_file" || return 1
  1679. return 0
  1680. }
  1681. run_service_hook () {
  1682. local action="$1" service subservice subservices loaded
  1683. shift
  1684. declare -A loaded
  1685. for service in "$@"; do
  1686. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1687. for subservice in $subservices; do
  1688. if [ "${loaded[$subservice]}" ]; then
  1689. ## Prevent double inclusion of same service if this
  1690. ## service is deps of two or more of your
  1691. ## requirements.
  1692. continue
  1693. fi
  1694. charm=$(get_service_charm "$subservice") || return 1
  1695. charm.has_hook "$charm" "$action" >/dev/null || continue
  1696. type=$(get_service_type "$subservice") || return 1
  1697. PROJECT_NAME=$(get_default_project_name) || return 1
  1698. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1699. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1700. if [ "$type" != "stub" ]; then
  1701. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1702. fi
  1703. Wrap "${wrap_opts[@]}" -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1704. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1705. export SERVICE_NAME=$subservice
  1706. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1707. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1708. export CHARM_NAME="$charm"
  1709. export PROJECT_NAME="$PROJECT_NAME"
  1710. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1711. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1712. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1713. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1714. charm.run_hook "local" "$charm" "$action"
  1715. EOF
  1716. loaded[$subservice]=1
  1717. done
  1718. done
  1719. return 0
  1720. }
  1721. host_resource_get() {
  1722. local location="$1" cfg="$2"
  1723. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1724. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1725. return 1
  1726. }
  1727. if fn.exists host_resource_get_$type; then
  1728. host_resource_get_$type "$location" "$cfg"
  1729. else
  1730. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1731. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1732. "$DARKYELLOW$subservice$NORMAL config."
  1733. return 1
  1734. fi
  1735. }
  1736. export -f host_resource_get
  1737. host_resource_get_git() {
  1738. local location="$1" cfg="$2" branch parent url
  1739. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1740. branch=${branch:-master}
  1741. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1742. parent="$(dirname "$location")"
  1743. (
  1744. mkdir -p "$parent" && cd "$parent" &&
  1745. git clone -b "$branch" "$url" "$(basename "$location")"
  1746. ) || return 1
  1747. }
  1748. export -f host_resource_get_git
  1749. host_resource_get_git-sub() {
  1750. local location="$1" cfg="$2" branch parent url
  1751. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1752. branch=${branch:-master}
  1753. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1754. parent="$(dirname "$location")"
  1755. (
  1756. mkdir -p "$parent" && cd "$parent" &&
  1757. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1758. ) || return 1
  1759. }
  1760. export -f host_resource_get_git-sub
  1761. setup_host_resource () {
  1762. local subservice="$1" service_def location get cfg
  1763. service_def=$(get_compose_service_def "$subservice") || return 1
  1764. while read-0 location cfg; do
  1765. ## XXXvlab: will it be a git resources always ?
  1766. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1767. err "Hum, location '$location' does not seem to be a git directory."
  1768. return 1
  1769. fi
  1770. if [ -d "$location" ]; then
  1771. info "host resource '$location' already set up."
  1772. continue
  1773. fi
  1774. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1775. if [ -z "$get" ]; then
  1776. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1777. "specified for $DARKYELLOW$subservice$NORMAL."
  1778. return 1
  1779. fi
  1780. host_resource_get "$location" "$get" || return 1
  1781. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1782. }
  1783. export -f setup_host_resource
  1784. setup_host_resources () {
  1785. local service subservices subservice loaded
  1786. declare -A loaded
  1787. for service in "$@"; do
  1788. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1789. for subservice in $subservices; do
  1790. if [ "${loaded[$subservice]}" ]; then
  1791. ## Prevent double inclusion of same service if this
  1792. ## service is deps of two or more of your
  1793. ## requirements.
  1794. continue
  1795. fi
  1796. setup_host_resource "$subservice" || return 1
  1797. loaded[$subservice]=1
  1798. done
  1799. done
  1800. return 0
  1801. }
  1802. export -f setup_host_resources
  1803. ## Works on stdin
  1804. cfg-get-value () {
  1805. local key="$1" out
  1806. if [ -z "$key" ]; then
  1807. yaml_get_interpret || return 1
  1808. return 0
  1809. fi
  1810. if ! out=$(shyaml -y get-value "$key" 2>/dev/null); then
  1811. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1812. return 1
  1813. fi
  1814. printf "%s\n" "$out" | yaml_get_interpret
  1815. }
  1816. export -f cfg-get-value
  1817. relation-get () {
  1818. if [ -z "$RELATION_DATA_FILE" ]; then
  1819. err-d "$FUNCNAME: var \$RELATION_DATA_FILE is not set."
  1820. return 1
  1821. fi
  1822. cfg-get-value "$1" < "$RELATION_DATA_FILE"
  1823. }
  1824. export -f relation-get
  1825. expand_vars() {
  1826. local unlikely_prefix="UNLIKELY_PREFIX"
  1827. content=$(cat -)
  1828. ## find first identifier not in content
  1829. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1830. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1831. size_prefix="${#unlikely_prefix}"
  1832. first_matching=$(echo "$remaining_lines" |
  1833. grep -v "^$unlikely_prefix$" |
  1834. uniq -w "$((size_prefix + 1))" -c |
  1835. sort -rn |
  1836. head -n 1)
  1837. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1838. first_matching="${first_matching#* }"
  1839. next_char=${first_matching:$size_prefix:1}
  1840. if [ "$next_char" != "0" ]; then
  1841. unlikely_prefix+="0"
  1842. else
  1843. unlikely_prefix+="1"
  1844. fi
  1845. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1846. done
  1847. eval "cat <<$unlikely_prefix
  1848. $content
  1849. $unlikely_prefix"
  1850. }
  1851. export -f expand_vars
  1852. yaml_get_interpret() {
  1853. local content tag
  1854. content=$(cat -)
  1855. tag=$(echo "$content" | shyaml get-type) || return 1
  1856. content=$(echo "$content" | shyaml get-value) || return 1
  1857. if ! [ "${tag:0:1}" == "!" ]; then
  1858. echo "$content" || return 1
  1859. return 0
  1860. fi
  1861. case "$tag" in
  1862. "!bash-stdout")
  1863. echo "$content" | bash || {
  1864. err "shell code didn't end with errorlevel 0"
  1865. return 1
  1866. }
  1867. ;;
  1868. "!var-expand")
  1869. echo "$content" | expand_vars || {
  1870. err "shell expansion failed"
  1871. return 1
  1872. }
  1873. ;;
  1874. "!file-content")
  1875. source=$(echo "$content" | expand_vars) || {
  1876. err "shell expansion failed"
  1877. return 1
  1878. }
  1879. cat "$source" || return 1
  1880. ;;
  1881. *)
  1882. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1883. return 1
  1884. ;;
  1885. esac
  1886. }
  1887. export -f yaml_get_interpret
  1888. options-get () {
  1889. local key="$1" out
  1890. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1891. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1892. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1893. return 1
  1894. fi
  1895. echo "$out" | yaml_get_interpret
  1896. }
  1897. export -f options-get
  1898. relation-base-compose-get () {
  1899. local key="$1" out
  1900. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1901. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1902. return 1
  1903. fi
  1904. echo "$out" | yaml_get_interpret
  1905. }
  1906. export -f relation-base-compose-get
  1907. relation-target-compose-get () {
  1908. local key="$1" out
  1909. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1910. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1911. return 1
  1912. fi
  1913. echo "$out" | yaml_get_interpret
  1914. }
  1915. export -f relation-target-compose-get
  1916. relation-set () {
  1917. local key="$1" value="$2"
  1918. if [ -z "$RELATION_DATA_FILE" ]; then
  1919. err "$FUNCNAME: relation does not seems to be correctly setup."
  1920. return 1
  1921. fi
  1922. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1923. err "$FUNCNAME: can't read relation's data." >&2
  1924. return 1
  1925. fi
  1926. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1927. }
  1928. export -f relation-set
  1929. _config_merge() {
  1930. local config_filename="$1" mixin="$2"
  1931. touch "$config_filename" &&
  1932. merge_yaml "$config_filename" "$mixin" > "$config_filename.tmp" || return 1
  1933. mv "$config_filename.tmp" "$config_filename"
  1934. }
  1935. export -f _config_merge
  1936. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1937. config-add() {
  1938. local metadata="$1"
  1939. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1940. }
  1941. export -f config-add
  1942. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1943. init-config-add() {
  1944. local metadata="$1"
  1945. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1946. <(yaml_key_val_str "services" "$metadata")
  1947. }
  1948. export -f init-config-add
  1949. docker_get_uid() {
  1950. local service="$1" user="$2" uid
  1951. uid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"") || {
  1952. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1953. return 1
  1954. }
  1955. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid'"
  1956. echo "$uid"
  1957. }
  1958. export -f docker_get_uid
  1959. docker_get_uid_gid() {
  1960. local service="$1" user="$2" group="$3" uid
  1961. uid_gid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"; id -g \"$group\"") || {
  1962. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1963. return 1
  1964. }
  1965. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid_gid'"
  1966. echo "$uid_gid"
  1967. }
  1968. export -f docker_get_uid_gid
  1969. logstdout() {
  1970. local name="$1"
  1971. sed -r 's%^%'"${name}"'> %g'
  1972. }
  1973. export -f logstdout
  1974. logstderr() {
  1975. local name="$1"
  1976. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1977. }
  1978. export -f logstderr
  1979. _run_service_relation () {
  1980. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1981. local errlvl
  1982. charm=$(get_service_charm "$service") || return 1
  1983. target_charm=$(get_service_charm "$target_service") || return 1
  1984. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1985. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1986. [ -n "$base_script_name" ] || [ -n "$target_script_name" ] || return 0
  1987. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1988. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1989. export BASE_SERVICE_NAME=$service
  1990. export BASE_CHARM_NAME=$charm
  1991. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1992. export TARGET_SERVICE_NAME=$target_service
  1993. export TARGET_CHARM_NAME=$target_charm
  1994. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1995. export RELATION_DATA_FILE
  1996. target_errlvl=0
  1997. if [ -z "$target_script_name" ]; then
  1998. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1999. else
  2000. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  2001. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  2002. RELATION_CONFIG="$relation_dir/config_provider"
  2003. type=$(get_service_type "$target_service") || return 1
  2004. if [ "$type" != "stub" ]; then
  2005. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$target_service") || return 1
  2006. fi
  2007. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  2008. {
  2009. (
  2010. SERVICE_NAME=$target_service
  2011. SERVICE_DATASTORE="$DATASTORE/$target_service"
  2012. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  2013. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  2014. charm.run_relation_hook local "$target_charm" "$relation_name" relation-joined
  2015. echo "$?" > "$relation_dir/target_errlvl"
  2016. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  2017. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  2018. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  2019. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  2020. "failed before outputing an errorlevel."
  2021. ((target_errlvl |= "1" ))
  2022. }
  2023. if [ -e "$RELATION_CONFIG" ]; then
  2024. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  2025. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  2026. rm "$RELATION_CONFIG"
  2027. ((target_errlvl |= "$?"))
  2028. fi
  2029. fi
  2030. if [ "$target_errlvl" == 0 ]; then
  2031. errlvl=0
  2032. if [ "$base_script_name" ]; then
  2033. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  2034. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  2035. RELATION_CONFIG="$relation_dir/config_providee"
  2036. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  2037. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$service") || return 1
  2038. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  2039. {
  2040. (
  2041. SERVICE_NAME=$service
  2042. SERVICE_DATASTORE="$DATASTORE/$service"
  2043. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2044. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  2045. charm.run_relation_hook local "$charm" "$relation_name" relation-joined
  2046. echo "$?" > "$relation_dir/errlvl"
  2047. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  2048. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2049. errlvl="$(cat "$relation_dir/errlvl")" || {
  2050. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  2051. "failed before outputing an errorlevel."
  2052. ((errlvl |= "1" ))
  2053. }
  2054. if [ -e "$RELATION_CONFIG" ]; then
  2055. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  2056. rm "$RELATION_CONFIG"
  2057. ((errlvl |= "$?" ))
  2058. fi
  2059. if [ "$errlvl" != 0 ]; then
  2060. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  2061. fi
  2062. else
  2063. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  2064. fi
  2065. else
  2066. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  2067. fi
  2068. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  2069. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  2070. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  2071. return 0
  2072. else
  2073. return 1
  2074. fi
  2075. }
  2076. export -f _run_service_relation
  2077. _get_compose_relations_cached () {
  2078. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2079. relation_name relation_def target_service
  2080. if [ -e "$cache_file" ]; then
  2081. #debug "$FUNCNAME: STATIC cache hit $1"
  2082. cat "$cache_file" &&
  2083. touch "$cache_file" || return 1
  2084. return 0
  2085. fi
  2086. (
  2087. set -o pipefail
  2088. if [ "$compose_service_def" ]; then
  2089. while read-0 relation_name relation_def; do
  2090. ## XXXvlab: could we use braces here instead of parenthesis ?
  2091. (
  2092. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  2093. "str")
  2094. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  2095. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2096. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  2097. ;;
  2098. "sequence")
  2099. while read-0 target_service; do
  2100. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2101. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  2102. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  2103. ;;
  2104. "struct")
  2105. while read-0 target_service relation_config; do
  2106. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2107. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  2108. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  2109. ;;
  2110. esac
  2111. ) </dev/null >> "$cache_file" || return 1
  2112. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  2113. fi
  2114. )
  2115. if [ "$?" != 0 ]; then
  2116. err "Error while looking for compose relations."
  2117. rm -f "$cache_file" ## no cache
  2118. return 1
  2119. fi
  2120. [ -e "$cache_file" ] && cat "$cache_file"
  2121. return 0
  2122. }
  2123. export -f _get_compose_relations_cached
  2124. get_compose_relations () {
  2125. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2126. compose_def
  2127. if [ -e "$cache_file" ]; then
  2128. #debug "$FUNCNAME: SESSION cache hit $1"
  2129. cat "$cache_file"
  2130. return 0
  2131. fi
  2132. compose_def="$(get_compose_service_def "$service")" || return 1
  2133. _get_compose_relations_cached "$compose_def" > "$cache_file"
  2134. if [ "$?" != 0 ]; then
  2135. rm -f "$cache_file" ## no cache
  2136. return 1
  2137. fi
  2138. cat "$cache_file"
  2139. }
  2140. export -f get_compose_relations
  2141. get_all_services() {
  2142. local services compose_yml_services service
  2143. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2144. err-d "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2145. return 1
  2146. fi
  2147. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$GLOBAL_ALL_RELATIONS_HASH" "$(declare -f "$FUNCNAME")")" \
  2148. s rn ts rc td services service
  2149. if [ -e "$cache_file" ]; then
  2150. #debug "$FUNCNAME: cache hit $1"
  2151. cat "$cache_file"
  2152. return 0
  2153. fi
  2154. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2155. err-d "Can't access global \$GLOBAL_ALL_RELATIONS"
  2156. return 1
  2157. fi
  2158. declare -A services
  2159. while read-0 s _ ts _ _; do
  2160. for service in "$s" "$ts"; do
  2161. [ "${services[$service]}" ] && continue
  2162. services["$service"]=1
  2163. echo "$service"
  2164. done
  2165. done < "$GLOBAL_ALL_RELATIONS" > "$cache_file.wip"
  2166. compose_yml_services=($(compose:yml:root:services)) || return 1
  2167. for service in "${compose_yml_services[@]}"; do
  2168. [ "${services[$service]}" ] && continue
  2169. services["$service"]=1
  2170. echo "$service"
  2171. done >> "$cache_file.wip"
  2172. mv "$cache_file"{.wip,} || return 1
  2173. cat "$cache_file"
  2174. }
  2175. export -f get_all_services
  2176. get_service_relations () {
  2177. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")" \
  2178. s rn ts rc td
  2179. if [ -e "$cache_file" ]; then
  2180. #debug "$FUNCNAME: SESSION cache hit $1"
  2181. cat "$cache_file"
  2182. return 0
  2183. fi
  2184. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2185. err-d "Can't access global \$GLOBAL_ALL_RELATIONS"
  2186. return 1
  2187. fi
  2188. while read-0 s rn ts rc td; do
  2189. [[ "$s" == "$service" ]] || continue
  2190. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  2191. done < <(cat "$GLOBAL_ALL_RELATIONS") > "$cache_file"
  2192. cat "$cache_file"
  2193. }
  2194. export -f get_service_relations
  2195. get_service_relation() {
  2196. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  2197. rn ts rc td
  2198. if [ -e "$cache_file" ]; then
  2199. #debug "$FUNCNAME: SESSION cache hit $1"
  2200. cat "$cache_file"
  2201. return 0
  2202. fi
  2203. while read-0-err E rn ts rc td; do
  2204. [ "$relation" == "$rn" ] && {
  2205. printf "%s\0" "$ts" "$rc" "$td"
  2206. break
  2207. }
  2208. done < <(p-err get_service_relations "$service") > "${cache_file}.wip"
  2209. if [ "$?" != 0 ]; then
  2210. return 1
  2211. fi
  2212. if [ "$E" != 0 ]; then
  2213. return 1
  2214. fi
  2215. mv "${cache_file}"{.wip,} || return 1
  2216. cat "$cache_file"
  2217. }
  2218. export -f get_service_relation
  2219. ## From a service and a relation, get all relations targeting given
  2220. ## service with given relation.
  2221. ##
  2222. ## Returns a NUL separated list of couple of:
  2223. ## (base_service, relation_config)
  2224. ##
  2225. get_service_incoming_relations() {
  2226. if [ -z "$SUBSET_ALL_RELATIONS_HASH" ]; then
  2227. err-d "Expected \$SUBSET_ALL_RELATIONS_HASH to be set."
  2228. return 1
  2229. fi
  2230. local service="$1" relation="$2" \
  2231. cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$SUBSET_ALL_RELATIONS_HASH")" \
  2232. s rn ts rc td
  2233. if [ -e "$cache_file" ]; then
  2234. #debug "$FUNCNAME: SESSION cache hit $1"
  2235. cat "$cache_file"
  2236. return 0
  2237. fi
  2238. while read-0 s rn ts rc _td; do
  2239. [[ "$ts" == "$service" ]] || continue
  2240. [[ "$rn" == "$relation" ]] || continue
  2241. relation_data_file=$(get_relation_data_file "$s" "$ts" "$rn" "$rc") || return 1
  2242. printf "%s\0" "$s" "$(cat "$relation_data_file")" || return 1
  2243. debug "Found relation $rn from $s to $ts" >&2
  2244. done < "$SUBSET_ALL_RELATIONS" > "$cache_file.wip"
  2245. mv "$cache_file"{.wip,} || return 1
  2246. cat "$cache_file"
  2247. }
  2248. export -f get_service_incoming_relations
  2249. export TRAVERSE_SEPARATOR=:
  2250. ## Traverse on first service satisfying relation
  2251. service:traverse() {
  2252. local service_path="$1"
  2253. {
  2254. SEPARATOR=:
  2255. read -d "$TRAVERSE_SEPARATOR" service
  2256. while read -d "$TRAVERSE_SEPARATOR" relation; do
  2257. ## XXXvlab: Take only first service
  2258. if ! read-0 ts _ _ < <(get_service_relation "${service}" "${relation}"); then
  2259. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2260. "from ${DARKYELLOW}$service${NORMAL}."
  2261. return 1
  2262. fi
  2263. service="$ts"
  2264. done
  2265. echo "$service"
  2266. } < <(e "${service_path}${TRAVERSE_SEPARATOR}")
  2267. }
  2268. export -f service:traverse
  2269. service:relation-file() {
  2270. local service_path="$1" relation service relation_file
  2271. if ! [[ "$service_path" == *"$TRAVERSE_SEPARATOR"* ]]; then
  2272. err "Invalid argument '$service_path'." \
  2273. "Must provide a service path (no '${TRAVERSE_SEPARATOR}' found)."
  2274. return 1
  2275. fi
  2276. relation="${service_path##*${TRAVERSE_SEPARATOR}}"
  2277. service=$(service:traverse "${service_path%${TRAVERSE_SEPARATOR}*}") || return 1
  2278. if ! read-0 ts rc _ < <(get_service_relation "${service}" "${relation}"); then
  2279. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2280. "from ${DARKYELLOW}$service${NORMAL}."
  2281. return 1
  2282. fi
  2283. relation_dir=$(get_relation_data_dir "$service" "$ts" "$relation") || {
  2284. err "Failed to find relation file"
  2285. return 1
  2286. }
  2287. relation_file="$relation_dir/data"
  2288. if ! [ -e "$relation_file" ]; then
  2289. e "$rc" > "$relation_file"
  2290. chmod go-rwx "$relation_file" ## protecting this file
  2291. fi
  2292. echo "$relation_file"
  2293. }
  2294. export -f service:relation-file
  2295. service:relation-options() {
  2296. local service_path="$1" relation_file
  2297. relation_file=$(service:relation-file "$service_path") || {
  2298. err "Failed to find relation file"
  2299. return 1
  2300. }
  2301. cat "$relation_file"
  2302. }
  2303. export -f service:relation-options
  2304. relation:get() {
  2305. local service_path="$1" query="$2" relation_file
  2306. relation_file=$(service:relation-file "$service_path") || {
  2307. err "Failed to find relation file"
  2308. return 1
  2309. }
  2310. cfg-get-value "$query" < "$relation_file"
  2311. }
  2312. export -f relation:get
  2313. services:get:upable() {
  2314. if [ -z "$CHARM_STORE_HASH" ]; then
  2315. err-d "Expected \$CHARM_STORE_HASH to be set."
  2316. return 1
  2317. fi
  2318. local services_args=("$@") cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$CHARM_STORE_HASH" "$@")"
  2319. if [ -e "$cache_file" ]; then
  2320. touch "$cache_file" || return 1
  2321. cat "$cache_file"
  2322. return 0
  2323. fi
  2324. declare -A seen
  2325. services=($(get_ordered_service_dependencies "${services_args[@]}")) || exit 1
  2326. for service in "${services[@]}"; do
  2327. mservice=$(get_master_service_for_service "$service") || exit 1
  2328. [ "${seen[$mservice]}" ] && continue
  2329. type="$(get_service_type "$mservice")" || exit 1
  2330. ## remove run-once
  2331. [ "$type" == "run-once" ] && continue
  2332. [ "$type" == "stub" ] && continue
  2333. seen[$mservice]=1
  2334. echo "$mservice"
  2335. done > "$cache_file".wip
  2336. mv "$cache_file".wip "$cache_file"
  2337. cat "$cache_file"
  2338. }
  2339. export -f services:get:upable
  2340. service:state() {
  2341. local service="$1" states state
  2342. project_name=$(get_default_project_name) || return 1
  2343. states=()
  2344. for state in "$SERVICE_STATE_PATH"/"$project_name"/"$service"/*; do
  2345. [ -e "$state" ] || continue
  2346. state=${state##*/}
  2347. states+=("$state")
  2348. done
  2349. if [[ " ${states[*]} " == *" deploying "* ]]; then
  2350. echo "deploying"
  2351. elif [[ " ${states[*]} " == *" up "* ]]; then
  2352. echo "up"
  2353. else
  2354. echo "down"
  2355. fi
  2356. }
  2357. export -f service:state
  2358. _get_charm_metadata_uses() {
  2359. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2360. if [ -e "$cache_file" ]; then
  2361. #debug "$FUNCNAME: SESSION cache hit $1"
  2362. cat "$cache_file" || return 1
  2363. return 0
  2364. fi
  2365. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  2366. }
  2367. export -f _get_charm_metadata_uses
  2368. _get_service_metadata() {
  2369. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2370. charm
  2371. if [ -e "$cache_file" ]; then
  2372. #debug "$FUNCNAME: SESSION cache hit $1"
  2373. cat "$cache_file"
  2374. return 0
  2375. fi
  2376. charm="$(get_service_charm "$service")" || return 1
  2377. charm.metadata "$charm" > "$cache_file"
  2378. if [ "$?" != 0 ]; then
  2379. rm -f "$cache_file" ## no cache
  2380. return 1
  2381. fi
  2382. cat "$cache_file"
  2383. }
  2384. export -f _get_service_metadata
  2385. _get_service_uses() {
  2386. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2387. metadata
  2388. if [ -e "$cache_file" ]; then
  2389. #debug "$FUNCNAME: SESSION cache hit $1"
  2390. cat "$cache_file"
  2391. return 0
  2392. fi
  2393. metadata="$(_get_service_metadata "$service")" || return 1
  2394. _get_charm_metadata_uses "$metadata" > "$cache_file"
  2395. if [ "$?" != 0 ]; then
  2396. rm -f "$cache_file" ## no cache
  2397. return 1
  2398. fi
  2399. cat "$cache_file"
  2400. }
  2401. export -f _get_service_uses
  2402. _get_services_uses() {
  2403. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2404. service rn rd
  2405. if [ -e "$cache_file" ]; then
  2406. #debug "$FUNCNAME: SESSION cache hit $1"
  2407. cat "$cache_file"
  2408. return 0
  2409. fi
  2410. for service in "$@"; do
  2411. _get_service_uses "$service" | while read-0 rn rd; do
  2412. printf "%s\0" "$service" "$rn" "$rd"
  2413. done
  2414. [ "${PIPESTATUS[0]}" == 0 ] || {
  2415. return 1
  2416. }
  2417. done > "${cache_file}.wip"
  2418. mv "${cache_file}"{.wip,} &&
  2419. cat "$cache_file" || return 1
  2420. }
  2421. export -f _get_services_uses
  2422. _get_provides_provides() {
  2423. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2424. service rn rd
  2425. if [ -e "$cache_file" ]; then
  2426. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  2427. cat "$cache_file"
  2428. return 0
  2429. fi
  2430. type=$(printf "%s" "$provides" | shyaml get-type)
  2431. case "$type" in
  2432. sequence)
  2433. while read-0 prov; do
  2434. printf "%s\0" "$prov" ""
  2435. done < <(echo "$provides" | shyaml get-values-0)
  2436. ;;
  2437. struct)
  2438. printf "%s" "$provides" | shyaml key-values-0
  2439. ;;
  2440. str)
  2441. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  2442. ;;
  2443. *)
  2444. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  2445. return 1
  2446. esac | tee "$cache_file"
  2447. return "${PIPESTATUS[0]}"
  2448. }
  2449. _get_metadata_provides() {
  2450. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2451. service rn rd
  2452. if [ -e "$cache_file" ]; then
  2453. #debug "$FUNCNAME: CACHEDIR cache hit"
  2454. cat "$cache_file"
  2455. return 0
  2456. fi
  2457. provides=$(printf "%s" "$metadata" | shyaml -q get-value -y provides "")
  2458. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  2459. _get_provides_provides "$provides" | tee "$cache_file"
  2460. return "${PIPESTATUS[0]}"
  2461. }
  2462. _get_services_provides() {
  2463. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2464. service rn rd
  2465. if [ -e "$cache_file" ]; then
  2466. #debug "$FUNCNAME: SESSION cache hit $1"
  2467. cat "$cache_file"
  2468. return 0
  2469. fi
  2470. ## YYY: replace the inner loop by a cached function
  2471. for service in "$@"; do
  2472. metadata="$(_get_service_metadata "$service")" || return 1
  2473. while read-0 rn rd; do
  2474. printf "%s\0" "$service" "$rn" "$rd"
  2475. done < <(_get_metadata_provides "$metadata")
  2476. done > "$cache_file"
  2477. if [ "$?" != 0 ]; then
  2478. rm -f "$cache_file" ## no cache
  2479. return 1
  2480. fi
  2481. cat "$cache_file"
  2482. }
  2483. export -f _get_services_provides
  2484. _get_charm_provides() {
  2485. if [ -z "$CHARM_STORE_HASH" ]; then
  2486. err-d "Expected \$CHARM_STORE_HASH to be set."
  2487. return 1
  2488. fi
  2489. local cache_file="$CACHEDIR/$FUNCNAME.cache.$CHARM_STORE_HASH" errlvl
  2490. if [ -e "$cache_file" ]; then
  2491. #debug "$FUNCNAME: SESSION cache hit"
  2492. cat "$cache_file"
  2493. return 0
  2494. fi
  2495. start="$SECONDS"
  2496. debug "Getting charm provider list..."
  2497. while read-0 charm _ realpath metadata; do
  2498. metadata="$(charm.metadata "$charm")" || continue
  2499. # echo "reading $charm" >&2
  2500. while read-0 rn rd; do
  2501. printf "%s\0" "$charm" "$rn" "$rd"
  2502. done < <(_get_metadata_provides "$metadata")
  2503. done < <(charm.ls) | tee "$cache_file"
  2504. errlvl="${PIPESTATUS[0]}"
  2505. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  2506. return "$errlvl"
  2507. }
  2508. _get_charm_providing() {
  2509. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2510. relation="$1"
  2511. if [ -e "$cache_file" ]; then
  2512. #debug "$FUNCNAME: SESSION cache hit $1"
  2513. cat "$cache_file"
  2514. return 0
  2515. fi
  2516. while read-0 charm relation_name relation_def; do
  2517. [ "$relation_name" == "$relation" ] || continue
  2518. printf "%s\0" "$charm" "$relation_def"
  2519. done < <(_get_charm_provides) > "$cache_file"
  2520. if [ "$?" != 0 ]; then
  2521. rm -f "$cache_file" ## no cache
  2522. return 1
  2523. fi
  2524. cat "$cache_file"
  2525. }
  2526. _get_services_providing() {
  2527. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2528. relation="$1"
  2529. shift ## services is "$@"
  2530. if [ -e "$cache_file" ]; then
  2531. #debug "$FUNCNAME: SESSION cache hit $1"
  2532. cat "$cache_file"
  2533. return 0
  2534. fi
  2535. while read-0 service relation_name relation_def; do
  2536. [ "$relation_name" == "$relation" ] || continue
  2537. printf "%s\0" "$service" "$relation_def"
  2538. done < <(_get_services_provides "$@") > "$cache_file"
  2539. if [ "$?" != 0 ]; then
  2540. rm -f "$cache_file" ## no cache
  2541. return 1
  2542. fi
  2543. cat "$cache_file"
  2544. }
  2545. export -f _get_services_provides
  2546. _out_new_relation_from_defs() {
  2547. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  2548. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2549. ## YYYvlab: should be seen even in no debug mode no ?
  2550. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2551. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  2552. td=${td:-True}
  2553. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  2554. after=$(_out_after_value_from_def "$service" "$rn" "$rel_def") || return 1
  2555. printf "%s\0" "$after" "$service" "$relation_name" "$ts" "$rc" "$td"
  2556. }
  2557. _out_after_value_from_def() {
  2558. local service="$1" relation_name="$2" relation_def="$3" after_t after
  2559. if after_t=$(echo "$relation_def" | shyaml get-type after 2>/dev/null); then
  2560. case "$after_t" in
  2561. sequence)
  2562. after="$(echo "$relation_def" | shyaml get-values after 2>/dev/null)" || return 1
  2563. after=",$service:${after//$'\n'/,$service:},"
  2564. ;;
  2565. struct)
  2566. err "Invalid type for ${WHITE}after${NORMAL}'s value in ${DARKBLUE}$relation_name${NORMAL}'s definition."
  2567. return 1
  2568. ;;
  2569. str)
  2570. after=",$service:$(echo "$relation_def" | shyaml get-value after "" 2>/dev/null)," || return 1
  2571. ;;
  2572. esac
  2573. else
  2574. after=""
  2575. fi
  2576. e "$after"
  2577. }
  2578. get_all_compose_yml_service() {
  2579. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2580. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2581. err "Failed to get compose yml hash"
  2582. return 1
  2583. }
  2584. fi
  2585. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2586. if [ -e "${cache_file}" ]; then
  2587. #debug "$FUNCNAME: cache hit: ${cache_file}"
  2588. cat "${cache_file}"
  2589. return 0
  2590. fi
  2591. compose_yml_content=$(get_compose_yml_content) || return 1
  2592. printf "%s" "${compose_yml_content}" | shyaml keys-0 2>/dev/null > "${cache_file}.wip" || {
  2593. err "Failed to get keys of compose content."
  2594. return 1
  2595. }
  2596. mv "${cache_file}"{.wip,} || return 1
  2597. cat "${cache_file}"
  2598. }
  2599. ## Outputs all relations array.
  2600. _service:all:relations_cached() {
  2601. local services service E
  2602. services=($(compose:yml:root:services)) || return 1
  2603. get_all_relations "${services[@]}" || return 1
  2604. }
  2605. ## Outputs all relations array.
  2606. service:all:relations() {
  2607. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2608. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2609. err "Failed to get compose yml hash."
  2610. return 1
  2611. }
  2612. fi
  2613. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2614. if [ -e "${cache_file}" ]; then
  2615. # debug "$FUNCNAME: SESSION cache hit $1"
  2616. cat "${cache_file}"
  2617. return 0
  2618. fi
  2619. _service:all:relations_cached > "${cache_file}.wip" || {
  2620. err-d "Failed to compute all relations."
  2621. return 1
  2622. }
  2623. mv "${cache_file}"{.wip,} || return 1
  2624. cat "${cache_file}"
  2625. }
  2626. _service:all:relations_hash_cached() {
  2627. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2628. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2629. err "Failed to get compose yml hash."
  2630. return 1
  2631. }
  2632. fi
  2633. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH" \
  2634. hash
  2635. if [ -e "${cache_file}" ]; then
  2636. # debug "$FUNCNAME: SESSION cache hit $1"
  2637. cat "${cache_file}"
  2638. return 0
  2639. fi
  2640. service:all:relations > "${cache_file}.pre" || {
  2641. err-d "Failed to get all relations."
  2642. return 1
  2643. }
  2644. {
  2645. p0 "$(hash_get < "${cache_file}.pre")" || return 1
  2646. cat "${cache_file}.pre"
  2647. rm "${cache_file}.pre"
  2648. } > "${cache_file}".wip || return 1
  2649. mv "${cache_file}"{.wip,} || return 1
  2650. cat "${cache_file}"
  2651. }
  2652. ## Get all relations from all services in the current compose file.
  2653. ## Sets GLOBAL_ALL_RELATIONS_HASH and returns all relations array.
  2654. service:all:set_relations_hash() {
  2655. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2656. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2657. err "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2658. echo " (despite \$GLOBAL_ALL_RELATIONS being set)" >&2
  2659. return 1
  2660. fi
  2661. return 0
  2662. fi
  2663. ## sets COMPOSE_YML_CONTENT_HASH
  2664. _service:all:relations_hash_cached >/dev/null || return 1
  2665. {
  2666. read-0 GLOBAL_ALL_RELATIONS_HASH || return 1
  2667. export GLOBAL_ALL_RELATIONS_HASH
  2668. ## transfer to statedir
  2669. export GLOBAL_ALL_RELATIONS="$state_tmpdir/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2670. cat > "$GLOBAL_ALL_RELATIONS"
  2671. } < <(_service:all:relations_hash_cached)
  2672. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2673. err "Failed to set \$GLOBAL_ALL_RELATIONS."
  2674. return 1
  2675. fi
  2676. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2677. err "Failed to set \$GLOBAL_ALL_RELATIONS_HASH."
  2678. return 1
  2679. fi
  2680. }
  2681. get_subset_relations () {
  2682. local service all_services services start
  2683. if [ -n "$SUBSET_ALL_RELATIONS" ]; then
  2684. return 0
  2685. fi
  2686. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2687. err-d "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2688. return 1
  2689. fi
  2690. cache_hash=$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH" "$(declare -f "$FUNCNAME")")
  2691. local cache_file="$CACHEDIR/$FUNCNAME.cache.$cache_hash"
  2692. if [ -e "${cache_file}" ]; then
  2693. export SUBSET_ALL_RELATIONS="$cache_file"
  2694. hash=$(hash_get < "$cache_file") || return 1
  2695. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2696. cat "${cache_file}"
  2697. return 0
  2698. fi
  2699. ## collect all connected services first
  2700. all_services=("$@")
  2701. declare -A services
  2702. while [ "${#all_services[@]}" != 0 ]; do
  2703. array_pop all_services service
  2704. # debug " Getting relations for $DARKYELLOW$service$NORMAL"
  2705. while read-0 s rn ts rc td; do
  2706. [[ "$s" == "$service" ]] || continue
  2707. # debug " adding relation $DARKBLUE$rn$NORMAL to $DARKYELLOW$ts$NORMAL"
  2708. p0 "$service" "$rn" "$ts" "$rc" "$td"
  2709. if [ -z "${services[$ts]}" ] && [[ " ${all_services[@]} " != *" $ts "* ]]; then
  2710. all_services+=("$ts")
  2711. fi
  2712. done < "$GLOBAL_ALL_RELATIONS"
  2713. services["$service"]=1
  2714. done > "$cache_file.wip"
  2715. mv "$cache_file"{.wip,} || return 1
  2716. export SUBSET_ALL_RELATIONS="$cache_file"
  2717. hash=$(hash_get < "$cache_file") || return 1
  2718. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2719. cat "$cache_file"
  2720. }
  2721. export -f get_subset_relations
  2722. get_all_relations () {
  2723. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2724. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || return 1
  2725. fi
  2726. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2727. cat "$GLOBAL_ALL_RELATIONS" || return 1
  2728. return 0
  2729. fi
  2730. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$COMPOSE_YML_CONTENT_HASH" "$(declare -p without_relations)")" \
  2731. services all_services service services_uses services_provides \
  2732. changed summon required recommended optional
  2733. if [ -e "${cache_file}" ]; then
  2734. #debug "$FUNCNAME: SESSION cache hit $1"
  2735. export GLOBAL_ALL_RELATIONS="$cache_file"
  2736. cat "${cache_file}"
  2737. return 0
  2738. fi
  2739. declare -A services
  2740. services_uses=()
  2741. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2742. _get_services_uses "$@" >/dev/null || return 1
  2743. array_read-0 services_uses < <(_get_services_uses "$@")
  2744. services_provides=()
  2745. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2746. _get_services_provides "$@" >/dev/null || return 1
  2747. array_read-0 services_provides < <(_get_services_provides "$@")
  2748. for service in "$@"; do
  2749. services[$service]=1
  2750. done
  2751. all_services=("$@")
  2752. while [ "${#all_services[@]}" != 0 ]; do
  2753. array_pop all_services service
  2754. while read-0-err E relation_name ts relation_config tech_dep; do
  2755. [ "${without_relations[$service:$relation_name]}" ] && {
  2756. debug "Ignoring compose $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> ${DARKYELLOW}$ts$NORMAL"
  2757. continue
  2758. }
  2759. ## First is priority, that can be adjusted in second step
  2760. printf "%s\0" "" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  2761. ## adding target services ?
  2762. [ "${services[$ts]}" ] && continue
  2763. array_read-0 services_uses < <(_get_services_uses "$ts")
  2764. all_services+=("$ts")
  2765. services[$ts]=1
  2766. done < <(p-err get_compose_relations "$service")
  2767. if [ "$E" != 0 ]; then
  2768. err "Failed to get relations for $DARKYELLOW$service$NORMAL."
  2769. return 1
  2770. fi
  2771. done > "${cache_file}.wip"
  2772. while true; do
  2773. changed=
  2774. new_services_uses=()
  2775. summon=()
  2776. required=()
  2777. recommended=()
  2778. optional=()
  2779. while [ "${#services_uses[@]}" != 0 ]; do
  2780. service="${services_uses[0]}"
  2781. relation_name="${services_uses[1]}"
  2782. relation_def="${services_uses[2]}"
  2783. services_uses=("${services_uses[@]:3}")
  2784. [ "${without_relations[$service:$relation_name]}" ] && {
  2785. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2786. continue
  2787. }
  2788. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2789. after=$(_out_after_value_from_def "$service" "$relation_name" "$relation_def") || return 1
  2790. ## is this "use" declaration satisfied ?
  2791. found=
  2792. while read-0 p s rn ts rc td; do
  2793. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  2794. if [ "$default_options" ]; then
  2795. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2796. fi
  2797. found="$ts"
  2798. p="$after"
  2799. fi
  2800. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td"
  2801. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2802. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2803. if [ "$found" ]; then ## this "use" declaration was satisfied
  2804. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation" \
  2805. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2806. continue
  2807. fi
  2808. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2809. auto=${auto:-pair}
  2810. case "$auto" in
  2811. "pair"|"summon")
  2812. service_list=()
  2813. array_read-0 service_list < <(array_keys_to_stdin services)
  2814. providers=()
  2815. providers_def=()
  2816. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2817. if [ "${#providers[@]}" == 1 ]; then
  2818. ts="${providers[0]}"
  2819. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2820. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2821. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2822. "${providers_def[0]}" "$relation_def" \
  2823. >> "${cache_file}.wip" || return 1
  2824. ## Adding service
  2825. [ "${services[$ts]}" ] && continue
  2826. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2827. services[$ts]=1
  2828. changed=1
  2829. continue
  2830. fi
  2831. if [ "${#providers[@]}" -gt 1 ]; then
  2832. msg=""
  2833. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2834. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2835. "(> 1 provider)."
  2836. elif [ "$auto" == "summon" ]; then ## no provider
  2837. summon+=("$service" "$relation_name" "$relation_def")
  2838. fi
  2839. ;;
  2840. null|disable|disabled)
  2841. :
  2842. ;;
  2843. *)
  2844. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2845. return 1
  2846. ;;
  2847. esac
  2848. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2849. constraint=${constraint:-optional}
  2850. case "$constraint" in
  2851. "required")
  2852. required+=("$service" "$relation_name" "$relation_def")
  2853. ;;
  2854. "recommended")
  2855. recommended+=("$service" "$relation_name" "$relation_def")
  2856. ;;
  2857. "optional")
  2858. optional+=("$service" "$relation_name" "$relation_def")
  2859. ;;
  2860. *)
  2861. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2862. return 1
  2863. ;;
  2864. esac
  2865. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2866. done
  2867. services_uses=("${new_services_uses[@]}")
  2868. if [ "$changed" ]; then
  2869. continue
  2870. fi
  2871. ## situation is stable
  2872. if [ "${#summon[@]}" != 0 ]; then
  2873. declare -A summon_requeued=()
  2874. while [ "${#summon[@]}" != 0 ]; do
  2875. service="${summon[0]}"
  2876. relation_name="${summon[1]}"
  2877. relation_def="${summon[2]}"
  2878. summon=("${summon[@]:3}")
  2879. providers=()
  2880. providers_def=()
  2881. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2882. ## select first provider that is not a stub
  2883. new_providers=()
  2884. new_providers_def=()
  2885. while [[ "${#providers[@]}" != 0 ]]; do
  2886. provider="${providers[0]}"
  2887. provider_def="${providers_def[0]}"
  2888. providers=("${providers[@]:1}")
  2889. providers_def=("${providers_def[@]:1}")
  2890. type="$(get_service_type "$provider")" || true
  2891. [ "$type" == "stub" ] && continue
  2892. new_providers+=("$provider")
  2893. new_providers_def+=("$provider_def")
  2894. done
  2895. providers=("${new_providers[@]}")
  2896. providers_def=("${new_providers_def[@]}")
  2897. if [ "${#providers[@]}" == 0 ]; then
  2898. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2899. return 1
  2900. fi
  2901. if [ "${#providers[@]}" -gt 1 ]; then
  2902. ## if there are multiple providers (for instance
  2903. ## sql-database), there are some case where other
  2904. ## services will also summon a more specific
  2905. ## postgres-database, that will solve our
  2906. ## constraint. So we'd rather pass (and requeue)
  2907. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2908. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2909. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2910. "(> 1 provider). Requeuing."
  2911. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2912. summon_requeued["$service/$relation_name"]=1
  2913. continue
  2914. else
  2915. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2916. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2917. "(> 1 provider). Choosing first."
  2918. fi
  2919. fi
  2920. ts="${providers[0]}"
  2921. ## YYYvlab: should be seen even in no debug mode no ?
  2922. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2923. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2924. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2925. "${providers_def[0]}" "$relation_def" \
  2926. >> "${cache_file}.wip" || return 1
  2927. ## Adding service
  2928. [ "${services[$ts]}" ] && continue
  2929. array_read-0 services_uses < <(_get_services_uses "$ts")
  2930. services[$ts]=1
  2931. changed=1
  2932. continue 2
  2933. done
  2934. continue
  2935. fi
  2936. [ "$NO_CONSTRAINT_CHECK" ] && break
  2937. if [ "${#required[@]}" != 0 ]; then
  2938. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2939. err "Required relations not satisfied"
  2940. return 1
  2941. fi
  2942. if [ "${#recommended[@]}" != 0 ]; then
  2943. ## make recommendation
  2944. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2945. fi
  2946. if [ -z "$QUIET" ]; then
  2947. if [ "${#optional[@]}" != 0 ]; then
  2948. ## inform about options
  2949. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2950. fi
  2951. fi
  2952. # if [ "${#required[@]}" != 0 ]; then
  2953. # err "Required relations not satisfied"
  2954. # return 1
  2955. # fi
  2956. if [ "${#recommended[@]}" != 0 ]; then
  2957. warn "Recommended relations not satisfied"
  2958. fi
  2959. break
  2960. done
  2961. if [ "$?" != 0 ]; then
  2962. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2963. return 1
  2964. fi
  2965. ##
  2966. ## Sort relations thanks to uses =metadata.yml= relations.
  2967. ##
  2968. mv "${cache_file}.wip"{,.in} &&
  2969. rm -f "${cache_file}.wip.final" &&
  2970. touch "${cache_file}.wip.final" || {
  2971. err "Unexpected error when mangling cache files."
  2972. return 1
  2973. }
  2974. declare -A relation_done=()
  2975. while true; do
  2976. had_remaining_relation=
  2977. had_new_relation=
  2978. while read-0 p s rn ts rc td; do
  2979. if [ -z "$p" ] || [ "$p" == "," ]; then
  2980. relation_done["$s:$rn"]=1
  2981. # printf " .. %-30s %-30s %-30s\n" "$s" "$ts" "$rn" >&2
  2982. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  2983. had_new_relation=1
  2984. else
  2985. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2986. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2987. had_remaining_relation=1
  2988. fi
  2989. done < "${cache_file}.wip.in"
  2990. [ -z "$had_remaining_relation" ] && break
  2991. mv "${cache_file}.wip."{out,in}
  2992. while read-0 p s rn ts rc td; do
  2993. for rel in "${!relation_done[@]}"; do
  2994. p="${p//,$rel,/,}"
  2995. done
  2996. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2997. if [ -z "$had_new_relation" ]; then
  2998. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  2999. for rel in ${p//,/ }; do
  3000. rel_s=${rel%%:*}
  3001. rel_r=${rel##*:}
  3002. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  3003. done
  3004. else
  3005. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  3006. fi
  3007. done < "${cache_file}.wip.in"
  3008. if [ -z "$had_new_relation" ]; then
  3009. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  3010. return 1
  3011. fi
  3012. mv "${cache_file}.wip."{out,in}
  3013. done
  3014. mv "${cache_file}"{.wip.final,} || return 1
  3015. export GLOBAL_ALL_RELATIONS="$cache_file"
  3016. GLOBAL_ALL_RELATIONS_HASH=$(hash_get < "$cache_file") || return 1
  3017. export GLOBAL_ALL_RELATIONS_HASH
  3018. cat "$cache_file"
  3019. }
  3020. export -f get_all_relations
  3021. _display_solves() {
  3022. local array_name="$1" by_relation msg
  3023. ## inform about options
  3024. msg=""
  3025. declare -A by_relation
  3026. while read-0 service relation_name relation_def; do
  3027. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  3028. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  3029. if [ -z "$solves" ]; then
  3030. continue
  3031. fi
  3032. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  3033. if [ "$auto" == "pair" ]; then
  3034. requirement="add provider in cluster to auto-pair"
  3035. else
  3036. requirement="add explicit relation"
  3037. fi
  3038. while read-0 name def; do
  3039. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  3040. done < <(printf "%s" "$solves" | shyaml key-values-0)
  3041. done < <(array_values_to_stdin "$array_name")
  3042. while read-0 relation_name message; do
  3043. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  3044. "$relation_name" "$message" )"
  3045. done < <(array_kv_to_stdin by_relation)
  3046. if [ "$msg" ]; then
  3047. printf "%s\n" "${msg:1}"
  3048. fi
  3049. }
  3050. get_compose_relation_def() {
  3051. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  3052. while read-0 relation_name target_service relation_config tech_dep; do
  3053. [ "$relation_name" == "$relation" ] || continue
  3054. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  3055. done < <(get_compose_relations "$service") || return 1
  3056. }
  3057. export -f get_compose_relation_def
  3058. run_service_relations () {
  3059. local service services loaded subservices subservice
  3060. PROJECT_NAME=$(get_default_project_name) || return 1
  3061. export PROJECT_NAME
  3062. declare -A loaded
  3063. subservices=$(get_ordered_service_dependencies "$@") || return 1
  3064. for service in $subservices; do
  3065. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  3066. for subservice in $(get_service_deps "$service") "$service"; do
  3067. [ "${loaded[$subservice]}" ] && continue
  3068. export BASE_SERVICE_NAME=$service
  3069. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  3070. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  3071. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  3072. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  3073. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  3074. while read-0 relation_name target_service relation_config tech_dep; do
  3075. [ "${without_relations[$service:$relation_name]}" ] && {
  3076. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  3077. continue
  3078. }
  3079. export relation_config
  3080. export TARGET_SERVICE_NAME=$target_service
  3081. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  3082. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  3083. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  3084. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  3085. Wrap "${wrap_opts[@]}" -d "building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  3086. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  3087. EOF
  3088. done < <(get_service_relations "$subservice") || return 1
  3089. loaded[$subservice]=1
  3090. done
  3091. done
  3092. }
  3093. export -f run_service_relations
  3094. _run_service_action_direct() {
  3095. local service="$1" action="$2" charm _dummy project_name
  3096. shift; shift
  3097. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  3098. if read-0 _dummy || [ "$_dummy" ]; then
  3099. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3100. return 1
  3101. fi
  3102. project_name=$(get_default_project_name) || return 1
  3103. export PROJECT_NAME="$project_name"
  3104. export state_tmpdir
  3105. (
  3106. set +e ## Prevents unwanted leaks from parent shell
  3107. export COMPOSE_CONFIG=$(get_compose_yml_content)
  3108. export METADATA_CONFIG=$(charm.metadata "$charm")
  3109. export SERVICE_NAME=$service
  3110. export ACTION_NAME=$action
  3111. export ACTION_SCRIPT_PATH="$action_script_path"
  3112. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3113. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3114. export SERVICE_DATASTORE="$DATASTORE/$service"
  3115. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3116. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3117. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  3118. ) 0<&6 ## inject general stdin
  3119. }
  3120. export -f _run_service_action_direct
  3121. _run_service_action_relation() {
  3122. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  3123. shift; shift
  3124. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  3125. if read-0 _dummy || [ "$_dummy" ]; then
  3126. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3127. return 1
  3128. fi
  3129. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  3130. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  3131. export state_tmpdir
  3132. (
  3133. set +e ## Prevents unwanted leaks from parent shell
  3134. export METADATA_CONFIG=$(charm.metadata "$charm")
  3135. export SERVICE_NAME=$service
  3136. export RELATION_TARGET_SERVICE="$target_service"
  3137. export RELATION_TARGET_CHARM="$target_charm"
  3138. export RELATION_BASE_SERVICE="$service"
  3139. export RELATION_BASE_CHARM="$charm"
  3140. export RELATION_DATA_FILE="$RELATION_DATA_FILE"
  3141. export ACTION_NAME=$action
  3142. export ACTION_SCRIPT_PATH="$action_script_path"
  3143. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3144. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3145. export SERVICE_DATASTORE="$DATASTORE/$service"
  3146. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3147. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3148. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  3149. ) 0<&6 ## inject general stdin
  3150. }
  3151. export -f _run_service_action_relation
  3152. get_relation_data_dir() {
  3153. local service="$1" target_service="$2" relation_name="$3" \
  3154. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  3155. if [ -e "$cache_file" ]; then
  3156. # debug "$FUNCNAME: cache hit ($*)"
  3157. cat "$cache_file"
  3158. return 0
  3159. fi
  3160. local project relation_dir
  3161. project=${PROJECT_NAME}
  3162. if [ -z "$project" ]; then
  3163. project=$(get_default_project_name) || return 1
  3164. fi
  3165. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  3166. if ! [ -d "$relation_dir" ]; then
  3167. mkdir -p "$relation_dir" || return 1
  3168. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  3169. fi
  3170. echo "$relation_dir" | tee "$cache_file"
  3171. }
  3172. export -f get_relation_data_dir
  3173. get_relation_data_file() {
  3174. local service="$1" target_service="$2" relation_name="$3" relation_config="$4" \
  3175. new new_md5 relation_dir relation_data_file
  3176. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  3177. relation_data_file="$relation_dir/data"
  3178. new=
  3179. if [ -e "$relation_data_file" ]; then
  3180. ## Has reference changed ?
  3181. new_md5=$(e "$relation_config" | md5_compat)
  3182. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  3183. new=true
  3184. fi
  3185. else
  3186. new=true
  3187. fi
  3188. if [ -n "$new" ]; then
  3189. OLDUMASK=$(umask)
  3190. umask 0077
  3191. e "$relation_config" > "$relation_data_file"
  3192. umask "$OLDUMASK"
  3193. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  3194. fi
  3195. echo "$relation_data_file"
  3196. }
  3197. export -f get_relation_data_file
  3198. has_service_action () {
  3199. if [ -z "$CHARM_STORE_HASH" ]; then
  3200. err-d "Can't access global \$CHARM_STORE_HASH"
  3201. return 1
  3202. fi
  3203. local service="$1" action="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$2.$CHARM_STORE_HASH" \
  3204. charm target_charm relation_name target_service relation_config _tech_dep \
  3205. path
  3206. if [ -e "$cache_file" ]; then
  3207. # debug "$FUNCNAME: cache hit ($*)"
  3208. if [ -s "$cache_file" ]; then
  3209. cat "$cache_file"
  3210. return 0
  3211. else
  3212. return 1
  3213. fi
  3214. fi
  3215. charm=$(get_service_charm "$service") || return 1
  3216. ## Action directly provided ?
  3217. if path=$(charm.has_direct_action "$charm" "$action"); then
  3218. p0 "direct" "$charm" "$path" | tee "$cache_file"
  3219. return 0
  3220. fi
  3221. ## Action provided by relation ?
  3222. while read-0 relation_name target_service relation_config _tech_dep; do
  3223. target_charm=$(get_service_charm "$target_service") || return 1
  3224. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  3225. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  3226. return 0
  3227. fi
  3228. done < <(get_service_relations "$service")
  3229. touch "$cache_file"
  3230. return 1
  3231. # master=$(get_top_master_service_for_service "$service")
  3232. # [ "$master" == "$charm" ] && return 1
  3233. # has_service_action "$master" "$action"
  3234. }
  3235. export -f has_service_action
  3236. run_service_action () {
  3237. local service="$1" action="$2" errlvl
  3238. shift ; shift
  3239. exec 6<&0 ## saving stdin
  3240. {
  3241. if ! read-0 action_type; then
  3242. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  3243. info " Add an executable script to 'actions/$action' to implement action."
  3244. return 1
  3245. fi
  3246. "_run_service_action_${action_type}" "$service" "$action" "$@"
  3247. errlvl="$?"
  3248. } < <(has_service_action "$service" "$action")
  3249. exec 0<&6 6<&- ## restoring stdin
  3250. return "$errlvl"
  3251. }
  3252. export -f run_service_action
  3253. get_compose_relation_config() {
  3254. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3255. if [ -e "$cache_file" ]; then
  3256. # debug "$FUNCNAME: cache hit ($*)"
  3257. cat "$cache_file"
  3258. return 0
  3259. fi
  3260. compose_service_def=$(get_compose_service_def "$service") || return 1
  3261. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  3262. }
  3263. export -f get_compose_relation_config
  3264. # ## Return key-values-0
  3265. # get_compose_relation_config_for_service() {
  3266. # local service=$1 relation_name=$2 relation_config
  3267. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  3268. # if ! relation_config=$(
  3269. # echo "$compose_service_relations" |
  3270. # shyaml get-value "${relation_name}" 2>/dev/null); then
  3271. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  3272. # "relation config in compose configuration."
  3273. # return 1
  3274. # fi
  3275. # if [ -z "$relation_config" ]; then
  3276. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  3277. # return 1
  3278. # fi
  3279. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  3280. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  3281. # return 1
  3282. # fi
  3283. # }
  3284. # export -f get_compose_relation_config_for_service
  3285. _get_container_relation() {
  3286. local metadata=$1 found relation_name relation_def
  3287. found=
  3288. while read-0 relation_name relation_def; do
  3289. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  3290. found="$relation_name"
  3291. break
  3292. }
  3293. done < <(_get_charm_metadata_uses "$metadata")
  3294. if [ -z "$found" ]; then
  3295. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  3296. "${WHITE}scope${NORMAL} set to 'container'."
  3297. return 1
  3298. fi
  3299. printf "%s" "$found"
  3300. }
  3301. _get_master_service_for_service_cached () {
  3302. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3303. charm requires master_charm target_charm target_service service_def found
  3304. if [ -e "$cache_file" ]; then
  3305. # debug "$FUNCNAME: STATIC cache hit ($1)"
  3306. cat "$cache_file" &&
  3307. touch "$cache_file" || return 1
  3308. return 0
  3309. fi
  3310. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3311. ## just return service name
  3312. echo "$service" | tee "$cache_file"
  3313. return 0
  3314. fi
  3315. ## Action provided by relation ?
  3316. container_relation=$(_get_container_relation "$metadata") || return 1
  3317. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  3318. if [ -z "$target_service" ]; then
  3319. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  3320. "${DARKYELLOW}$service$NORMAL compose definition."
  3321. err ${FUNCNAME[@]}
  3322. return 1
  3323. fi
  3324. echo "$target_service" | tee "$cache_file"
  3325. }
  3326. export -f _get_master_service_for_service_cached
  3327. get_master_service_for_service() {
  3328. if [ -z "$CHARM_STORE_HASH" ]; then
  3329. err-d "Expected \$CHARM_STORE_HASH to be set."
  3330. return 1
  3331. fi
  3332. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3333. charm metadata result
  3334. if [ -e "$cache_file" ]; then
  3335. # debug "$FUNCNAME: SESSION cache hit ($*)"
  3336. cat "$cache_file" || return 1
  3337. return 0
  3338. fi
  3339. charm=$(get_service_charm "$service") || return 1
  3340. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  3341. metadata=""
  3342. warn "No charm $DARKPINK$charm$NORMAL found."
  3343. }
  3344. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  3345. echo "$result" | tee "$cache_file" || return 1
  3346. }
  3347. export -f get_master_service_for_service
  3348. get_top_master_service_for_service() {
  3349. if [ -z "$CHARM_STORE_HASH" ]; then
  3350. err-d "Expected \$CHARM_STORE_HASH to be set."
  3351. return 1
  3352. fi
  3353. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3354. current_service
  3355. if [ -e "$cache_file" ]; then
  3356. # debug "$FUNCNAME: cache hit ($*)"
  3357. touch "$cache_file" || return 1
  3358. cat "$cache_file"
  3359. return 0
  3360. fi
  3361. current_service="$service"
  3362. while true; do
  3363. master_service=$(get_master_service_for_service "$current_service") || return 1
  3364. [ "$master_service" == "$current_service" ] && break
  3365. current_service="$master_service"
  3366. done
  3367. echo "$current_service" | tee "$cache_file"
  3368. return 0
  3369. }
  3370. export -f get_top_master_service_for_service
  3371. ##
  3372. ## The result is a mixin that is not always a complete valid
  3373. ## docker-compose entry (thinking of subordinates). The result
  3374. ## will be merge with master charms.
  3375. _get_docker_compose_mixin_from_metadata_cached() {
  3376. local service="$1" charm="$2" metadata="$3" \
  3377. has_build_dir="$4" \
  3378. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3379. metadata_file metadata volumes docker_compose subordinate image \
  3380. mixin mixins tmemory memory limit docker_memory
  3381. if [ -e "$cache_file" ]; then
  3382. #debug "$FUNCNAME: STATIC cache hit $1"
  3383. cat "$cache_file" &&
  3384. touch "$cache_file" || return 1
  3385. return 0
  3386. fi
  3387. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  3388. if [ "$metadata" ]; then
  3389. ## resources to volumes
  3390. volumes=$(
  3391. for resource_type in data config; do
  3392. while read-0 resource; do
  3393. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  3394. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  3395. done
  3396. while read-0 resource; do
  3397. if [[ "$resource" == /*:/*:* ]]; then
  3398. echo " - $resource"
  3399. elif [[ "$resource" == /*:/* ]]; then
  3400. echo " - $resource:rw"
  3401. elif [[ "$resource" == /*:* ]]; then
  3402. echo " - ${resource%%:*}:$resource"
  3403. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  3404. echo " - $resource:$resource:rw"
  3405. else
  3406. die "Invalid host-resource specified in 'metadata.yml'."
  3407. fi
  3408. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  3409. while read-0 resource; do
  3410. dest="$(charm.get_dir "$charm")/resources$resource"
  3411. if ! [ -e "$dest" ]; then
  3412. die "charm-resource: '$resource' does not exist (file: '$dest')."
  3413. fi
  3414. echo " - $dest:$resource:ro"
  3415. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  3416. ) || return 1
  3417. if [ "$volumes" ]; then
  3418. mixins+=("volumes:"$'\n'"$volumes")
  3419. fi
  3420. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3421. if [ "$type" != "run-once" ]; then
  3422. mixins+=("restart: unless-stopped")
  3423. fi
  3424. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  3425. if [ "$docker_compose" ]; then
  3426. mixins+=("$docker_compose")
  3427. fi
  3428. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3429. subordinate=true
  3430. fi
  3431. fi
  3432. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  3433. [ "$image" == "None" ] && image=""
  3434. if [ -n "$image" ]; then
  3435. if [ -n "$subordinate" ]; then
  3436. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  3437. return 1
  3438. fi
  3439. mixins+=("image: $image")
  3440. elif [ "$has_build_dir" ]; then
  3441. if [ "$subordinate" ]; then
  3442. err "Subordinate charm can not have a 'build' sub directory."
  3443. return 1
  3444. fi
  3445. mixins+=("build: $(charm.get_dir "$charm")/build")
  3446. fi
  3447. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  3448. [ "$limit" == "null" ] && limit=""
  3449. if [ -n "$limit" ]; then
  3450. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  3451. [ "$E" != 0 ]; then
  3452. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  3453. return 1
  3454. fi
  3455. case "$tmemory" in
  3456. '!!str'|'!!int')
  3457. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  3458. err "Invalid format specified for .limit.memory: '$memory'."
  3459. return 1
  3460. }
  3461. ;;
  3462. '!!float')
  3463. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  3464. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  3465. return 1
  3466. ;;
  3467. '!!null')
  3468. :
  3469. ;;
  3470. *)
  3471. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  3472. "for ${WHITE}.limit.memory${NORMAL}."
  3473. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  3474. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  3475. echo " Example values: '1.5G', '252M', ..." >&2
  3476. return 1
  3477. ;;
  3478. esac
  3479. if [ -n "$docker_memory" ]; then
  3480. if [[ "$docker_memory" -lt 6291456 ]]; then
  3481. err "Can't limit service to lower than 6M."
  3482. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  3483. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  3484. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  3485. return 1
  3486. fi
  3487. mixins+=(
  3488. "mem_limit: $docker_memory"
  3489. "memswap_limit: $docker_memory"
  3490. )
  3491. fi
  3492. fi
  3493. ## Final merging
  3494. mixin=$(merge_yaml_str "${mixins[@]}") || {
  3495. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  3496. return 1
  3497. }
  3498. echo "$mixin" | tee "$cache_file"
  3499. }
  3500. export -f _get_docker_compose_mixin_from_metadata_cached
  3501. get_docker_compose_mixin_from_metadata() {
  3502. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3503. if [ -e "$cache_file" ]; then
  3504. #debug "$FUNCNAME: SESSION cache hit ($*)"
  3505. cat "$cache_file"
  3506. return 0
  3507. fi
  3508. charm=$(get_service_charm "$service") || return 1
  3509. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  3510. has_build_dir=
  3511. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  3512. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  3513. echo "$mixin" | tee "$cache_file"
  3514. }
  3515. export -f get_docker_compose_mixin_from_metadata
  3516. _save() {
  3517. local name="$1"
  3518. cat - | tee -a "$docker_compose_dir/.data/$name"
  3519. }
  3520. export -f _save
  3521. get_default_project_name() {
  3522. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  3523. echo "$DEFAULT_PROJECT_NAME"
  3524. return 0
  3525. fi
  3526. local normalized_path compose_yml_location name
  3527. compose_yml_location="$(get_compose_yml_location)" || return 1
  3528. if [ -n "$compose_yml_location" ]; then
  3529. if normalized_path=$(readlink -f "$compose_yml_location"); then
  3530. name="${normalized_path%/*}" ## dirname
  3531. name="${name##*/}" ## basename
  3532. name="${name%%-deploy}" ## remove any '-deploy'
  3533. name="${name,,}" ## lowercase
  3534. e "$name"
  3535. return 0
  3536. fi
  3537. fi
  3538. echo "orphan"
  3539. return 0
  3540. }
  3541. export -f get_default_project_name
  3542. get_running_compose_containers() {
  3543. ## XXXvlab: docker bug: there will be a final newline anyway
  3544. docker ps --filter label="compose.service" --format='{{.ID}}'
  3545. }
  3546. export -f get_running_compose_containers
  3547. get_healthy_container_ip_for_service () {
  3548. local service="$1" port="$2" timeout=${3:-60}
  3549. local containers container container_network container_ip
  3550. containers="$(get_running_containers_for_service "$service")"
  3551. if [ -z "$containers" ]; then
  3552. err "No containers running for service $DARKYELLOW$service$NORMAL."
  3553. return 1
  3554. fi
  3555. ## XXXvlab: taking first container is probably not a good idea
  3556. container="$(echo "$containers" | head -n 1)"
  3557. ## XXXvlab: taking first ip is probably not a good idea
  3558. read-0 container_network container_ip < <(get_container_network_ip "$container")
  3559. if [ -z "$container_ip" ]; then
  3560. err "Can't get container's IP. You should check health of" \
  3561. "${DARKYELLOW}$service${NORMAL}'s container."
  3562. return 1
  3563. fi
  3564. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  3565. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  3566. echo " Please check that container is healthy. Here are last logs:" >&2
  3567. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  3568. return 1
  3569. }
  3570. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  3571. echo "$container_network:$container_ip"
  3572. }
  3573. export -f get_healthy_container_ip_for_service
  3574. switch_to_relation_service() {
  3575. local relation="$1"
  3576. ## XXXvlab: can't get real config here
  3577. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  3578. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  3579. return 1
  3580. fi
  3581. export SERVICE_NAME="$ts"
  3582. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3583. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$SERVICE_NAME")
  3584. export DOCKER_BASE_IMAGE
  3585. target_charm=$(get_service_charm "$ts") || return 1
  3586. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3587. cd "$target_charm_path"
  3588. }
  3589. export -f switch_to_relation_service
  3590. get_volumes_for_container() {
  3591. local container="$1"
  3592. docker inspect \
  3593. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3594. "$container"
  3595. }
  3596. export -f get_volumes_for_container
  3597. is_volume_used() {
  3598. local volume="$1" container_id src dst
  3599. while read -r container_id; do
  3600. while read-0 src dst; do
  3601. [[ "$src/" == "$volume"/* ]] && return 0
  3602. done < <(get_volumes_for_container "$container_id")
  3603. done < <(get_running_compose_containers)
  3604. return 1
  3605. }
  3606. export -f is_volume_used
  3607. clean_unused_docker_compose() {
  3608. for f in /var/lib/compose/docker-compose/*; do
  3609. [ -e "$f" ] || continue
  3610. is_volume_used "$f" && continue
  3611. debug "Cleaning unused docker-compose ${f##*/}"
  3612. rm -rf "$f" || return 1
  3613. done
  3614. return 0
  3615. }
  3616. export -f clean_unused_docker_compose
  3617. docker_compose_store() {
  3618. local file="$1" sha
  3619. sha=$(hash_get 64 < "$file") || return 1
  3620. project=$(get_default_project_name) || return 1
  3621. dst="/var/lib/compose/docker-compose/$sha/$project"
  3622. mkdir -p "$dst" || return 1
  3623. cat <<EOF > "$dst/.env" || return 1
  3624. DOCKER_COMPOSE_PATH=$dst
  3625. COMPOSE_HTTP_TIMEOUT=7200
  3626. EOF
  3627. cp "$file" "$dst/docker-compose.yml" || return 1
  3628. mkdir -p "$dst/bin" || return 1
  3629. cat <<EOF > "$dst/bin/dc" || return 1
  3630. #!/bin/bash
  3631. $(declare -f read-0)
  3632. docker_run_opts=()
  3633. while read-0 opt; do
  3634. if [[ "\$opt" == "!env:"* ]]; then
  3635. opt="\${opt##!env:}"
  3636. var="\${opt%%=*}"
  3637. value="\${opt#*=}"
  3638. export "\$var"="\$value"
  3639. else
  3640. docker_run_opts+=("\$opt")
  3641. fi
  3642. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3643. docker_run_opts+=(
  3644. "-w" "$dst"
  3645. "--entrypoint" "/usr/local/bin/docker-compose"
  3646. )
  3647. [ -t 1 ] && {
  3648. docker_run_opts+=("-ti")
  3649. }
  3650. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3651. EOF
  3652. chmod +x "$dst/bin/dc" || return 1
  3653. printf "%s" "$sha"
  3654. }
  3655. export -f docker_compose_store
  3656. launch_docker_compose() {
  3657. local charm docker_compose_tmpdir docker_compose_dir
  3658. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3659. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3660. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3661. ## docker-compose will name network from the parent dir name
  3662. project=$(get_default_project_name)
  3663. mkdir -p "$docker_compose_tmpdir/$project"
  3664. docker_compose_dir="$docker_compose_tmpdir/$project"
  3665. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  3666. err "${FUNCNAME[0]} is meant to be called after"\
  3667. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  3668. echo " Called by:" >&2
  3669. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  3670. return 1
  3671. fi
  3672. cat "$_CURRENT_DOCKER_COMPOSE" > "$docker_compose_dir/docker-compose.yml" || return 1
  3673. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3674. # debug "Merging some config data in docker-compose.yml:"
  3675. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3676. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3677. fi
  3678. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3679. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3680. fi
  3681. ## XXXvlab: could be more specific and only link the needed charms
  3682. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3683. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3684. # if charm.exists "$charm"; then
  3685. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3686. # fi
  3687. # done
  3688. mkdir "$docker_compose_dir/.data"
  3689. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3690. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3691. fi
  3692. {
  3693. {
  3694. {
  3695. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3696. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3697. else
  3698. cd "$docker_compose_dir" || return 1
  3699. fi
  3700. if [ -f ".env" ]; then
  3701. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3702. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3703. fi
  3704. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3705. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3706. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3707. if [ "$DRY_COMPOSE_RUN" ]; then
  3708. echo docker-compose "$@"
  3709. else
  3710. docker-compose "$@"
  3711. fi
  3712. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3713. } | _save stdout
  3714. } 3>&1 1>&2 2>&3 | _save stderr
  3715. } 3>&1 1>&2 2>&3
  3716. if tail -n 1 "$docker_compose_dir/.data/stderr" | grep -E "Service .+ failed to build: Error getting container [0-9a-f]+ from driver devicemapper: (open|Error mounting) /dev/mapper/docker-.*: no such file or directory$" >/dev/null 2>&1; then
  3717. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3718. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3719. fi
  3720. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3721. if [ -z "$docker_compose_errlvl" ]; then
  3722. err "Something went wrong before you could gather docker-compose errorlevel."
  3723. return 1
  3724. fi
  3725. return "$docker_compose_errlvl"
  3726. }
  3727. export -f launch_docker_compose
  3728. get_compose_yml_location() {
  3729. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3730. echo "$COMPOSE_YML_FILE"
  3731. return 0
  3732. fi
  3733. parent=$(while ! [ -f "./compose.yml" ]; do
  3734. [ "$PWD" == "/" ] && exit 0
  3735. cd ..
  3736. done; echo "$PWD"
  3737. )
  3738. if [ "$parent" ]; then
  3739. echo "$parent/compose.yml"
  3740. return 0
  3741. fi
  3742. ## XXXvlab: do we need this additional environment variable,
  3743. ## COMPOSE_YML_FILE is not sufficient ?
  3744. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3745. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3746. warn "No 'compose.yml' was found in current or parent dirs," \
  3747. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3748. "(${DEFAULT_COMPOSE_FILE})"
  3749. return 0
  3750. fi
  3751. echo "$DEFAULT_COMPOSE_FILE"
  3752. return 0
  3753. fi
  3754. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3755. return 0
  3756. }
  3757. export -f get_compose_yml_location
  3758. get_compose_yml_content() {
  3759. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3760. if [ -e "$cache_file" ]; then
  3761. cat "$cache_file" &&
  3762. touch "$cache_file" || return 1
  3763. return 0
  3764. fi
  3765. if [ -z "$COMPOSE_YML_FILE" ]; then
  3766. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3767. fi
  3768. if [ -e "$COMPOSE_YML_FILE" ]; then
  3769. # debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3770. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3771. err "Could not read '$COMPOSE_YML_FILE'."
  3772. return 1
  3773. }
  3774. else
  3775. debug "No compose file found. Using an empty one."
  3776. COMPOSE_YML_CONTENT=""
  3777. fi
  3778. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3779. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3780. if [ "$?" != 0 ]; then
  3781. outputed_something=
  3782. while IFS='' read -r line1 && IFS='' read -r line2; do
  3783. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3784. outputed_something=true
  3785. echo "$line1 $GRAY($line2)$NORMAL"
  3786. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3787. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3788. prefix " $GRAY|$NORMAL "
  3789. [ "$outputed_something" ] || {
  3790. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3791. echo "$output" | prefix " $GRAY|$NORMAL "
  3792. }
  3793. return 1
  3794. fi
  3795. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3796. }
  3797. export -f get_compose_yml_content
  3798. compose:yml:hash() {
  3799. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3800. if [ -e "$cache_file" ]; then
  3801. cat "$cache_file" &&
  3802. touch "$cache_file" || return 1
  3803. return 0
  3804. fi
  3805. compose_yml_content=$(get_compose_yml_content) || return 1
  3806. compose_yml_hash=$(echo "$compose_yml_content" | hash_get) || return 1
  3807. e "$compose_yml_hash" | tee "$cache_file" || return 1
  3808. }
  3809. export -f compose:yml:hash
  3810. compose:yml:root:services() {
  3811. local cache_file="$state_tmpdir/$FUNCNAME.cache" services compose_yml_content
  3812. if [ -e "$cache_file" ]; then
  3813. cat "$cache_file" &&
  3814. touch "$cache_file" || return 1
  3815. return 0
  3816. fi
  3817. compose_yml_content=$(get_compose_yml_content) || return 1
  3818. services=($(e "$compose_yml_content" | shyaml keys)) || return 1
  3819. e "${services[*]}" | tee "$cache_file" || return 1
  3820. }
  3821. export -f compose:yml:root:services
  3822. get_default_target_services() {
  3823. local services=("$@")
  3824. if [ -z "${services[*]}" ]; then
  3825. if [ "$DEFAULT_SERVICES" ]; then
  3826. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3827. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3828. services="$DEFAULT_SERVICES"
  3829. else
  3830. err "No service provided."
  3831. return 1
  3832. fi
  3833. fi
  3834. echo "${services[*]}"
  3835. }
  3836. export -f get_default_target_services
  3837. get_master_services() {
  3838. local loaded master_service service
  3839. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" )"
  3840. if [ -e "$cache_file" ]; then
  3841. cat "$cache_file" &&
  3842. touch "$cache_file" || return 1
  3843. return 0
  3844. fi
  3845. declare -A loaded
  3846. for service in "$@"; do
  3847. master_service=$(get_top_master_service_for_service "$service") || return 1
  3848. if [ "${loaded[$master_service]}" ]; then
  3849. continue
  3850. fi
  3851. echo "$master_service"
  3852. loaded["$master_service"]=1
  3853. done > "$cache_file".wip || return 1
  3854. mv "$cache_file"{.wip,} || return 1
  3855. cat "$cache_file" || return 1
  3856. }
  3857. export -f get_master_services
  3858. get_current_docker_container_id() {
  3859. local line
  3860. line=$(cat "/proc/self/cpuset") || return 1
  3861. [[ "$line" == *docker* ]] || return 1
  3862. echo "${line##*/}"
  3863. }
  3864. export -f get_current_docker_container_id
  3865. ## if we are in a docker compose, we might want to know what is the
  3866. ## real host path of some local paths.
  3867. get_host_path() {
  3868. local path="$1"
  3869. path=$(realpath "$path") || return 1
  3870. container_id=$(get_current_docker_container_id) || {
  3871. print "%s" "$path"
  3872. return 0
  3873. }
  3874. biggest_dst=
  3875. current_src=
  3876. while read-0 src dst; do
  3877. [[ "$path" == "$dst"* ]] || continue
  3878. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3879. biggest_dst="$dst"
  3880. current_src="$src"
  3881. fi
  3882. done < <(get_volumes_for_container "$container_id")
  3883. if [ "$current_src" ]; then
  3884. printf "%s" "$current_src"
  3885. else
  3886. return 1
  3887. fi
  3888. }
  3889. export -f get_host_path
  3890. _setup_state_dir() {
  3891. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3892. #debug "Creating temporary state directory in '$state_tmpdir'."
  3893. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3894. # rm -rf \"$state_tmpdir\""
  3895. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3896. }
  3897. get_docker_compose_help_msg() {
  3898. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3899. docker_compose_help_msg
  3900. if [ -e "$cache_file" ]; then
  3901. cat "$cache_file" &&
  3902. touch "$cache_file" || return 1
  3903. return 0
  3904. fi
  3905. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3906. echo "$docker_compose_help_msg" |
  3907. tee "$cache_file" || return 1
  3908. }
  3909. get_docker_compose_usage() {
  3910. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3911. docker_compose_help_msg
  3912. if [ -e "$cache_file" ]; then
  3913. cat "$cache_file" &&
  3914. touch "$cache_file" || return 1
  3915. return 0
  3916. fi
  3917. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3918. echo "$docker_compose_help_msg" |
  3919. grep -m 1 "^Usage:" -A 10000 |
  3920. egrep -m 1 "^\$" -B 10000 |
  3921. nspc |
  3922. sed -r 's/^Usage: //g' |
  3923. tee "$cache_file" || return 1
  3924. }
  3925. get_docker_compose_opts_help() {
  3926. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3927. docker_compose_help_msg
  3928. if [ -e "$cache_file" ]; then
  3929. cat "$cache_file" &&
  3930. touch "$cache_file" || return 1
  3931. return 0
  3932. fi
  3933. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3934. echo "$docker_compose_opts_help" |
  3935. grep '^Options:' -A 20000 |
  3936. tail -n +2 |
  3937. { cat ; echo; } |
  3938. egrep -m 1 "^\S*\$" -B 10000 |
  3939. head -n -1 |
  3940. tee "$cache_file" || return 1
  3941. }
  3942. get_docker_compose_commands_help() {
  3943. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3944. docker_compose_help_msg
  3945. if [ -e "$cache_file" ]; then
  3946. cat "$cache_file" &&
  3947. touch "$cache_file" || return 1
  3948. return 0
  3949. fi
  3950. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3951. echo "$docker_compose_opts_help" |
  3952. grep '^Commands:' -A 20000 |
  3953. tail -n +2 |
  3954. { cat ; echo; } |
  3955. egrep -m 1 "^\S*\$" -B 10000 |
  3956. head -n -1 |
  3957. tee "$cache_file" || return 1
  3958. }
  3959. get_docker_compose_opts_list() {
  3960. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3961. docker_compose_help_msg
  3962. if [ -e "$cache_file" ]; then
  3963. cat "$cache_file" &&
  3964. touch "$cache_file" || return 1
  3965. return 0
  3966. fi
  3967. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3968. echo "$docker_compose_opts_help" |
  3969. egrep "^\s+-" |
  3970. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3971. tee "$cache_file" || return 1
  3972. }
  3973. options_parser() {
  3974. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3975. printf "\0"
  3976. }
  3977. remove_options_in_option_help_msg() {
  3978. {
  3979. read-0 null
  3980. if [ "$null" ]; then
  3981. err "options parsing error, should start with an option line."
  3982. return 1
  3983. fi
  3984. while read-0 opt full_txt;do
  3985. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3986. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3987. for to_remove in "$@"; do
  3988. str_matches "$to_remove" $multi_opts $single_opts && {
  3989. continue 2
  3990. }
  3991. done
  3992. echo -n "$full_txt"
  3993. done
  3994. } < <(options_parser)
  3995. }
  3996. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3997. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3998. multi_opts_filter() {
  3999. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  4000. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  4001. tr ',' "\n" | nspc
  4002. }
  4003. single_opts_filter() {
  4004. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  4005. tr ',' "\n" | nspc
  4006. }
  4007. get_docker_compose_multi_opts_list() {
  4008. local action="$1" opts_list
  4009. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4010. echo "$opts_list" | multi_opts_filter
  4011. }
  4012. get_docker_compose_single_opts_list() {
  4013. local action="$1" opts_list
  4014. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4015. echo "$opts_list" | single_opts_filter
  4016. }
  4017. display_commands_help() {
  4018. local charm_actions
  4019. echo
  4020. echo "${WHITE}Commands${NORMAL} (added by compose):"
  4021. echo " ${DARKCYAN}cache${NORMAL} Control compose's cache"
  4022. echo " ${DARKCYAN}status${NORMAL} Display statuses of services"
  4023. echo
  4024. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  4025. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  4026. charm_actions_help=$(get_docker_charm_action_help) || return 1
  4027. if [ "$charm_actions_help" ]; then
  4028. echo
  4029. echo "${WHITE}Charm actions${NORMAL}:"
  4030. printf "%s\n" "$charm_actions_help" | \
  4031. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  4032. fi
  4033. }
  4034. get_docker_charm_action() {
  4035. local services service charm relation_name target_service relation_config \
  4036. target_charm services
  4037. ## XXXvlab: this is for get_service_relations
  4038. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4039. err-d "Failed to set relations hash."
  4040. return 1
  4041. }
  4042. services=($(get_all_services)) || return 1
  4043. for service in "${services[@]}"; do
  4044. printf "%s:\n" "$service"
  4045. charm=$(get_service_charm "$service") || return 1
  4046. for action in $(charm.ls_direct_actions "$charm"); do
  4047. printf " %s:\n" "$action"
  4048. printf " type: %s\n" "direct"
  4049. done
  4050. while read-0 relation_name target_service _relation_config _tech_dep; do
  4051. target_charm=$(get_service_charm "$target_service") || return 1
  4052. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4053. printf " %s:\n" "$action"
  4054. printf " type: %s\n" "indirect"
  4055. printf " inherited: %s\n" "$target_charm"
  4056. done
  4057. done < <(get_service_relations "$service")
  4058. done
  4059. }
  4060. export -f get_docker_charm_action
  4061. get_docker_charm_action_help() {
  4062. local services service charm relation_name target_service relation_config \
  4063. target_charm
  4064. ## XXXvlab: this is for get_service_relations
  4065. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4066. err-d "Failed to set relations hash."
  4067. return 1
  4068. }
  4069. services=($(get_all_services)) || return 1
  4070. for service in "${services[@]}"; do
  4071. out=$(
  4072. charm=$(get_service_charm "$service") || return 1
  4073. for action in $(charm.ls_direct_actions "$charm"); do
  4074. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  4075. done
  4076. while read-0 relation_name target_service _relation_config _tech_dep; do
  4077. target_charm=$(get_service_charm "$target_service") || return 1
  4078. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4079. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  4080. done
  4081. done < <(get_service_relations "$service")
  4082. )
  4083. if [ "$out" ]; then
  4084. echo " for ${DARKYELLOW}$service${NORMAL}:"
  4085. printf "%s\n" "$out"
  4086. fi
  4087. done
  4088. }
  4089. display_help() {
  4090. print_help
  4091. echo "${WHITE}Usage${NORMAL}:"
  4092. echo " $usage"
  4093. echo " $usage cache {clean|clear}"
  4094. echo "${WHITE}Options${NORMAL}:"
  4095. echo " -h, --help Print this message and quit"
  4096. echo " (ignoring any other options)"
  4097. echo " -V, --version Print current version and quit"
  4098. echo " (ignoring any other options)"
  4099. echo " --dirs Display data dirs and quit"
  4100. echo " (ignoring any other options)"
  4101. echo " --get-project-name Display project name and quit"
  4102. echo " (ignoring any other options)"
  4103. echo " --get-available-actions Display all available actions and quit"
  4104. echo " (ignoring any other options)"
  4105. echo " -v, --verbose Be more verbose"
  4106. echo " -q, --quiet Be quiet"
  4107. echo " -d, --debug Print full debugging information (sets also verbose)"
  4108. echo " --dry-compose-run If docker-compose will be run, only print out what"
  4109. echo " command line will be used."
  4110. echo " --no-relations Do not run any relation script"
  4111. echo " --no-hooks Do not run any hook script"
  4112. echo " --no-init Do not run any init script"
  4113. echo " --no-post-deploy Do not run any post-deploy script"
  4114. echo " --no-pre-deploy Do not run any pre-deploy script"
  4115. echo " --without-relation RELATION "
  4116. echo " Do not run given relation"
  4117. echo " -R, --rebuild-relations-to-service SERVICE"
  4118. echo " Will rebuild all relations to given service"
  4119. echo " --add-compose-content, -Y YAML"
  4120. echo " Will merge some direct YAML with the current compose"
  4121. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  4122. echo " --push-builds Will push cached docker images to docker cache registry"
  4123. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  4124. filter_docker_compose_help_message
  4125. display_commands_help
  4126. }
  4127. _graph_service() {
  4128. local service="$1" base="$1"
  4129. charm=$(get_service_charm "$service") || return 1
  4130. metadata=$(charm.metadata "$charm") || return 1
  4131. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  4132. if [[ "$subordinate" =~ ^True|true$ ]]; then
  4133. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  4134. master_charm=
  4135. while read-0 relation_name relation; do
  4136. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  4137. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  4138. if [ -z "$interface" ]; then
  4139. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  4140. return 1
  4141. fi
  4142. ## Action provided by relation ?
  4143. target_service=
  4144. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  4145. [ "$interface" == "$relation_name" ] && {
  4146. target_service="$candidate_target_service"
  4147. break
  4148. }
  4149. done < <(get_service_relations "$service")
  4150. if [ -z "$target_service" ]; then
  4151. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  4152. "${DARKYELLOW}$service$NORMAL compose definition."
  4153. return 1
  4154. fi
  4155. master_service="$target_service"
  4156. master_charm=$(get_service_charm "$target_service") || return 1
  4157. break
  4158. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  4159. fi
  4160. _graph_node_service "$service" "$base" "$charm"
  4161. _graph_edge_service "$service" "$subordinate" "$master_service"
  4162. }
  4163. _graph_node_service() {
  4164. local service="$1" base="$2" charm="$3"
  4165. cat <<EOF
  4166. "$(_graph_node_service_label ${service})" [
  4167. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  4168. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  4169. color = $([ "$base" ] && echo "blue" || echo "black")
  4170. fillcolor = "white"
  4171. fontname = "Courier New"
  4172. shape = "Mrecord"
  4173. label =<$(_graph_node_service_content "$service")>
  4174. ];
  4175. EOF
  4176. }
  4177. _graph_edge_service() {
  4178. local service="$1" subordinate="$2" master_service="$3"
  4179. while read-0 relation_name target_service relation_config tech_dep; do
  4180. cat <<EOF
  4181. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  4182. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  4183. fontsize = 16
  4184. fontcolor = "black"
  4185. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  4186. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  4187. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  4188. arrowtail = odot
  4189. # arrowhead = dotlicurve
  4190. taillabel = "$relation_name" ];
  4191. EOF
  4192. done < <(get_service_relations "$service") || return 1
  4193. }
  4194. _graph_node_service_label() {
  4195. local service="$1"
  4196. echo "service_$service"
  4197. }
  4198. _graph_node_service_content() {
  4199. local service="$1"
  4200. charm=$(get_service_charm "$service") || return 1
  4201. cat <<EOF
  4202. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  4203. <tr>
  4204. <td bgcolor="black" align="center" colspan="2">
  4205. <font color="white">$service</font>
  4206. </td>
  4207. </tr>
  4208. $(if [ "$charm" != "$service" ]; then
  4209. cat <<EOF2
  4210. <tr>
  4211. <td align="left" port="r0">charm: $charm</td>
  4212. </tr>
  4213. EOF2
  4214. fi)
  4215. </table>
  4216. EOF
  4217. }
  4218. cla_contains () {
  4219. local e
  4220. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  4221. return 1
  4222. }
  4223. filter_docker_compose_help_message() {
  4224. cat - |
  4225. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  4226. s/docker-compose.yml/compose.yml/g;
  4227. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  4228. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  4229. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  4230. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  4231. }
  4232. graph() {
  4233. local services=("$@")
  4234. declare -A entries
  4235. cat <<EOF
  4236. digraph g {
  4237. graph [
  4238. fontsize=30
  4239. labelloc="t"
  4240. label=""
  4241. splines=true
  4242. overlap=false
  4243. #rankdir = "LR"
  4244. ];
  4245. ratio = auto;
  4246. EOF
  4247. for target_service in "$@"; do
  4248. services=$(get_ordered_service_dependencies "$target_service") || return 1
  4249. for service in $services; do
  4250. [ "${entries[$service]}" ] && continue || entries[$service]=1
  4251. if cla_contains "$service" "${services[@]}"; then
  4252. base=true
  4253. else
  4254. base=
  4255. fi
  4256. _graph_service "$service" "$base"
  4257. done
  4258. done
  4259. echo "}"
  4260. }
  4261. cached_wget() {
  4262. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  4263. url="$1"
  4264. if [ -e "$cache_file" ]; then
  4265. cat "$cache_file"
  4266. touch "$cache_file"
  4267. return 0
  4268. fi
  4269. wget -O- "${url}" |
  4270. tee "$cache_file"
  4271. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4272. rm "$cache_file"
  4273. die "Unable to fetch '$url'."
  4274. return 1
  4275. fi
  4276. }
  4277. export -f cached_wget
  4278. [ "$SOURCED" ] && return 0
  4279. trap_add "EXIT" clean_cache
  4280. export COMPOSE_DOCKER_REGISTRY="${COMPOSE_DOCKER_REGISTRY:-docker.0k.io}"
  4281. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  4282. if [ -r /etc/default/charm ]; then
  4283. . "/etc/default/charm"
  4284. fi
  4285. if [ -r "/etc/default/$exname" ]; then
  4286. . "/etc/default/$exname"
  4287. fi
  4288. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  4289. ## userdir ? and global /etc/compose.yml ?
  4290. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  4291. /etc/default/compose /etc/compose/local.conf; do
  4292. [ -e "$cfgfile" ] || continue
  4293. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  4294. done
  4295. fi
  4296. _setup_state_dir
  4297. mkdir -p "$CACHEDIR" || exit 1
  4298. log () { cat; }
  4299. export -f log
  4300. ##
  4301. ## Argument parsing
  4302. ##
  4303. wrap_opts=()
  4304. services=()
  4305. remainder_args=()
  4306. compose_opts=()
  4307. compose_contents=()
  4308. action_opts=()
  4309. services_args=()
  4310. pos_arg_ct=0
  4311. no_hooks=
  4312. no_init=
  4313. action=
  4314. stage="main" ## switches from 'main', to 'action', 'remainder'
  4315. is_docker_compose_action=
  4316. is_docker_compose_action_multi_service=
  4317. rebuild_relations_to_service=()
  4318. color=
  4319. declare -A without_relations
  4320. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  4321. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  4322. while read-0 arg; do
  4323. case "$stage" in
  4324. "main")
  4325. case "$arg" in
  4326. --help|-h)
  4327. no_init=true ; no_hooks=true ; no_relations=true
  4328. display_help
  4329. exit 0
  4330. ;;
  4331. --verbose|-v)
  4332. export VERBOSE=true
  4333. compose_opts+=("--verbose")
  4334. ;;
  4335. --quiet|-q)
  4336. export QUIET=true
  4337. export wrap_opts+=("-q")
  4338. log () { cat >&2; }
  4339. export -f log
  4340. ;;
  4341. --version|-V)
  4342. print_version
  4343. docker-compose --version
  4344. docker --version
  4345. exit 0
  4346. ;;
  4347. -f|--file)
  4348. read-0 value
  4349. [ -e "$value" ] || die "File $value doesn't exists"
  4350. export COMPOSE_YML_FILE="$value"
  4351. shift
  4352. ;;
  4353. -p|--project-name)
  4354. read-0 value
  4355. export DEFAULT_PROJECT_NAME="$value"
  4356. compose_opts+=("--project-name $value")
  4357. shift
  4358. ;;
  4359. --color|-c)
  4360. if [ "$color" == "0" ]; then
  4361. err "Conflicting option --color with previous --no-ansi."
  4362. exit 1
  4363. fi
  4364. color=1
  4365. ansi_color yes
  4366. ;;
  4367. --no-ansi)
  4368. if [ "$color" == "1" ]; then
  4369. err "Conflicting option --no-ansi with previous --color."
  4370. exit 1
  4371. fi
  4372. color=0
  4373. ansi_color no
  4374. compose_opts+=("--no-ansi")
  4375. ;;
  4376. --no-relations)
  4377. export no_relations=true
  4378. ;;
  4379. --without-relation)
  4380. read-0 value
  4381. without_relations["$value"]=1
  4382. shift
  4383. ;;
  4384. --no-hooks)
  4385. export no_hooks=true
  4386. ;;
  4387. --no-init)
  4388. export no_init=true
  4389. ;;
  4390. --no-post-deploy)
  4391. export no_post_deploy=true
  4392. ;;
  4393. --no-pre-deploy)
  4394. export no_pre_deploy=true
  4395. ;;
  4396. --rebuild-relations-to-service|-R)
  4397. read-0 value
  4398. rebuild_relations_to_service+=("$value")
  4399. shift
  4400. ;;
  4401. --push-builds)
  4402. export COMPOSE_PUSH_TO_REGISTRY=1
  4403. ;;
  4404. --debug|-d)
  4405. export DEBUG=true
  4406. export VERBOSE=true
  4407. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  4408. ;;
  4409. --add-compose-content|-Y)
  4410. read-0 value
  4411. compose_contents+=("$value")
  4412. shift
  4413. ;;
  4414. --dirs)
  4415. echo "CACHEDIR: $CACHEDIR"
  4416. echo "VARDIR: $VARDIR"
  4417. exit 0
  4418. ;;
  4419. --get-project-name)
  4420. project=$(get_default_project_name) || exit 1
  4421. echo "$project"
  4422. exit 0
  4423. ;;
  4424. --get-available-actions)
  4425. get_docker_charm_action
  4426. exit $?
  4427. ;;
  4428. --dry-compose-run)
  4429. export DRY_COMPOSE_RUN=true
  4430. ;;
  4431. --*|-*)
  4432. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4433. read-0 value
  4434. compose_opts+=("$arg" "$value")
  4435. shift;
  4436. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4437. compose_opts+=("$arg")
  4438. else
  4439. err "Unknown option '$arg'. Please check help:"
  4440. display_help >&2
  4441. exit 1
  4442. fi
  4443. ;;
  4444. *)
  4445. action="$arg"
  4446. stage="action"
  4447. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  4448. is_docker_compose_action=true
  4449. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  4450. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  4451. if [ "$DC_MATCH_MULTI" ]; then
  4452. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  4453. fi
  4454. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  4455. pos_args=("${pos_args[@]:1}")
  4456. if [[ "${pos_args[0]}" == "[SERVICE...]" ]]; then
  4457. is_docker_compose_action_multi_service=1
  4458. elif [[ "${pos_args[0]}" == "SERVICE" ]]; then
  4459. is_docker_compose_action_multi_service=0
  4460. fi
  4461. # echo "USAGE: $DC_USAGE"
  4462. # echo "pos_args: ${pos_args[@]}"
  4463. # echo "MULTI: $DC_MATCH_MULTI"
  4464. # echo "SINGLE: $DC_MATCH_SINGLE"
  4465. # exit 1
  4466. else
  4467. stage="remainder"
  4468. fi
  4469. ;;
  4470. esac
  4471. ;;
  4472. "action") ## Only for docker-compose actions
  4473. case "$arg" in
  4474. --help|-h)
  4475. no_init=true ; no_hooks=true ; no_relations=true
  4476. action_opts+=("$arg")
  4477. ;;
  4478. --*|-*)
  4479. if [ "$is_docker_compose_action" ]; then
  4480. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4481. read-0 value
  4482. action_opts+=("$arg" "$value")
  4483. shift
  4484. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4485. action_opts+=("$arg")
  4486. else
  4487. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  4488. docker-compose "$action" --help |
  4489. filter_docker_compose_help_message >&2
  4490. exit 1
  4491. fi
  4492. fi
  4493. ;;
  4494. *)
  4495. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  4496. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  4497. services_args+=("$arg")
  4498. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  4499. services_args=("$arg") || exit 1
  4500. stage="remainder"
  4501. else
  4502. action_posargs+=("$arg")
  4503. ((pos_arg_ct++))
  4504. fi
  4505. ;;
  4506. esac
  4507. ;;
  4508. "remainder")
  4509. remainder_args+=("$arg")
  4510. while read-0 arg; do
  4511. remainder_args+=("$arg")
  4512. done
  4513. break 3
  4514. ;;
  4515. esac
  4516. shift
  4517. done < <(cla.normalize "$@")
  4518. ## These actions are additions to docker-compose actions and charm
  4519. ## actions
  4520. more_actions=(status)
  4521. if [[ "$action" == *" "* ]]; then
  4522. err "Invalid action name containing spaces: ${DARKCYAN}$action${NORMAL}"
  4523. exit 1
  4524. fi
  4525. is_more_action=
  4526. [[ " ${more_actions[*]} " == *" $action "* ]] && is_more_action=true
  4527. [ -n "$CACHEDIR" ] || die "No cache directory defined."
  4528. [ -d "$CACHEDIR" ] || die "Cache directory '$CACHEDIR' doesn't exists."
  4529. case "$action" in
  4530. cache)
  4531. case "${remainder_args[0]}" in
  4532. clean)
  4533. clean_cache
  4534. exit 0
  4535. ;;
  4536. clear)
  4537. Wrap "${wrap_opts[@]}" -v -d "clear cache directory" -- rm -rf "$CACHEDIR/"*
  4538. ## clear all docker caches
  4539. ## image name are like '[$COMPOSE_DOCKER_REGISTRY]cache/charm/CHARM_NAME:HASH'
  4540. Wrap "${wrap_opts[@]}" -v -d "clear docker cache" <<EOF
  4541. docker images --format "{{.Repository}}:{{.Tag}}" |
  4542. egrep "^($COMPOSE_DOCKER_REGISTRY/)?cache/charm/[a-zA-Z0-9._-]+:[0-9a-f]{32,32}$" |
  4543. while read -r image; do
  4544. docker rmi "\$image" || true
  4545. done
  4546. EOF
  4547. exit 0
  4548. ;;
  4549. *)
  4550. err "Unknown cache command: ${DARKCYAN}${remainder_args[0]}${NORMAL}"
  4551. exit 1
  4552. ;;
  4553. esac
  4554. ;;
  4555. status)
  4556. state_inner_cols=(name charm type state root)
  4557. state_all_services=
  4558. state_services=()
  4559. state_columns=()
  4560. state_columns_default=(name charm type state version)
  4561. state_filters=()
  4562. state_columns_default_msg=""
  4563. for col in "${state_columns_default[@]}"; do
  4564. if [ -n "$state_columns_default_msg" ]; then
  4565. state_columns_default_msg+=","
  4566. fi
  4567. state_columns_default_msg+="$col"
  4568. done
  4569. help="\
  4570. Display status information on services.
  4571. If no services are provided, all services in the root compose file
  4572. will be displayed. Use the --all option to display status of all
  4573. services (including dependencies).
  4574. $exname offers a few possible columns that can be complete on a charm
  4575. level by implementing an \`actions/get-COLNAME\` script.
  4576. These are the compose's columns: ${state_inner_cols[@]}.
  4577. Usage: status [options] [SERVICE...]
  4578. Options:
  4579. -h, --help Print this message and quit
  4580. -a, --all Display status of all services
  4581. (removes all filter, and will add a
  4582. 'root' first column by default)
  4583. -c, --column Column to display, can provide several
  4584. separated by commas, or option can be repeated.
  4585. (default: ${state_columns_default_msg})
  4586. -f, --filter Filter services by a key=value pair,
  4587. separated by commas or can be repeated.
  4588. (default: --filter root=yes)
  4589. "
  4590. while read-0 arg; do
  4591. case "$arg" in
  4592. --help|-h)
  4593. echo "$help"
  4594. exit 0
  4595. ;;
  4596. --all|-a)
  4597. if [ "${#state_services[@]}" -gt 0 ]; then
  4598. err "Cannot use --all and provide services at the same time."
  4599. exit 1
  4600. fi
  4601. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4602. err "Cannot use --all and provide filters at the same time."
  4603. exit 1
  4604. fi
  4605. state_all_services=1
  4606. ;;
  4607. --column|-c)
  4608. read-0 value
  4609. if [[ "$value" == *,* ]]; then
  4610. state_columns+=(${value//,/ })
  4611. else
  4612. state_columns+=("$value")
  4613. fi
  4614. ;;
  4615. --filter|-f)
  4616. if [ "${#state_services[@]}" -gt 0 ]; then
  4617. err "Cannot use --filter and provide services at the same time."
  4618. exit 1
  4619. fi
  4620. if [ -n "$state_all_services" ]; then
  4621. err "Cannot use --all and provide filters at the same time."
  4622. exit 1
  4623. fi
  4624. read-0 value
  4625. if [[ "$value" == *,* ]]; then
  4626. state_filters+=(${value//,/ })
  4627. else
  4628. state_filters+=("$value")
  4629. fi
  4630. ;;
  4631. --*|-*)
  4632. err "Unknown option '$arg'. Please check help:"
  4633. echo "$help" >&2
  4634. ;;
  4635. *)
  4636. if [ -n "$state_all_services" ]; then
  4637. err "Cannot use --all and provide services at the same time."
  4638. exit 1
  4639. fi
  4640. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4641. err "Cannot use --filter and provide filters at the same time."
  4642. exit 1
  4643. fi
  4644. state_services+=("$arg")
  4645. ;;
  4646. esac
  4647. done < <(cla.normalize "${remainder_args[@]}")
  4648. if [ "${#state_columns[@]}" == 0 ]; then
  4649. state_columns=("${state_columns_default[@]}")
  4650. fi
  4651. ;;
  4652. esac
  4653. export compose_contents
  4654. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  4655. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  4656. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  4657. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  4658. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  4659. aexport remainder_args
  4660. ##
  4661. ## Actual code
  4662. ##
  4663. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  4664. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  4665. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || exit 1
  4666. CHARM_STORE_HASH=$(charm.store_metadata_hash) || exit 1
  4667. COMBINED_HASH=$(H "$COMPOSE_YML_CONTENT_HASH" "$CHARM_STORE_HASH") || exit 1
  4668. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT COMPOSE_YML_CONTENT_HASH CHARM_STORE_HASH COMBINED_HASH
  4669. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  4670. ##
  4671. ## Get services in command line.
  4672. ##
  4673. if [ -z "$is_docker_compose_action" ] && [ -z "$is_more_action" ] && [ -n "$action" ]; then
  4674. action_service=${remainder_args[0]}
  4675. if [ -z "$action_service" ]; then
  4676. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  4677. display_commands_help
  4678. exit 1
  4679. fi
  4680. services_args=($(compose:yml:root:services)) || return 1
  4681. ## Required by has_service_action
  4682. service:all:set_relations_hash
  4683. remainder_args=("${remainder_args[@]:1}")
  4684. if has_service_action "$action_service" "$action" >/dev/null; then
  4685. is_service_action=true
  4686. services_args=("$action_service")
  4687. {
  4688. read-0 action_type
  4689. case "$action_type" in
  4690. "relation")
  4691. read-0 _ target_service _target_charm relation_name _ action_script_path
  4692. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  4693. services_args+=("$target_service")
  4694. ;;
  4695. "direct")
  4696. read-0 _ action_script_path
  4697. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  4698. ;;
  4699. esac
  4700. } < <(has_service_action "$action_service" "$action")
  4701. get_all_relations "${services_args[@]}" >/dev/null || {
  4702. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  4703. exit 1
  4704. }
  4705. ## Divert logging to stdout to stderr
  4706. log () { cat >&2; }
  4707. export -f log
  4708. else
  4709. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  4710. fi
  4711. else
  4712. case "$action" in
  4713. ps|up)
  4714. if [ "${#services_args[@]}" == 0 ]; then
  4715. services_args=($(compose:yml:root:services)) || return 1
  4716. fi
  4717. ;;
  4718. status)
  4719. services_args=("${state_services[@]}")
  4720. if [ "${#services_args[@]}" == 0 ] && [ -z "$state_all_services" ]; then
  4721. services_args=($(compose:yml:root:services)) || return 1
  4722. fi
  4723. ;;
  4724. config)
  4725. services_args=("${action_posargs[@]}")
  4726. ;;
  4727. esac
  4728. fi
  4729. export COMPOSE_ACTION="$action"
  4730. NO_CONSTRAINT_CHECK=True
  4731. case "$action" in
  4732. up|status)
  4733. NO_CONSTRAINT_CHECK=
  4734. if [ -n "$DEBUG" ]; then
  4735. Elt "solve all relations"
  4736. start=$(time_now)
  4737. fi
  4738. service:all:set_relations_hash || exit 1
  4739. if [ -n "$DEBUG" ]; then
  4740. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4741. print_info "$(printf "%.3fs" "$elapsed")"
  4742. Feedback
  4743. fi
  4744. all_services=($(get_all_services)) || exit 1
  4745. ## check that services_args is a subset of all_services
  4746. for service in "${services_args[@]}"; do
  4747. [[ " ${all_services[*]} " == *" $service "* ]] || {
  4748. err "Service ${DARKYELLOW}$service${NORMAL} is not defined in the current compose file."
  4749. echo " Neither is is a dependency of a service in the compose file." >&2
  4750. echo " These are the services directly or indirectly available from current compose file:" >&2
  4751. for service in "${all_services[@]}"; do
  4752. echo " - ${DARKYELLOW}$service${NORMAL}" >&2
  4753. done
  4754. exit 1
  4755. }
  4756. done
  4757. ;;
  4758. esac
  4759. case "$action" in
  4760. up)
  4761. PROJECT_NAME=$(get_default_project_name) || exit 1
  4762. ## Remove all intents (*ing states)
  4763. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*ing || true
  4764. ## Notify that we have the intent to bring up all these
  4765. ## This will be use in inner or concurrent 'run' to include the
  4766. ## services that are supposed to be up.
  4767. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME" || exit 1
  4768. services_args_deps=($(get_ordered_service_dependencies "${services_args[@]}")) || exit 1
  4769. for service in "${services_args_deps[@]}"; do
  4770. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service" || exit 1
  4771. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/up ] || {
  4772. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/deploying || exit 1
  4773. }
  4774. done
  4775. ## remove services not included in compose.yml anymore
  4776. all_services_deps=($(get_ordered_service_dependencies "${all_services[@]}")) || exit 1
  4777. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/up; do
  4778. [ -e "$service" ] || continue
  4779. state=${service##*/}
  4780. service=${service%/$state}
  4781. service=${service##*/}
  4782. if [[ " ${all_services_deps[*]} " != *" ${service} "* ]]; then
  4783. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  4784. fi
  4785. done
  4786. ;;
  4787. run)
  4788. PROJECT_NAME=$(get_default_project_name) || return 1
  4789. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  4790. ## Notify that we have the intent to bring up all these
  4791. ## This will be use in inner or concurrent 'run' to include the
  4792. ## services that are supposed to be up.
  4793. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/{up,deploying}; do
  4794. [ -e "$service" ] || continue
  4795. state=${service##*/}
  4796. service=${service%/$state}
  4797. service=${service##*/}
  4798. ## don't add if orphaning
  4799. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning ] && continue
  4800. done
  4801. fi
  4802. ;;
  4803. status)
  4804. if [ -n "${state_all_services}" ] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  4805. services_args=("${all_services[@]}")
  4806. fi
  4807. ;;
  4808. esac
  4809. if [ -n "$is_docker_compose_action_multi_service" ]; then
  4810. if [ -n "$DEBUG" ]; then
  4811. Elt "get relation subset"
  4812. start=$(time_now)
  4813. fi
  4814. get_subset_relations "${services_args[@]}" >/dev/null || exit 1
  4815. if [ -n "$DEBUG" ]; then
  4816. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4817. print_info "$(printf "%.3fs" "$elapsed")"
  4818. Feedback
  4819. fi
  4820. fi
  4821. if [ -n "$is_docker_compose_action" ] && [ "${#services_args[@]}" -gt 0 ]; then
  4822. services=($(get_master_services "${services_args[@]}")) || exit 1
  4823. if [ "$action" == "up" ]; then
  4824. action_posargs+=($(services:get:upable "${services_args[@]}")) || exit 1
  4825. elif [ "$is_docker_compose_action_multi_service" == "1" ]; then
  4826. action_posargs+=("${services[@]}")
  4827. elif [ "$is_docker_compose_action_multi_service" == "0" ]; then
  4828. action_posargs+=("${services[0]}") ## only the first service is the legit one
  4829. fi
  4830. ## Get rid of subordinates
  4831. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  4832. fi
  4833. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  4834. err "Fails to compile base 'docker-compose.yml'"
  4835. exit 1
  4836. }
  4837. ##
  4838. ## Pre-action
  4839. ##
  4840. full_init=
  4841. case "$action" in
  4842. build)
  4843. full_init=true ## will actually stop after build
  4844. ;;
  4845. up|run)
  4846. full_init=true
  4847. post_hook=true
  4848. ;;
  4849. ""|down|restart|logs|config|ps|status)
  4850. full_init=
  4851. ;;
  4852. *)
  4853. if [ "$is_service_action" ]; then
  4854. full_init=true
  4855. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4856. for keyword in "${keywords[@]}"; do
  4857. case "$keyword" in
  4858. no-hooks)
  4859. no_hooks=true
  4860. ;;
  4861. hooks)
  4862. full_init=true
  4863. ;;
  4864. esac
  4865. done
  4866. fi
  4867. ;;
  4868. esac
  4869. if [ -n "$full_init" ]; then
  4870. if [[ "$action" == "build" ]] || [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4871. [[ "$action" == "build" ]] || Section "acquire charm's images"
  4872. run_service_acquire_images "${services_args[@]}" || exit 1
  4873. Feed
  4874. [ "$action" == "build" ] && {
  4875. exit 0
  4876. }
  4877. Section setup host resources
  4878. setup_host_resources "${services_args[@]}" || exit 1
  4879. ## init in order
  4880. Section initialisation
  4881. run_service_hook init "${services_args[@]}" || exit 1
  4882. fi
  4883. ## Get relations
  4884. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4885. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4886. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4887. rebuild_relations_to_service=($rebuild_relations_to_service)
  4888. project=$(get_default_project_name) || return 1
  4889. for service in "${rebuild_relations_to_service[@]}"; do
  4890. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  4891. [ -d "$dir" ] && {
  4892. debug rm -rf "$dir"
  4893. rm -rf "$dir"
  4894. }
  4895. done
  4896. done
  4897. fi
  4898. run_service_relations "${services_args[@]}" || exit 1
  4899. fi
  4900. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  4901. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  4902. fi
  4903. fi | log
  4904. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4905. exit 1
  4906. fi
  4907. [ "$action" == "build" ] && exit 0
  4908. if [ "$action" == "status" ]; then
  4909. if [[ -n "${state_all_services}" ]] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  4910. compose_yml_services=($(compose:yml:root:services)) || exit 1
  4911. fi
  4912. if [[ -n "${state_all_services}" ]]; then
  4913. state_columns=("root" ${state_columns[@]})
  4914. fi
  4915. state_columns_raw=()
  4916. for col in "${state_columns[@]}"; do
  4917. if [[ "$col" == "-"* ]]; then
  4918. col=${col#-}
  4919. fi
  4920. state_columns_raw+=("$col")
  4921. done
  4922. state_columns_align=""
  4923. for col in "${state_columns[@]}"; do
  4924. if [[ "$col" == "-"* ]]; then
  4925. state_columns_align+="+"
  4926. else
  4927. state_columns_align+="-"
  4928. fi
  4929. done
  4930. while read-0-err E "${state_columns_raw[@]}"; do
  4931. values=()
  4932. for col in "${state_columns_raw[@]}"; do
  4933. color=
  4934. value="${!col}"
  4935. read -r -- value_trim <<<"${!col}"
  4936. case "$col" in
  4937. root)
  4938. case "$value_trim" in
  4939. 0) value=" ";;
  4940. 1) value="*";;
  4941. esac
  4942. ;;
  4943. name) color=darkyellow;;
  4944. charm) color=darkpink;;
  4945. state)
  4946. case "$value_trim" in
  4947. up) color=green;;
  4948. down) color=gray;;
  4949. deploying) color=yellow;;
  4950. *) color=red;;
  4951. esac
  4952. ;;
  4953. type)
  4954. case "$value_trim" in
  4955. run-once) color=gray;;
  4956. stub) color=gray;;
  4957. *) color=darkcyan;;
  4958. esac
  4959. ;;
  4960. *)
  4961. if [[ "${value_trim}" == "N/A" ]]; then
  4962. color=gray
  4963. fi
  4964. ;;
  4965. esac
  4966. color="${color^^}"
  4967. if [ -n "$color" ]; then
  4968. values+=("${!color}$value${NORMAL}")
  4969. else
  4970. values+=("$value")
  4971. fi
  4972. done
  4973. first=1
  4974. for value in "${values[@]}"; do
  4975. if [ -n "$first" ]; then
  4976. first=
  4977. else
  4978. printf " "
  4979. fi
  4980. printf "%s" "$value"
  4981. done
  4982. printf "\n"
  4983. done < <(
  4984. set -o pipefail
  4985. filter_cols=()
  4986. for filter in "${state_filters[@]}"; do
  4987. IFS="=" read -r key value <<<"$filter"
  4988. ## if not already in state_columns_raw
  4989. [[ " ${state_columns_raw[*]} " == *" $key "* ]] ||
  4990. filter_cols+=("$key")
  4991. done
  4992. for service in "${services_args[@]}"; do
  4993. declare -A values=()
  4994. for col in "${state_columns_raw[@]}" "${filter_cols[@]}"; do
  4995. case "$col" in
  4996. root)
  4997. if [[ " ${compose_yml_services[*]} " == *" ${service} "* ]]; then
  4998. value="1"
  4999. else
  5000. value="0"
  5001. fi
  5002. ;;
  5003. name) value="$service" ;;
  5004. charm)
  5005. value=$(get_service_charm "$service") || { echo 1; exit 1; }
  5006. ;;
  5007. state)
  5008. value=$(service:state "$service") || { echo 1; exit 1; }
  5009. ;;
  5010. type)
  5011. value=$(get_service_type "$service") || { echo 1; exit 1; }
  5012. ;;
  5013. *)
  5014. if has_service_action "$service" "get-$col" >/dev/null; then
  5015. state_msg=$(run_service_action "$service" "get-$col") || { echo 1; exit 1 ; }
  5016. if [[ "$state_msg" == *$'\n'* ]]; then
  5017. value="${state_msg%%$'\n'*}"
  5018. ## XXXvlab: For now, these are not used, but we could
  5019. ## display them in additional lines (in same "cell")
  5020. msgs="${state_msg#*$'\n'}"
  5021. else
  5022. value=${state_msg}
  5023. fi
  5024. else
  5025. value="N/A"
  5026. fi
  5027. ;;
  5028. esac
  5029. values["$col"]="$value"
  5030. done
  5031. for filter in "${state_filters[@]}"; do
  5032. IFS="=" read -r key value <<<"$filter"
  5033. [[ "${values[$key]}" != "$value" ]] &&
  5034. continue 2
  5035. done
  5036. for col in "${state_columns_raw[@]}"; do
  5037. p0 "${values[$col]}"
  5038. done
  5039. done | col-0:normalize:size "${state_columns_align}"
  5040. echo 0
  5041. )
  5042. if [ "$E" != 0 ]; then
  5043. echo "E: '$E'" >&2
  5044. exit 1
  5045. fi
  5046. exit 0
  5047. fi
  5048. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  5049. charm=$(get_service_charm "${services_args[0]}") || exit 1
  5050. metadata=$(charm.metadata "$charm") || exit 1
  5051. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  5052. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5053. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  5054. fi
  5055. fi
  5056. export SERVICE_PACK="${services_args[*]}"
  5057. ##
  5058. ## Docker-compose
  5059. ##
  5060. errlvl="0"
  5061. case "$action" in
  5062. up|start|stop|build|run)
  5063. ## force daemon mode for up
  5064. if [[ "$action" == "up" ]]; then
  5065. if ! array_member action_opts -d; then
  5066. action_opts+=("-d")
  5067. fi
  5068. if ! array_member action_opts --remove-orphans; then
  5069. action_opts+=("--remove-orphans")
  5070. fi
  5071. fi
  5072. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5073. ;;
  5074. logs)
  5075. if ! array_member action_opts --tail; then ## force daemon mode for up
  5076. action_opts+=("--tail" "10")
  5077. fi
  5078. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5079. ;;
  5080. "")
  5081. launch_docker_compose "${compose_opts[@]}"
  5082. ;;
  5083. graph)
  5084. graph $SERVICE_PACK
  5085. ;;
  5086. config)
  5087. ## removing the services
  5088. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  5089. ## forcing docker-compose config to output the config file to stdout and not stderr
  5090. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  5091. echo "$out"
  5092. exit 1
  5093. }
  5094. echo "$out"
  5095. warn "Runtime configuration modification (from relations) are not included here."
  5096. ;;
  5097. down)
  5098. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  5099. debug "Adding a default argument of '--remove-orphans'"
  5100. action_opts+=("--remove-orphans")
  5101. fi
  5102. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  5103. ;;
  5104. *)
  5105. if [ "$is_service_action" ]; then
  5106. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  5107. errlvl="$?"
  5108. errlvl "$errlvl"
  5109. else
  5110. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5111. fi
  5112. ;;
  5113. esac || exit 1
  5114. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  5115. run_service_hook post_deploy "${services_args[@]}" || exit 1
  5116. fi
  5117. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  5118. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5119. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  5120. fi
  5121. fi
  5122. case "$action" in
  5123. up)
  5124. ## Notify that services in 'deploying' states have been deployed
  5125. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/deploying; do
  5126. [ -e "$service" ] || continue
  5127. state=${service##*/}
  5128. service=${service%/$state}
  5129. service=${service##*/}
  5130. mv "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/{deploying,up} || exit 1
  5131. done
  5132. ## Notify that services in 'orphaning' states have been removed
  5133. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/orphaning; do
  5134. [ -e "$service" ] || continue
  5135. state=${service##*/}
  5136. service=${service%/$state}
  5137. service=${service##*/}
  5138. rm "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  5139. done
  5140. ;;
  5141. down)
  5142. PROJECT_NAME=$(get_default_project_name) || return 1
  5143. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  5144. if ! dir_is_empty "$SERVICE_STATE_PATH/$PROJECT_NAME"; then
  5145. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*
  5146. fi
  5147. rmdir "$SERVICE_STATE_PATH/$PROJECT_NAME"/{*,}
  5148. fi
  5149. ;;
  5150. esac
  5151. clean_unused_docker_compose || exit 1
  5152. exit "$errlvl"