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.

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