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.

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