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.

5569 lines
188 KiB

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