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.

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