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.

6229 lines
212 KiB

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