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.

6275 lines
213 KiB

4 days ago
4 days ago
4 days ago
4 days ago
  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. export -f charm:upstream-version
  2430. service:upstream-version() {
  2431. local service="$1" version
  2432. charm=$(get_service_charm "$service") || return $?
  2433. version=$(charm:upstream-version "$charm") || return $?
  2434. e "$version"
  2435. }
  2436. export -f service:upstream-version
  2437. _get_charm_metadata_uses() {
  2438. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2439. if [ -e "$cache_file" ]; then
  2440. #debug "$FUNCNAME: SESSION cache hit $1"
  2441. cat "$cache_file" || return 1
  2442. return 0
  2443. fi
  2444. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  2445. }
  2446. export -f _get_charm_metadata_uses
  2447. _get_service_metadata() {
  2448. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2449. charm
  2450. if [ -e "$cache_file" ]; then
  2451. #debug "$FUNCNAME: SESSION cache hit $1"
  2452. cat "$cache_file"
  2453. return 0
  2454. fi
  2455. charm="$(get_service_charm "$service")" || return 1
  2456. charm.metadata "$charm" > "$cache_file"
  2457. if [ "$?" != 0 ]; then
  2458. rm -f "$cache_file" ## no cache
  2459. return 1
  2460. fi
  2461. cat "$cache_file"
  2462. }
  2463. export -f _get_service_metadata
  2464. _get_service_uses() {
  2465. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2466. metadata
  2467. if [ -e "$cache_file" ]; then
  2468. #debug "$FUNCNAME: SESSION cache hit $1"
  2469. cat "$cache_file"
  2470. return 0
  2471. fi
  2472. metadata="$(_get_service_metadata "$service")" || return 1
  2473. _get_charm_metadata_uses "$metadata" > "$cache_file"
  2474. if [ "$?" != 0 ]; then
  2475. rm -f "$cache_file" ## no cache
  2476. return 1
  2477. fi
  2478. cat "$cache_file"
  2479. }
  2480. export -f _get_service_uses
  2481. _get_services_uses() {
  2482. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2483. service rn rd
  2484. if [ -e "$cache_file" ]; then
  2485. #debug "$FUNCNAME: SESSION cache hit $1"
  2486. cat "$cache_file"
  2487. return 0
  2488. fi
  2489. for service in "$@"; do
  2490. _get_service_uses "$service" | while read-0 rn rd; do
  2491. printf "%s\0" "$service" "$rn" "$rd"
  2492. done
  2493. [ "${PIPESTATUS[0]}" == 0 ] || {
  2494. return 1
  2495. }
  2496. done > "${cache_file}.wip"
  2497. mv "${cache_file}"{.wip,} &&
  2498. cat "$cache_file" || return 1
  2499. }
  2500. export -f _get_services_uses
  2501. _get_provides_provides() {
  2502. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2503. service rn rd
  2504. if [ -e "$cache_file" ]; then
  2505. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  2506. cat "$cache_file"
  2507. return 0
  2508. fi
  2509. type=$(printf "%s" "$provides" | shyaml get-type)
  2510. case "$type" in
  2511. sequence)
  2512. while read-0 prov; do
  2513. printf "%s\0" "$prov" ""
  2514. done < <(echo "$provides" | shyaml get-values-0)
  2515. ;;
  2516. struct)
  2517. printf "%s" "$provides" | shyaml key-values-0
  2518. ;;
  2519. str)
  2520. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  2521. ;;
  2522. *)
  2523. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  2524. return 1
  2525. esac | tee "$cache_file"
  2526. return "${PIPESTATUS[0]}"
  2527. }
  2528. _get_metadata_provides() {
  2529. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2530. service rn rd
  2531. if [ -e "$cache_file" ]; then
  2532. #debug "$FUNCNAME: CACHEDIR cache hit"
  2533. cat "$cache_file"
  2534. return 0
  2535. fi
  2536. provides=$(printf "%s" "$metadata" | shyaml -q get-value -y provides "")
  2537. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  2538. _get_provides_provides "$provides" | tee "$cache_file"
  2539. return "${PIPESTATUS[0]}"
  2540. }
  2541. _get_services_provides() {
  2542. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2543. service rn rd
  2544. if [ -e "$cache_file" ]; then
  2545. #debug "$FUNCNAME: SESSION cache hit $1"
  2546. cat "$cache_file"
  2547. return 0
  2548. fi
  2549. ## YYY: replace the inner loop by a cached function
  2550. for service in "$@"; do
  2551. metadata="$(_get_service_metadata "$service")" || return 1
  2552. while read-0 rn rd; do
  2553. printf "%s\0" "$service" "$rn" "$rd"
  2554. done < <(_get_metadata_provides "$metadata")
  2555. done > "$cache_file"
  2556. if [ "$?" != 0 ]; then
  2557. rm -f "$cache_file" ## no cache
  2558. return 1
  2559. fi
  2560. cat "$cache_file"
  2561. }
  2562. export -f _get_services_provides
  2563. _get_charm_provides() {
  2564. if [ -z "$CHARM_STORE_HASH" ]; then
  2565. err-d "Expected \$CHARM_STORE_HASH to be set."
  2566. return 1
  2567. fi
  2568. local cache_file="$CACHEDIR/$FUNCNAME.cache.$CHARM_STORE_HASH" errlvl
  2569. if [ -e "$cache_file" ]; then
  2570. #debug "$FUNCNAME: SESSION cache hit"
  2571. cat "$cache_file"
  2572. return 0
  2573. fi
  2574. start="$SECONDS"
  2575. debug "Getting charm provider list..."
  2576. while read-0 charm _ realpath metadata; do
  2577. metadata="$(charm.metadata "$charm")" || continue
  2578. # echo "reading $charm" >&2
  2579. while read-0 rn rd; do
  2580. printf "%s\0" "$charm" "$rn" "$rd"
  2581. done < <(_get_metadata_provides "$metadata")
  2582. done < <(charm.ls) | tee "$cache_file"
  2583. errlvl="${PIPESTATUS[0]}"
  2584. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  2585. return "$errlvl"
  2586. }
  2587. _get_charm_providing() {
  2588. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2589. relation="$1"
  2590. if [ -e "$cache_file" ]; then
  2591. #debug "$FUNCNAME: SESSION cache hit $1"
  2592. cat "$cache_file"
  2593. return 0
  2594. fi
  2595. while read-0 charm relation_name relation_def; do
  2596. [ "$relation_name" == "$relation" ] || continue
  2597. printf "%s\0" "$charm" "$relation_def"
  2598. done < <(_get_charm_provides) > "$cache_file"
  2599. if [ "$?" != 0 ]; then
  2600. rm -f "$cache_file" ## no cache
  2601. return 1
  2602. fi
  2603. cat "$cache_file"
  2604. }
  2605. _get_services_providing() {
  2606. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2607. relation="$1"
  2608. shift ## services is "$@"
  2609. if [ -e "$cache_file" ]; then
  2610. #debug "$FUNCNAME: SESSION cache hit $1"
  2611. cat "$cache_file"
  2612. return 0
  2613. fi
  2614. while read-0 service relation_name relation_def; do
  2615. [ "$relation_name" == "$relation" ] || continue
  2616. printf "%s\0" "$service" "$relation_def"
  2617. done < <(_get_services_provides "$@") > "$cache_file"
  2618. if [ "$?" != 0 ]; then
  2619. rm -f "$cache_file" ## no cache
  2620. return 1
  2621. fi
  2622. cat "$cache_file"
  2623. }
  2624. export -f _get_services_provides
  2625. _out_new_relation_from_defs() {
  2626. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  2627. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2628. ## YYYvlab: should be seen even in no debug mode no ?
  2629. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2630. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  2631. td=${td:-True}
  2632. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  2633. after=$(_out_after_value_from_def "$service" "$rn" "$rel_def") || return 1
  2634. printf "%s\0" "$after" "$service" "$relation_name" "$ts" "$rc" "$td"
  2635. }
  2636. _out_after_value_from_def() {
  2637. local service="$1" relation_name="$2" relation_def="$3" after_t after
  2638. if after_t=$(echo "$relation_def" | shyaml get-type after 2>/dev/null); then
  2639. case "$after_t" in
  2640. sequence)
  2641. after="$(echo "$relation_def" | shyaml get-values after 2>/dev/null)" || return 1
  2642. after=",$service:${after//$'\n'/,$service:},"
  2643. ;;
  2644. struct)
  2645. err "Invalid type for ${WHITE}after${NORMAL}'s value in ${DARKBLUE}$relation_name${NORMAL}'s definition."
  2646. return 1
  2647. ;;
  2648. str)
  2649. after=",$service:$(echo "$relation_def" | shyaml get-value after "" 2>/dev/null)," || return 1
  2650. ;;
  2651. esac
  2652. else
  2653. after=""
  2654. fi
  2655. e "$after"
  2656. }
  2657. get_all_compose_yml_service() {
  2658. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2659. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2660. err "Failed to get compose yml hash"
  2661. return 1
  2662. }
  2663. fi
  2664. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2665. if [ -e "${cache_file}" ]; then
  2666. #debug "$FUNCNAME: cache hit: ${cache_file}"
  2667. cat "${cache_file}"
  2668. return 0
  2669. fi
  2670. compose_yml_content=$(get_compose_yml_content) || return 1
  2671. printf "%s" "${compose_yml_content}" | shyaml keys-0 2>/dev/null > "${cache_file}.wip" || {
  2672. err "Failed to get keys of compose content."
  2673. return 1
  2674. }
  2675. mv "${cache_file}"{.wip,} || return 1
  2676. cat "${cache_file}"
  2677. }
  2678. ## Outputs all relations array.
  2679. _service:all:relations_cached() {
  2680. local services service E
  2681. services=($(compose:yml:root:services)) || return 1
  2682. get_all_relations "${services[@]}" || return 1
  2683. }
  2684. ## Outputs all relations array.
  2685. service:all:relations() {
  2686. if [ -z "$COMBINED_HASH" ]; then
  2687. err-d "Expected \$COMBINED_HASH to be set."
  2688. return 1
  2689. fi
  2690. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMBINED_HASH"
  2691. if [ -e "${cache_file}" ]; then
  2692. # debug "$FUNCNAME: SESSION cache hit $1"
  2693. cat "${cache_file}"
  2694. return 0
  2695. fi
  2696. _service:all:relations_cached > "${cache_file}.wip" || {
  2697. err-d "Failed to compute all relations."
  2698. return 1
  2699. }
  2700. mv "${cache_file}"{.wip,} || return 1
  2701. cat "${cache_file}"
  2702. }
  2703. _service:all:relations_hash_cached() {
  2704. if [ -z "$COMBINED_HASH" ]; then
  2705. err-d "Expected \$COMBINED_HASH to be set."
  2706. return 1
  2707. fi
  2708. local cache_file="$CACHEDIR/$FUNCNAME.cache.x${COMBINED_HASH}" \
  2709. hash
  2710. if [ -e "${cache_file}" ]; then
  2711. # debug "$FUNCNAME: SESSION cache hit $cache_file"
  2712. cat "${cache_file}"
  2713. return 0
  2714. fi
  2715. service:all:relations > "${cache_file}.pre" || {
  2716. err-d "Failed to get all relations."
  2717. return 1
  2718. }
  2719. {
  2720. p0 "$(hash_get < "${cache_file}.pre")" || return 1
  2721. cat "${cache_file}.pre"
  2722. rm "${cache_file}.pre"
  2723. } > "${cache_file}".wip || return 1
  2724. mv "${cache_file}"{.wip,} || return 1
  2725. cat "${cache_file}"
  2726. }
  2727. ## Get all relations from all services in the current compose file.
  2728. ## Sets GLOBAL_ALL_RELATIONS_HASH and returns all relations array.
  2729. service:all:set_relations_hash() {
  2730. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2731. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2732. err "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2733. echo " (despite \$GLOBAL_ALL_RELATIONS being set)" >&2
  2734. return 1
  2735. fi
  2736. return 0
  2737. fi
  2738. ## sets COMPOSE_YML_CONTENT_HASH
  2739. _service:all:relations_hash_cached >/dev/null || return 1
  2740. {
  2741. read-0 GLOBAL_ALL_RELATIONS_HASH || return 1
  2742. export GLOBAL_ALL_RELATIONS_HASH
  2743. ## transfer to statedir
  2744. export GLOBAL_ALL_RELATIONS="$CACHEDIR/$FUNCNAME.cache.$COMBINED_HASH"
  2745. cat > "$GLOBAL_ALL_RELATIONS"
  2746. } < <(_service:all:relations_hash_cached)
  2747. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2748. err "Failed to set \$GLOBAL_ALL_RELATIONS."
  2749. return 1
  2750. fi
  2751. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2752. err "Failed to set \$GLOBAL_ALL_RELATIONS_HASH."
  2753. return 1
  2754. fi
  2755. }
  2756. get_subset_relations () {
  2757. local service all_services services start
  2758. if [ -n "$SUBSET_ALL_RELATIONS" ]; then
  2759. return 0
  2760. fi
  2761. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2762. err-d "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2763. return 1
  2764. fi
  2765. cache_hash=$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH" "$(declare -f "$FUNCNAME")")
  2766. local cache_file="$CACHEDIR/$FUNCNAME.cache.$cache_hash"
  2767. if [ -e "${cache_file}" ]; then
  2768. export SUBSET_ALL_RELATIONS="$cache_file"
  2769. hash=$(hash_get < "$cache_file") || return 1
  2770. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2771. cat "${cache_file}"
  2772. return 0
  2773. fi
  2774. ## collect all connected services first
  2775. all_services=("$@")
  2776. declare -A services
  2777. while [ "${#all_services[@]}" != 0 ]; do
  2778. array_pop all_services service
  2779. # debug " Getting relations for $DARKYELLOW$service$NORMAL"
  2780. while read-0 s rn ts rc td; do
  2781. [[ "$s" == "$service" ]] || continue
  2782. # debug " adding relation $DARKBLUE$rn$NORMAL to $DARKYELLOW$ts$NORMAL"
  2783. p0 "$service" "$rn" "$ts" "$rc" "$td"
  2784. if [ -z "${services[$ts]}" ] && [[ " ${all_services[@]} " != *" $ts "* ]]; then
  2785. all_services+=("$ts")
  2786. fi
  2787. done < "$GLOBAL_ALL_RELATIONS"
  2788. services["$service"]=1
  2789. done > "$cache_file.wip"
  2790. mv "$cache_file"{.wip,} || return 1
  2791. export SUBSET_ALL_RELATIONS="$cache_file"
  2792. hash=$(hash_get < "$cache_file") || return 1
  2793. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2794. cat "$cache_file"
  2795. }
  2796. export -f get_subset_relations
  2797. get_all_relations () {
  2798. if [ -z "$COMBINED_HASH" ]; then
  2799. err-d "Expected \$COMBINED_HASH to be set."
  2800. return 1
  2801. fi
  2802. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2803. cat "$GLOBAL_ALL_RELATIONS" || return 1
  2804. return 0
  2805. fi
  2806. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" "$COMBINED_HASH" "$(declare -p without_relations)")" \
  2807. services all_services service services_uses services_provides \
  2808. changed summon required recommended optional
  2809. if [ -e "${cache_file}" ]; then
  2810. #debug "$FUNCNAME: SESSION cache hit $1"
  2811. export GLOBAL_ALL_RELATIONS="$cache_file"
  2812. cat "${cache_file}"
  2813. return 0
  2814. fi
  2815. declare -A services
  2816. services_uses=()
  2817. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2818. _get_services_uses "$@" >/dev/null || return 1
  2819. array_read-0 services_uses < <(_get_services_uses "$@")
  2820. services_provides=()
  2821. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2822. _get_services_provides "$@" >/dev/null || return 1
  2823. array_read-0 services_provides < <(_get_services_provides "$@")
  2824. for service in "$@"; do
  2825. services[$service]=1
  2826. done
  2827. all_services=("$@")
  2828. while [ "${#all_services[@]}" != 0 ]; do
  2829. array_pop all_services service
  2830. while read-0-err E relation_name ts relation_config tech_dep; do
  2831. [ "${without_relations[$service:$relation_name]}" ] && {
  2832. debug "Ignoring compose $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> ${DARKYELLOW}$ts$NORMAL"
  2833. continue
  2834. }
  2835. ## First is priority, that can be adjusted in second step
  2836. printf "%s\0" "" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  2837. ## adding target services ?
  2838. [ "${services[$ts]}" ] && continue
  2839. array_read-0 services_uses < <(_get_services_uses "$ts")
  2840. all_services+=("$ts")
  2841. services[$ts]=1
  2842. done < <(p-err get_compose_relations "$service")
  2843. if [ "$E" != 0 ]; then
  2844. err "Failed to get relations for $DARKYELLOW$service$NORMAL."
  2845. return 1
  2846. fi
  2847. done > "${cache_file}.wip"
  2848. while true; do
  2849. changed=
  2850. new_services_uses=()
  2851. summon=()
  2852. required=()
  2853. recommended=()
  2854. optional=()
  2855. while [ "${#services_uses[@]}" != 0 ]; do
  2856. service="${services_uses[0]}"
  2857. relation_name="${services_uses[1]}"
  2858. relation_def="${services_uses[2]}"
  2859. services_uses=("${services_uses[@]:3}")
  2860. [ "${without_relations[$service:$relation_name]}" ] && {
  2861. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2862. continue
  2863. }
  2864. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2865. after=$(_out_after_value_from_def "$service" "$relation_name" "$relation_def") || return 1
  2866. ## is this "use" declaration satisfied ?
  2867. found=
  2868. while read-0 p s rn ts rc td; do
  2869. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  2870. if [ "$default_options" ]; then
  2871. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2872. fi
  2873. found="$ts"
  2874. p="$after"
  2875. fi
  2876. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td"
  2877. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2878. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2879. if [ "$found" ]; then ## this "use" declaration was satisfied
  2880. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation" \
  2881. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2882. continue
  2883. fi
  2884. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2885. auto=${auto:-pair}
  2886. case "$auto" in
  2887. "pair"|"summon")
  2888. service_list=()
  2889. array_read-0 service_list < <(array_keys_to_stdin services)
  2890. providers=()
  2891. providers_def=()
  2892. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2893. if [ "${#providers[@]}" == 1 ]; then
  2894. ts="${providers[0]}"
  2895. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2896. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2897. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2898. "${providers_def[0]}" "$relation_def" \
  2899. >> "${cache_file}.wip" || return 1
  2900. ## Adding service
  2901. [ "${services[$ts]}" ] && continue
  2902. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2903. services[$ts]=1
  2904. changed=1
  2905. continue
  2906. fi
  2907. if [ "${#providers[@]}" -gt 1 ]; then
  2908. msg=""
  2909. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2910. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2911. "(> 1 provider)."
  2912. elif [ "$auto" == "summon" ]; then ## no provider
  2913. summon+=("$service" "$relation_name" "$relation_def")
  2914. fi
  2915. ;;
  2916. null|disable|disabled)
  2917. :
  2918. ;;
  2919. *)
  2920. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2921. return 1
  2922. ;;
  2923. esac
  2924. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2925. constraint=${constraint:-optional}
  2926. case "$constraint" in
  2927. "required")
  2928. required+=("$service" "$relation_name" "$relation_def")
  2929. ;;
  2930. "recommended")
  2931. recommended+=("$service" "$relation_name" "$relation_def")
  2932. ;;
  2933. "optional")
  2934. optional+=("$service" "$relation_name" "$relation_def")
  2935. ;;
  2936. *)
  2937. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2938. return 1
  2939. ;;
  2940. esac
  2941. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2942. done
  2943. services_uses=("${new_services_uses[@]}")
  2944. if [ "$changed" ]; then
  2945. continue
  2946. fi
  2947. ## situation is stable
  2948. if [ "${#summon[@]}" != 0 ]; then
  2949. declare -A summon_requeued=()
  2950. while [ "${#summon[@]}" != 0 ]; do
  2951. service="${summon[0]}"
  2952. relation_name="${summon[1]}"
  2953. relation_def="${summon[2]}"
  2954. summon=("${summon[@]:3}")
  2955. providers=()
  2956. providers_def=()
  2957. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2958. ## select first provider that is not a stub
  2959. new_providers=()
  2960. new_providers_def=()
  2961. while [[ "${#providers[@]}" != 0 ]]; do
  2962. provider="${providers[0]}"
  2963. provider_def="${providers_def[0]}"
  2964. providers=("${providers[@]:1}")
  2965. providers_def=("${providers_def[@]:1}")
  2966. type="$(get_service_type "$provider")" || true
  2967. [ "$type" == "stub" ] && continue
  2968. new_providers+=("$provider")
  2969. new_providers_def+=("$provider_def")
  2970. done
  2971. providers=("${new_providers[@]}")
  2972. providers_def=("${new_providers_def[@]}")
  2973. if [ "${#providers[@]}" == 0 ]; then
  2974. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2975. return 1
  2976. fi
  2977. if [ "${#providers[@]}" -gt 1 ]; then
  2978. ## if there are multiple providers (for instance
  2979. ## sql-database), there are some case where other
  2980. ## services will also summon a more specific
  2981. ## postgres-database, that will solve our
  2982. ## constraint. So we'd rather pass (and requeue)
  2983. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2984. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2985. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2986. "(> 1 provider). Requeuing."
  2987. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2988. summon_requeued["$service/$relation_name"]=1
  2989. continue
  2990. else
  2991. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2992. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2993. "(> 1 provider). Choosing first."
  2994. fi
  2995. fi
  2996. ts="${providers[0]}"
  2997. ## YYYvlab: should be seen even in no debug mode no ?
  2998. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2999. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  3000. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  3001. "${providers_def[0]}" "$relation_def" \
  3002. >> "${cache_file}.wip" || return 1
  3003. ## Adding service
  3004. [ "${services[$ts]}" ] && continue
  3005. array_read-0 services_uses < <(_get_services_uses "$ts")
  3006. services[$ts]=1
  3007. changed=1
  3008. continue 2
  3009. done
  3010. continue
  3011. fi
  3012. [ "$NO_CONSTRAINT_CHECK" ] && break
  3013. if [ "${#required[@]}" != 0 ]; then
  3014. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  3015. err "Required relations not satisfied"
  3016. return 1
  3017. fi
  3018. if [ "${#recommended[@]}" != 0 ]; then
  3019. ## make recommendation
  3020. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  3021. fi
  3022. if [ -z "$QUIET" ]; then
  3023. if [ "${#optional[@]}" != 0 ]; then
  3024. ## inform about options
  3025. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  3026. fi
  3027. fi
  3028. # if [ "${#required[@]}" != 0 ]; then
  3029. # err "Required relations not satisfied"
  3030. # return 1
  3031. # fi
  3032. if [ "${#recommended[@]}" != 0 ]; then
  3033. warn "Recommended relations not satisfied"
  3034. fi
  3035. break
  3036. done
  3037. if [ "$?" != 0 ]; then
  3038. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  3039. return 1
  3040. fi
  3041. ##
  3042. ## Sort relations thanks to uses =metadata.yml= relations.
  3043. ##
  3044. mv "${cache_file}.wip"{,.in} &&
  3045. rm -f "${cache_file}.wip.final" &&
  3046. touch "${cache_file}.wip.final" || {
  3047. err "Unexpected error when mangling cache files."
  3048. return 1
  3049. }
  3050. declare -A relation_done=()
  3051. while true; do
  3052. had_remaining_relation=
  3053. had_new_relation=
  3054. while read-0 p s rn ts rc td; do
  3055. if [ -z "$p" ] || [ "$p" == "," ]; then
  3056. relation_done["$s:$rn"]=1
  3057. # printf " .. %-30s %-30s %-30s\n" "$s" "$ts" "$rn" >&2
  3058. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  3059. had_new_relation=1
  3060. else
  3061. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  3062. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  3063. had_remaining_relation=1
  3064. fi
  3065. done < "${cache_file}.wip.in"
  3066. [ -z "$had_remaining_relation" ] && break
  3067. mv "${cache_file}.wip."{out,in}
  3068. while read-0 p s rn ts rc td; do
  3069. for rel in "${!relation_done[@]}"; do
  3070. p="${p//,$rel,/,}"
  3071. done
  3072. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  3073. if [ -z "$had_new_relation" ]; then
  3074. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  3075. for rel in ${p//,/ }; do
  3076. rel_s=${rel%%:*}
  3077. rel_r=${rel##*:}
  3078. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  3079. done
  3080. else
  3081. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  3082. fi
  3083. done < "${cache_file}.wip.in"
  3084. if [ -z "$had_new_relation" ]; then
  3085. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  3086. return 1
  3087. fi
  3088. mv "${cache_file}.wip."{out,in}
  3089. done
  3090. mv "${cache_file}"{.wip.final,} || return 1
  3091. export GLOBAL_ALL_RELATIONS="$cache_file"
  3092. GLOBAL_ALL_RELATIONS_HASH=$(hash_get < "$cache_file") || return 1
  3093. export GLOBAL_ALL_RELATIONS_HASH
  3094. cat "$cache_file"
  3095. }
  3096. export -f get_all_relations
  3097. _display_solves() {
  3098. local array_name="$1" by_relation msg
  3099. ## inform about options
  3100. msg=""
  3101. declare -A by_relation
  3102. while read-0 service relation_name relation_def; do
  3103. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  3104. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  3105. if [ -z "$solves" ]; then
  3106. continue
  3107. fi
  3108. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  3109. if [ "$auto" == "pair" ]; then
  3110. requirement="add provider in cluster to auto-pair"
  3111. else
  3112. requirement="add explicit relation"
  3113. fi
  3114. while read-0 name def; do
  3115. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  3116. done < <(printf "%s" "$solves" | shyaml key-values-0)
  3117. done < <(array_values_to_stdin "$array_name")
  3118. while read-0 relation_name message; do
  3119. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  3120. "$relation_name" "$message" )"
  3121. done < <(array_kv_to_stdin by_relation)
  3122. if [ "$msg" ]; then
  3123. printf "%s\n" "${msg:1}"
  3124. fi
  3125. }
  3126. get_compose_relation_def() {
  3127. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  3128. while read-0 relation_name target_service relation_config tech_dep; do
  3129. [ "$relation_name" == "$relation" ] || continue
  3130. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  3131. done < <(get_compose_relations "$service") || return 1
  3132. }
  3133. export -f get_compose_relation_def
  3134. run_service_relations () {
  3135. local service services loaded subservices subservice
  3136. PROJECT_NAME=$(get_default_project_name) || return 1
  3137. export PROJECT_NAME
  3138. declare -A loaded
  3139. subservices=$(get_ordered_service_dependencies "$@") || return 1
  3140. for service in $subservices; do
  3141. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  3142. for subservice in $(get_service_deps "$service") "$service"; do
  3143. [ "${loaded[$subservice]}" ] && continue
  3144. export BASE_SERVICE_NAME=$service
  3145. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  3146. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  3147. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  3148. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  3149. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  3150. while read-0 relation_name target_service relation_config tech_dep; do
  3151. [ "${without_relations[$service:$relation_name]}" ] && {
  3152. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  3153. continue
  3154. }
  3155. export relation_config
  3156. export TARGET_SERVICE_NAME=$target_service
  3157. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  3158. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  3159. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  3160. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  3161. Wrap "${wrap_opts[@]}" -d "building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  3162. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  3163. EOF
  3164. done < <(get_service_relations "$subservice") || return 1
  3165. loaded[$subservice]=1
  3166. done
  3167. done
  3168. }
  3169. export -f run_service_relations
  3170. _run_service_action_direct() {
  3171. local service="$1" action="$2" charm _dummy project_name
  3172. shift; shift
  3173. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  3174. if read-0 _dummy || [ "$_dummy" ]; then
  3175. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3176. return 1
  3177. fi
  3178. project_name=$(get_default_project_name) || return 1
  3179. export PROJECT_NAME="$project_name"
  3180. export state_tmpdir
  3181. (
  3182. set +e ## Prevents unwanted leaks from parent shell
  3183. export COMPOSE_CONFIG=$(get_compose_yml_content)
  3184. export METADATA_CONFIG=$(charm.metadata "$charm")
  3185. export SERVICE_NAME=$service
  3186. export ACTION_NAME=$action
  3187. export ACTION_SCRIPT_PATH="$action_script_path"
  3188. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3189. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3190. export SERVICE_DATASTORE="$DATASTORE/$service"
  3191. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3192. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3193. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  3194. ) 0<&6 ## inject general stdin
  3195. }
  3196. export -f _run_service_action_direct
  3197. _run_service_action_relation() {
  3198. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  3199. shift; shift
  3200. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  3201. if read-0 _dummy || [ "$_dummy" ]; then
  3202. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3203. return 1
  3204. fi
  3205. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  3206. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  3207. export state_tmpdir
  3208. (
  3209. set +e ## Prevents unwanted leaks from parent shell
  3210. export METADATA_CONFIG=$(charm.metadata "$charm")
  3211. export SERVICE_NAME=$service
  3212. export RELATION_TARGET_SERVICE="$target_service"
  3213. export RELATION_TARGET_CHARM="$target_charm"
  3214. export RELATION_BASE_SERVICE="$service"
  3215. export RELATION_BASE_CHARM="$charm"
  3216. export RELATION_DATA_FILE="$RELATION_DATA_FILE"
  3217. export ACTION_NAME=$action
  3218. export ACTION_SCRIPT_PATH="$action_script_path"
  3219. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3220. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3221. export SERVICE_DATASTORE="$DATASTORE/$service"
  3222. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3223. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3224. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  3225. ) 0<&6 ## inject general stdin
  3226. }
  3227. export -f _run_service_action_relation
  3228. get_relation_data_dir() {
  3229. local service="$1" target_service="$2" relation_name="$3" \
  3230. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  3231. if [ -e "$cache_file" ]; then
  3232. # debug "$FUNCNAME: cache hit ($*)"
  3233. cat "$cache_file"
  3234. return 0
  3235. fi
  3236. local project relation_dir
  3237. project=${PROJECT_NAME}
  3238. if [ -z "$project" ]; then
  3239. project=$(get_default_project_name) || return 1
  3240. fi
  3241. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  3242. if ! [ -d "$relation_dir" ]; then
  3243. mkdir -p "$relation_dir" || return 1
  3244. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  3245. fi
  3246. echo "$relation_dir" | tee "$cache_file"
  3247. }
  3248. export -f get_relation_data_dir
  3249. get_relation_data_file() {
  3250. local service="$1" target_service="$2" relation_name="$3" relation_config="$4" \
  3251. new new_md5 relation_dir relation_data_file
  3252. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  3253. relation_data_file="$relation_dir/data"
  3254. new=
  3255. if [ -e "$relation_data_file" ]; then
  3256. ## Has reference changed ?
  3257. new_md5=$(e "$relation_config" | md5_compat)
  3258. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  3259. new=true
  3260. fi
  3261. else
  3262. new=true
  3263. fi
  3264. if [ -n "$new" ]; then
  3265. OLDUMASK=$(umask)
  3266. umask 0077
  3267. e "$relation_config" > "$relation_data_file"
  3268. umask "$OLDUMASK"
  3269. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  3270. fi
  3271. echo "$relation_data_file"
  3272. }
  3273. export -f get_relation_data_file
  3274. has_service_action () {
  3275. if [ -z "$CHARM_STORE_HASH" ]; then
  3276. err-d "Can't access global \$CHARM_STORE_HASH"
  3277. return 1
  3278. fi
  3279. local service="$1" action="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$2.$CHARM_STORE_HASH" \
  3280. charm target_charm relation_name target_service relation_config _tech_dep \
  3281. path
  3282. if [ -e "$cache_file" ]; then
  3283. # debug "$FUNCNAME: cache hit ($*)"
  3284. if [ -s "$cache_file" ]; then
  3285. cat "$cache_file"
  3286. return 0
  3287. else
  3288. return 1
  3289. fi
  3290. fi
  3291. charm=$(get_service_charm "$service") || return 1
  3292. ## Action directly provided ?
  3293. if path=$(charm.has_direct_action "$charm" "$action"); then
  3294. p0 "direct" "$charm" "$path" | tee "$cache_file"
  3295. return 0
  3296. fi
  3297. ## Action provided by relation ?
  3298. while read-0 relation_name target_service relation_config _tech_dep; do
  3299. target_charm=$(get_service_charm "$target_service") || return 1
  3300. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  3301. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  3302. return 0
  3303. fi
  3304. done < <(get_service_relations "$service")
  3305. touch "$cache_file"
  3306. return 1
  3307. # master=$(get_top_master_service_for_service "$service")
  3308. # [ "$master" == "$charm" ] && return 1
  3309. # has_service_action "$master" "$action"
  3310. }
  3311. export -f has_service_action
  3312. run_service_action () {
  3313. local service="$1" action="$2" errlvl
  3314. shift ; shift
  3315. exec 6<&0 ## saving stdin
  3316. {
  3317. if ! read-0 action_type; then
  3318. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  3319. info " Add an executable script to 'actions/$action' to implement action."
  3320. return 1
  3321. fi
  3322. "_run_service_action_${action_type}" "$service" "$action" "$@"
  3323. errlvl="$?"
  3324. } < <(has_service_action "$service" "$action")
  3325. exec 0<&6 6<&- ## restoring stdin
  3326. return "$errlvl"
  3327. }
  3328. export -f run_service_action
  3329. get_compose_relation_config() {
  3330. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3331. if [ -e "$cache_file" ]; then
  3332. # debug "$FUNCNAME: cache hit ($*)"
  3333. cat "$cache_file"
  3334. return 0
  3335. fi
  3336. compose_service_def=$(get_compose_service_def "$service") || return 1
  3337. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  3338. }
  3339. export -f get_compose_relation_config
  3340. # ## Return key-values-0
  3341. # get_compose_relation_config_for_service() {
  3342. # local service=$1 relation_name=$2 relation_config
  3343. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  3344. # if ! relation_config=$(
  3345. # echo "$compose_service_relations" |
  3346. # shyaml get-value "${relation_name}" 2>/dev/null); then
  3347. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  3348. # "relation config in compose configuration."
  3349. # return 1
  3350. # fi
  3351. # if [ -z "$relation_config" ]; then
  3352. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  3353. # return 1
  3354. # fi
  3355. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  3356. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  3357. # return 1
  3358. # fi
  3359. # }
  3360. # export -f get_compose_relation_config_for_service
  3361. _get_container_relation() {
  3362. local metadata=$1 found relation_name relation_def
  3363. found=
  3364. while read-0 relation_name relation_def; do
  3365. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  3366. found="$relation_name"
  3367. break
  3368. }
  3369. done < <(_get_charm_metadata_uses "$metadata")
  3370. if [ -z "$found" ]; then
  3371. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  3372. "${WHITE}scope${NORMAL} set to 'container'."
  3373. return 1
  3374. fi
  3375. printf "%s" "$found"
  3376. }
  3377. _get_master_service_for_service_cached () {
  3378. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3379. charm requires master_charm target_charm target_service service_def found
  3380. if [ -e "$cache_file" ]; then
  3381. # debug "$FUNCNAME: STATIC cache hit ($1)"
  3382. cat "$cache_file" &&
  3383. touch "$cache_file" || return 1
  3384. return 0
  3385. fi
  3386. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3387. ## just return service name
  3388. echo "$service" | tee "$cache_file"
  3389. return 0
  3390. fi
  3391. ## Action provided by relation ?
  3392. container_relation=$(_get_container_relation "$metadata") || return 1
  3393. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  3394. if [ -z "$target_service" ]; then
  3395. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  3396. "${DARKYELLOW}$service$NORMAL compose definition."
  3397. err ${FUNCNAME[@]}
  3398. return 1
  3399. fi
  3400. echo "$target_service" | tee "$cache_file"
  3401. }
  3402. export -f _get_master_service_for_service_cached
  3403. get_master_service_for_service() {
  3404. if [ -z "$CHARM_STORE_HASH" ]; then
  3405. err-d "Expected \$CHARM_STORE_HASH to be set."
  3406. return 1
  3407. fi
  3408. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3409. charm metadata result
  3410. if [ -e "$cache_file" ]; then
  3411. # debug "$FUNCNAME: SESSION cache hit ($*)"
  3412. cat "$cache_file" || return 1
  3413. return 0
  3414. fi
  3415. charm=$(get_service_charm "$service") || return 1
  3416. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  3417. metadata=""
  3418. warn "No charm $DARKPINK$charm$NORMAL found."
  3419. }
  3420. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  3421. echo "$result" | tee "$cache_file" || return 1
  3422. }
  3423. export -f get_master_service_for_service
  3424. get_top_master_service_for_service() {
  3425. if [ -z "$CHARM_STORE_HASH" ]; then
  3426. err-d "Expected \$CHARM_STORE_HASH to be set."
  3427. return 1
  3428. fi
  3429. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3430. current_service
  3431. if [ -e "$cache_file" ]; then
  3432. # debug "$FUNCNAME: cache hit ($*)"
  3433. touch "$cache_file" || return 1
  3434. cat "$cache_file"
  3435. return 0
  3436. fi
  3437. current_service="$service"
  3438. while true; do
  3439. master_service=$(get_master_service_for_service "$current_service") || return 1
  3440. [ "$master_service" == "$current_service" ] && break
  3441. current_service="$master_service"
  3442. done
  3443. echo "$current_service" | tee "$cache_file"
  3444. return 0
  3445. }
  3446. export -f get_top_master_service_for_service
  3447. ##
  3448. ## The result is a mixin that is not always a complete valid
  3449. ## docker-compose entry (thinking of subordinates). The result
  3450. ## will be merge with master charms.
  3451. _get_docker_compose_mixin_from_metadata_cached() {
  3452. local service="$1" charm="$2" metadata="$3" \
  3453. has_build_dir="$4" \
  3454. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3455. metadata_file metadata volumes docker_compose subordinate image \
  3456. mixin mixins tmemory memory limit docker_memory
  3457. if [ -e "$cache_file" ]; then
  3458. #debug "$FUNCNAME: STATIC cache hit $1"
  3459. cat "$cache_file" &&
  3460. touch "$cache_file" || return 1
  3461. return 0
  3462. fi
  3463. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  3464. if [ "$metadata" ]; then
  3465. ## resources to volumes
  3466. volumes=$(
  3467. for resource_type in data config; do
  3468. while read-0 resource; do
  3469. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  3470. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  3471. done
  3472. while read-0 resource; do
  3473. if [[ "$resource" == /*:/*:* ]]; then
  3474. echo " - $resource"
  3475. elif [[ "$resource" == /*:/* ]]; then
  3476. echo " - $resource:rw"
  3477. elif [[ "$resource" == /*:* ]]; then
  3478. echo " - ${resource%%:*}:$resource"
  3479. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  3480. echo " - $resource:$resource:rw"
  3481. else
  3482. die "Invalid host-resource specified in 'metadata.yml'."
  3483. fi
  3484. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  3485. while read-0 resource; do
  3486. charm_path="$(charm.get_dir "$charm")"
  3487. dest="$charm_path/resources$resource"
  3488. host_dest="$HOST_CHARM_STORE${dest#$CHARM_STORE}"
  3489. if ! [ -e "$dest" ]; then
  3490. die "charm-resource: '$resource' does not exist (file: '$host_dest')."
  3491. fi
  3492. echo " - $host_dest:$resource:ro"
  3493. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  3494. ) || return 1
  3495. if [ "$volumes" ]; then
  3496. mixins+=("volumes:"$'\n'"$volumes")
  3497. fi
  3498. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3499. if [ "$type" != "run-once" ]; then
  3500. mixins+=("restart: unless-stopped")
  3501. fi
  3502. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  3503. if [ "$docker_compose" ]; then
  3504. mixins+=("$docker_compose")
  3505. fi
  3506. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3507. subordinate=true
  3508. fi
  3509. fi
  3510. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  3511. [ "$image" == "None" ] && image=""
  3512. if [ -n "$image" ]; then
  3513. if [ -n "$subordinate" ]; then
  3514. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  3515. return 1
  3516. fi
  3517. mixins+=("image: $image")
  3518. elif [ "$has_build_dir" ]; then
  3519. if [ "$subordinate" ]; then
  3520. err "Subordinate charm can not have a 'build' sub directory."
  3521. return 1
  3522. fi
  3523. mixins+=("build: $(charm.get_dir "$charm")/build")
  3524. fi
  3525. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  3526. [ "$limit" == "null" ] && limit=""
  3527. if [ -n "$limit" ]; then
  3528. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  3529. [ "$E" != 0 ]; then
  3530. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  3531. return 1
  3532. fi
  3533. case "$tmemory" in
  3534. '!!str'|'!!int')
  3535. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  3536. err "Invalid format specified for .limit.memory: '$memory'."
  3537. return 1
  3538. }
  3539. ;;
  3540. '!!float')
  3541. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  3542. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  3543. return 1
  3544. ;;
  3545. '!!null')
  3546. :
  3547. ;;
  3548. *)
  3549. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  3550. "for ${WHITE}.limit.memory${NORMAL}."
  3551. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  3552. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  3553. echo " Example values: '1.5G', '252M', ..." >&2
  3554. return 1
  3555. ;;
  3556. esac
  3557. if [ -n "$docker_memory" ]; then
  3558. if [[ "$docker_memory" -lt 6291456 ]]; then
  3559. err "Can't limit service to lower than 6M."
  3560. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  3561. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  3562. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  3563. return 1
  3564. fi
  3565. mixins+=(
  3566. "mem_limit: $docker_memory"
  3567. "memswap_limit: $docker_memory"
  3568. )
  3569. fi
  3570. fi
  3571. ## Final merging
  3572. mixin=$(merge_yaml_str "${mixins[@]}") || {
  3573. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  3574. return 1
  3575. }
  3576. echo "$mixin" | tee "$cache_file"
  3577. }
  3578. export -f _get_docker_compose_mixin_from_metadata_cached
  3579. get_docker_compose_mixin_from_metadata() {
  3580. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3581. if [ -e "$cache_file" ]; then
  3582. #debug "$FUNCNAME: SESSION cache hit ($*)"
  3583. cat "$cache_file"
  3584. return 0
  3585. fi
  3586. charm=$(get_service_charm "$service") || return 1
  3587. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  3588. has_build_dir=
  3589. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  3590. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  3591. echo "$mixin" | tee "$cache_file"
  3592. }
  3593. export -f get_docker_compose_mixin_from_metadata
  3594. _save() {
  3595. local name="$1"
  3596. cat - | tee -a "$docker_compose_dir/.data/$name"
  3597. }
  3598. export -f _save
  3599. get_default_project_name() {
  3600. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  3601. echo "$DEFAULT_PROJECT_NAME"
  3602. return 0
  3603. fi
  3604. local normalized_path compose_yml_location name
  3605. compose_yml_location="$(get_compose_yml_location)" || return 1
  3606. if [ -n "$compose_yml_location" ]; then
  3607. if normalized_path=$(readlink -f "$compose_yml_location"); then
  3608. name="${normalized_path%/*}" ## dirname
  3609. name="${name##*/}" ## basename
  3610. name="${name%%-deploy}" ## remove any '-deploy'
  3611. name="${name,,}" ## lowercase
  3612. e "$name"
  3613. return 0
  3614. fi
  3615. fi
  3616. echo "orphan"
  3617. return 0
  3618. }
  3619. export -f get_default_project_name
  3620. get_running_compose_containers() {
  3621. ## XXXvlab: docker bug: there will be a final newline anyway
  3622. docker ps --filter label="compose.service" --format='{{.ID}}'
  3623. }
  3624. export -f get_running_compose_containers
  3625. get_healthy_container_ip_for_service () {
  3626. local service="$1" port="$2" timeout=${3:-60}
  3627. local containers container container_network container_ip
  3628. containers="$(get_running_containers_for_service "$service")"
  3629. if [ -z "$containers" ]; then
  3630. err "No containers running for service $DARKYELLOW$service$NORMAL."
  3631. return 1
  3632. fi
  3633. ## XXXvlab: taking first container is probably not a good idea
  3634. container="$(echo "$containers" | head -n 1)"
  3635. ## XXXvlab: taking first ip is probably not a good idea
  3636. read-0 container_network container_ip < <(get_container_network_ip "$container")
  3637. if [ -z "$container_ip" ]; then
  3638. err "Can't get container's IP. You should check health of" \
  3639. "${DARKYELLOW}$service${NORMAL}'s container."
  3640. return 1
  3641. fi
  3642. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  3643. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  3644. echo " Please check that container is healthy. Here are last logs:" >&2
  3645. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  3646. return 1
  3647. }
  3648. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  3649. echo "$container_network:$container_ip"
  3650. }
  3651. export -f get_healthy_container_ip_for_service
  3652. switch_to_relation_service() {
  3653. local relation="$1"
  3654. ## XXXvlab: can't get real config here
  3655. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  3656. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  3657. return 1
  3658. fi
  3659. export SERVICE_NAME="$ts"
  3660. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3661. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$SERVICE_NAME")
  3662. export DOCKER_BASE_IMAGE
  3663. target_charm=$(get_service_charm "$ts") || return 1
  3664. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3665. cd "$target_charm_path"
  3666. }
  3667. export -f switch_to_relation_service
  3668. get_volumes_for_container() {
  3669. local container="$1"
  3670. docker inspect \
  3671. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3672. "$container"
  3673. }
  3674. export -f get_volumes_for_container
  3675. is_volume_used() {
  3676. local volume="$1" container_id src dst
  3677. while read -r container_id; do
  3678. while read-0 src dst; do
  3679. [[ "$src/" == "$volume"/* ]] && return 0
  3680. done < <(get_volumes_for_container "$container_id")
  3681. done < <(get_running_compose_containers)
  3682. return 1
  3683. }
  3684. export -f is_volume_used
  3685. clean_unused_docker_compose() {
  3686. for f in /var/lib/compose/docker-compose/*; do
  3687. [ -e "$f" ] || continue
  3688. is_volume_used "$f" && continue
  3689. debug "Cleaning unused docker-compose ${f##*/}"
  3690. rm -rf "$f" || return 1
  3691. done
  3692. return 0
  3693. }
  3694. export -f clean_unused_docker_compose
  3695. docker_compose_store() {
  3696. local file="$1" sha
  3697. sha=$(hash_get 64 < "$file") || return 1
  3698. project=$(get_default_project_name) || return 1
  3699. dst="/var/lib/compose/docker-compose/$sha/$project"
  3700. mkdir -p "$dst" || return 1
  3701. cat <<EOF > "$dst/.env" || return 1
  3702. DOCKER_COMPOSE_PATH=$dst
  3703. COMPOSE_HTTP_TIMEOUT=7200
  3704. EOF
  3705. cp "$file" "$dst/docker-compose.yml" || return 1
  3706. mkdir -p "$dst/bin" || return 1
  3707. cat <<EOF > "$dst/bin/dc" || return 1
  3708. #!/bin/bash
  3709. $(declare -f read-0)
  3710. docker_run_opts=()
  3711. while read-0 opt; do
  3712. if [[ "\$opt" == "!env:"* ]]; then
  3713. opt="\${opt##!env:}"
  3714. var="\${opt%%=*}"
  3715. value="\${opt#*=}"
  3716. export "\$var"="\$value"
  3717. else
  3718. docker_run_opts+=("\$opt")
  3719. fi
  3720. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3721. docker_run_opts+=(
  3722. "-w" "$dst"
  3723. "--entrypoint" "/usr/local/bin/docker-compose"
  3724. )
  3725. [ -t 1 ] && {
  3726. docker_run_opts+=("-ti")
  3727. }
  3728. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3729. EOF
  3730. chmod +x "$dst/bin/dc" || return 1
  3731. printf "%s" "$sha"
  3732. }
  3733. export -f docker_compose_store
  3734. launch_docker_compose() {
  3735. local charm docker_compose_tmpdir docker_compose_dir
  3736. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3737. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3738. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3739. ## docker-compose will name network from the parent dir name
  3740. project=$(get_default_project_name)
  3741. mkdir -p "$docker_compose_tmpdir/$project"
  3742. docker_compose_dir="$docker_compose_tmpdir/$project"
  3743. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  3744. err "${FUNCNAME[0]} is meant to be called after"\
  3745. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  3746. echo " Called by:" >&2
  3747. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  3748. return 1
  3749. fi
  3750. cat "$_CURRENT_DOCKER_COMPOSE" > "$docker_compose_dir/docker-compose.yml" || return 1
  3751. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3752. # debug "Merging some config data in docker-compose.yml:"
  3753. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3754. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3755. fi
  3756. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3757. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3758. fi
  3759. ## XXXvlab: could be more specific and only link the needed charms
  3760. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3761. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3762. # if charm.exists "$charm"; then
  3763. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3764. # fi
  3765. # done
  3766. mkdir "$docker_compose_dir/.data"
  3767. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3768. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3769. fi
  3770. {
  3771. {
  3772. {
  3773. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3774. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3775. else
  3776. cd "$docker_compose_dir" || return 1
  3777. fi
  3778. if [ -f ".env" ]; then
  3779. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3780. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3781. fi
  3782. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3783. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3784. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3785. if [ "$DRY_COMPOSE_RUN" ]; then
  3786. echo docker-compose "$@"
  3787. else
  3788. docker-compose "$@"
  3789. fi
  3790. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3791. } | _save stdout
  3792. } 3>&1 1>&2 2>&3 | _save stderr
  3793. } 3>&1 1>&2 2>&3
  3794. 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
  3795. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3796. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3797. fi
  3798. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3799. if [ -z "$docker_compose_errlvl" ]; then
  3800. err "Something went wrong before you could gather docker-compose errorlevel."
  3801. return 1
  3802. fi
  3803. return "$docker_compose_errlvl"
  3804. }
  3805. export -f launch_docker_compose
  3806. get_compose_yml_location() {
  3807. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3808. echo "$COMPOSE_YML_FILE"
  3809. return 0
  3810. fi
  3811. parent=$(while ! [ -f "./compose.yml" ]; do
  3812. [ "$PWD" == "/" ] && exit 0
  3813. cd ..
  3814. done; echo "$PWD"
  3815. )
  3816. if [ "$parent" ]; then
  3817. echo "$parent/compose.yml"
  3818. return 0
  3819. fi
  3820. ## XXXvlab: do we need this additional environment variable,
  3821. ## COMPOSE_YML_FILE is not sufficient ?
  3822. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3823. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3824. warn "No 'compose.yml' was found in current or parent dirs," \
  3825. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3826. "(${DEFAULT_COMPOSE_FILE})"
  3827. return 0
  3828. fi
  3829. echo "$DEFAULT_COMPOSE_FILE"
  3830. return 0
  3831. fi
  3832. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3833. return 0
  3834. }
  3835. export -f get_compose_yml_location
  3836. get_compose_yml_content() {
  3837. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3838. if [ -e "$cache_file" ]; then
  3839. cat "$cache_file" &&
  3840. touch "$cache_file" || return 1
  3841. return 0
  3842. fi
  3843. if [ -z "$COMPOSE_YML_FILE" ]; then
  3844. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3845. fi
  3846. if [ -e "$COMPOSE_YML_FILE" ]; then
  3847. # debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3848. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3849. err "Could not read '$COMPOSE_YML_FILE'."
  3850. return 1
  3851. }
  3852. else
  3853. debug "No compose file found. Using an empty one."
  3854. COMPOSE_YML_CONTENT=""
  3855. fi
  3856. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3857. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3858. if [ "$?" != 0 ]; then
  3859. outputed_something=
  3860. while IFS='' read -r line1 && IFS='' read -r line2; do
  3861. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3862. outputed_something=true
  3863. echo "$line1 $GRAY($line2)$NORMAL"
  3864. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3865. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3866. prefix " $GRAY|$NORMAL "
  3867. [ "$outputed_something" ] || {
  3868. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3869. echo "$output" | prefix " $GRAY|$NORMAL "
  3870. }
  3871. return 1
  3872. fi
  3873. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3874. }
  3875. export -f get_compose_yml_content
  3876. compose:yml:hash() {
  3877. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3878. if [ -e "$cache_file" ]; then
  3879. cat "$cache_file" &&
  3880. touch "$cache_file" || return 1
  3881. return 0
  3882. fi
  3883. compose_yml_content=$(get_compose_yml_content) || return 1
  3884. compose_yml_hash=$(echo "$compose_yml_content" | hash_get) || return 1
  3885. e "$compose_yml_hash" | tee "$cache_file" || return 1
  3886. }
  3887. export -f compose:yml:hash
  3888. compose:yml:root:services() {
  3889. local cache_file="$state_tmpdir/$FUNCNAME.cache" services compose_yml_content
  3890. if [ -e "$cache_file" ]; then
  3891. cat "$cache_file" &&
  3892. touch "$cache_file" || return 1
  3893. return 0
  3894. fi
  3895. compose_yml_content=$(get_compose_yml_content) || return 1
  3896. services=($(e "$compose_yml_content" | shyaml keys)) || return 1
  3897. e "${services[*]}" | tee "$cache_file" || return 1
  3898. }
  3899. export -f compose:yml:root:services
  3900. get_default_target_services() {
  3901. local services=("$@")
  3902. if [ -z "${services[*]}" ]; then
  3903. if [ "$DEFAULT_SERVICES" ]; then
  3904. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3905. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3906. services="$DEFAULT_SERVICES"
  3907. else
  3908. err "No service provided."
  3909. return 1
  3910. fi
  3911. fi
  3912. echo "${services[*]}"
  3913. }
  3914. export -f get_default_target_services
  3915. get_master_services() {
  3916. local loaded master_service service
  3917. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" )"
  3918. if [ -e "$cache_file" ]; then
  3919. cat "$cache_file" &&
  3920. touch "$cache_file" || return 1
  3921. return 0
  3922. fi
  3923. declare -A loaded
  3924. for service in "$@"; do
  3925. master_service=$(get_top_master_service_for_service "$service") || return 1
  3926. if [ "${loaded[$master_service]}" ]; then
  3927. continue
  3928. fi
  3929. echo "$master_service"
  3930. loaded["$master_service"]=1
  3931. done > "$cache_file".wip || return 1
  3932. mv "$cache_file"{.wip,} || return 1
  3933. cat "$cache_file" || return 1
  3934. }
  3935. export -f get_master_services
  3936. get_current_docker_container_id() {
  3937. local line
  3938. line=$(cat "/proc/self/cpuset") || return 1
  3939. [[ "$line" == *docker* ]] || return 1
  3940. echo "${line##*/}"
  3941. }
  3942. export -f get_current_docker_container_id
  3943. ## if we are in a docker compose, we might want to know what is the
  3944. ## real host path of some local paths.
  3945. get_host_path() {
  3946. local path="$1"
  3947. path=$(realpath "$path") || return 1
  3948. container_id=$(get_current_docker_container_id) || {
  3949. print "%s" "$path"
  3950. return 0
  3951. }
  3952. biggest_dst=
  3953. current_src=
  3954. while read-0 src dst; do
  3955. [[ "$path" == "$dst"* ]] || continue
  3956. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3957. biggest_dst="$dst"
  3958. current_src="$src"
  3959. fi
  3960. done < <(get_volumes_for_container "$container_id")
  3961. if [ "$current_src" ]; then
  3962. printf "%s" "$current_src"
  3963. else
  3964. return 1
  3965. fi
  3966. }
  3967. export -f get_host_path
  3968. _setup_state_dir() {
  3969. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3970. #debug "Creating temporary state directory in '$state_tmpdir'."
  3971. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3972. # rm -rf \"$state_tmpdir\""
  3973. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3974. }
  3975. get_docker_compose_help_msg() {
  3976. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3977. docker_compose_help_msg
  3978. if [ -e "$cache_file" ]; then
  3979. cat "$cache_file" &&
  3980. touch "$cache_file" || return 1
  3981. return 0
  3982. fi
  3983. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3984. echo "$docker_compose_help_msg" |
  3985. tee "$cache_file" || return 1
  3986. }
  3987. get_docker_compose_usage() {
  3988. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3989. docker_compose_help_msg
  3990. if [ -e "$cache_file" ]; then
  3991. cat "$cache_file" &&
  3992. touch "$cache_file" || return 1
  3993. return 0
  3994. fi
  3995. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3996. echo "$docker_compose_help_msg" |
  3997. grep -m 1 "^Usage:" -A 10000 |
  3998. egrep -m 1 "^\$" -B 10000 |
  3999. nspc |
  4000. sed -r 's/^Usage: //g' |
  4001. tee "$cache_file" || return 1
  4002. }
  4003. get_docker_compose_opts_help() {
  4004. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  4005. docker_compose_help_msg
  4006. if [ -e "$cache_file" ]; then
  4007. cat "$cache_file" &&
  4008. touch "$cache_file" || return 1
  4009. return 0
  4010. fi
  4011. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  4012. echo "$docker_compose_opts_help" |
  4013. grep '^Options:' -A 20000 |
  4014. tail -n +2 |
  4015. { cat ; echo; } |
  4016. egrep -m 1 "^\S*\$" -B 10000 |
  4017. head -n -1 |
  4018. tee "$cache_file" || return 1
  4019. }
  4020. get_docker_compose_commands_help() {
  4021. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  4022. docker_compose_help_msg
  4023. if [ -e "$cache_file" ]; then
  4024. cat "$cache_file" &&
  4025. touch "$cache_file" || return 1
  4026. return 0
  4027. fi
  4028. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  4029. echo "$docker_compose_opts_help" |
  4030. grep '^Commands:' -A 20000 |
  4031. tail -n +2 |
  4032. { cat ; echo; } |
  4033. egrep -m 1 "^\S*\$" -B 10000 |
  4034. head -n -1 |
  4035. tee "$cache_file" || return 1
  4036. }
  4037. get_docker_compose_opts_list() {
  4038. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  4039. docker_compose_help_msg
  4040. if [ -e "$cache_file" ]; then
  4041. cat "$cache_file" &&
  4042. touch "$cache_file" || return 1
  4043. return 0
  4044. fi
  4045. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  4046. echo "$docker_compose_opts_help" |
  4047. egrep "^\s+-" |
  4048. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  4049. tee "$cache_file" || return 1
  4050. }
  4051. options_parser() {
  4052. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  4053. printf "\0"
  4054. }
  4055. remove_options_in_option_help_msg() {
  4056. {
  4057. read-0 null
  4058. if [ "$null" ]; then
  4059. err "options parsing error, should start with an option line."
  4060. return 1
  4061. fi
  4062. while read-0 opt full_txt;do
  4063. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  4064. single_opts="$(printf "%s " $opt | single_opts_filter)"
  4065. for to_remove in "$@"; do
  4066. str_matches "$to_remove" $multi_opts $single_opts && {
  4067. continue 2
  4068. }
  4069. done
  4070. echo -n "$full_txt"
  4071. done
  4072. } < <(options_parser)
  4073. }
  4074. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  4075. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  4076. multi_opts_filter() {
  4077. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  4078. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  4079. tr ',' "\n" | nspc
  4080. }
  4081. single_opts_filter() {
  4082. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  4083. tr ',' "\n" | nspc
  4084. }
  4085. get_docker_compose_multi_opts_list() {
  4086. local action="$1" opts_list
  4087. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4088. echo "$opts_list" | multi_opts_filter
  4089. }
  4090. get_docker_compose_single_opts_list() {
  4091. local action="$1" opts_list
  4092. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4093. echo "$opts_list" | single_opts_filter
  4094. }
  4095. display_commands_help() {
  4096. local charm_actions
  4097. echo
  4098. echo "${WHITE}Commands${NORMAL} (added by compose):"
  4099. echo " ${DARKCYAN}cache${NORMAL} Control compose's cache"
  4100. echo " ${DARKCYAN}status${NORMAL} Display statuses of services"
  4101. echo
  4102. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  4103. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  4104. charm_actions_help=$(get_docker_charm_action_help) || return 1
  4105. if [ "$charm_actions_help" ]; then
  4106. echo
  4107. echo "${WHITE}Charm actions${NORMAL}:"
  4108. printf "%s\n" "$charm_actions_help" | \
  4109. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  4110. fi
  4111. }
  4112. get_docker_charm_action() {
  4113. local services service charm relation_name target_service relation_config \
  4114. target_charm services
  4115. ## XXXvlab: this is for get_service_relations
  4116. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4117. err-d "Failed to set relations hash."
  4118. return 1
  4119. }
  4120. services=($(get_all_services)) || return 1
  4121. for service in "${services[@]}"; do
  4122. printf "%s:\n" "$service"
  4123. charm=$(get_service_charm "$service") || return 1
  4124. for action in $(charm.ls_direct_actions "$charm"); do
  4125. printf " %s:\n" "$action"
  4126. printf " type: %s\n" "direct"
  4127. done
  4128. while read-0 relation_name target_service _relation_config _tech_dep; do
  4129. target_charm=$(get_service_charm "$target_service") || return 1
  4130. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4131. printf " %s:\n" "$action"
  4132. printf " type: %s\n" "indirect"
  4133. printf " inherited: %s\n" "$target_charm"
  4134. done
  4135. done < <(get_service_relations "$service")
  4136. done
  4137. }
  4138. export -f get_docker_charm_action
  4139. get_docker_charm_action_help() {
  4140. local services service charm relation_name target_service relation_config \
  4141. target_charm
  4142. ## XXXvlab: this is for get_service_relations
  4143. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4144. err-d "Failed to set relations hash."
  4145. return 1
  4146. }
  4147. services=($(get_all_services)) || return 1
  4148. for service in "${services[@]}"; do
  4149. out=$(
  4150. charm=$(get_service_charm "$service") || return 1
  4151. for action in $(charm.ls_direct_actions "$charm"); do
  4152. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  4153. done
  4154. while read-0 relation_name target_service _relation_config _tech_dep; do
  4155. target_charm=$(get_service_charm "$target_service") || return 1
  4156. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4157. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  4158. done
  4159. done < <(get_service_relations "$service")
  4160. )
  4161. if [ "$out" ]; then
  4162. echo " for ${DARKYELLOW}$service${NORMAL}:"
  4163. printf "%s\n" "$out"
  4164. fi
  4165. done
  4166. }
  4167. display_help() {
  4168. print_help
  4169. echo "${WHITE}Usage${NORMAL}:"
  4170. echo " $usage"
  4171. echo " $usage cache {clean|clear}"
  4172. echo "${WHITE}Options${NORMAL}:"
  4173. echo " -h, --help Print this message and quit"
  4174. echo " (ignoring any other options)"
  4175. echo " -V, --version Print current version and quit"
  4176. echo " (ignoring any other options)"
  4177. echo " --dirs Display data dirs and quit"
  4178. echo " (ignoring any other options)"
  4179. echo " --get-project-name Display project name and quit"
  4180. echo " (ignoring any other options)"
  4181. echo " --get-available-actions Display all available actions and quit"
  4182. echo " (ignoring any other options)"
  4183. echo " -v, --verbose Be more verbose"
  4184. echo " -q, --quiet Be quiet"
  4185. echo " -d, --debug Print full debugging information (sets also verbose)"
  4186. echo " --dry-compose-run If docker-compose will be run, only print out what"
  4187. echo " command line will be used."
  4188. echo " --no-relations Do not run any relation script"
  4189. echo " --no-hooks Do not run any hook script"
  4190. echo " --no-init Do not run any init script"
  4191. echo " --no-post-deploy Do not run any post-deploy script"
  4192. echo " --no-pre-deploy Do not run any pre-deploy script"
  4193. echo " --without-relation RELATION "
  4194. echo " Do not run given relation"
  4195. echo " -R, --rebuild-relations-to-service SERVICE"
  4196. echo " Will rebuild all relations to given service"
  4197. echo " --add-compose-content, -Y YAML"
  4198. echo " Will merge some direct YAML with the current compose"
  4199. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  4200. echo " --push-builds Will push cached docker images to docker cache registry"
  4201. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  4202. filter_docker_compose_help_message
  4203. display_commands_help
  4204. }
  4205. _graph_service() {
  4206. local service="$1" base="$1"
  4207. charm=$(get_service_charm "$service") || return 1
  4208. metadata=$(charm.metadata "$charm") || return 1
  4209. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  4210. if [[ "$subordinate" =~ ^True|true$ ]]; then
  4211. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  4212. master_charm=
  4213. while read-0 relation_name relation; do
  4214. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  4215. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  4216. if [ -z "$interface" ]; then
  4217. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  4218. return 1
  4219. fi
  4220. ## Action provided by relation ?
  4221. target_service=
  4222. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  4223. [ "$interface" == "$relation_name" ] && {
  4224. target_service="$candidate_target_service"
  4225. break
  4226. }
  4227. done < <(get_service_relations "$service")
  4228. if [ -z "$target_service" ]; then
  4229. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  4230. "${DARKYELLOW}$service$NORMAL compose definition."
  4231. return 1
  4232. fi
  4233. master_service="$target_service"
  4234. master_charm=$(get_service_charm "$target_service") || return 1
  4235. break
  4236. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  4237. fi
  4238. _graph_node_service "$service" "$base" "$charm"
  4239. _graph_edge_service "$service" "$subordinate" "$master_service"
  4240. }
  4241. _graph_node_service() {
  4242. local service="$1" base="$2" charm="$3"
  4243. cat <<EOF
  4244. "$(_graph_node_service_label ${service})" [
  4245. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  4246. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  4247. color = $([ "$base" ] && echo "blue" || echo "black")
  4248. fillcolor = "white"
  4249. fontname = "Courier New"
  4250. shape = "Mrecord"
  4251. label =<$(_graph_node_service_content "$service")>
  4252. ];
  4253. EOF
  4254. }
  4255. _graph_edge_service() {
  4256. local service="$1" subordinate="$2" master_service="$3"
  4257. while read-0 relation_name target_service relation_config tech_dep; do
  4258. cat <<EOF
  4259. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  4260. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  4261. fontsize = 16
  4262. fontcolor = "black"
  4263. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  4264. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  4265. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  4266. arrowtail = odot
  4267. # arrowhead = dotlicurve
  4268. taillabel = "$relation_name" ];
  4269. EOF
  4270. done < <(get_service_relations "$service") || return 1
  4271. }
  4272. _graph_node_service_label() {
  4273. local service="$1"
  4274. echo "service_$service"
  4275. }
  4276. _graph_node_service_content() {
  4277. local service="$1"
  4278. charm=$(get_service_charm "$service") || return 1
  4279. cat <<EOF
  4280. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  4281. <tr>
  4282. <td bgcolor="black" align="center" colspan="2">
  4283. <font color="white">$service</font>
  4284. </td>
  4285. </tr>
  4286. $(if [ "$charm" != "$service" ]; then
  4287. cat <<EOF2
  4288. <tr>
  4289. <td align="left" port="r0">charm: $charm</td>
  4290. </tr>
  4291. EOF2
  4292. fi)
  4293. </table>
  4294. EOF
  4295. }
  4296. cla_contains () {
  4297. local e
  4298. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  4299. return 1
  4300. }
  4301. filter_docker_compose_help_message() {
  4302. cat - |
  4303. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  4304. s/docker-compose.yml/compose.yml/g;
  4305. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  4306. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  4307. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  4308. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  4309. }
  4310. graph() {
  4311. local services=("$@")
  4312. declare -A entries
  4313. cat <<EOF
  4314. digraph g {
  4315. graph [
  4316. fontsize=30
  4317. labelloc="t"
  4318. label=""
  4319. splines=true
  4320. overlap=false
  4321. #rankdir = "LR"
  4322. ];
  4323. ratio = auto;
  4324. EOF
  4325. for target_service in "$@"; do
  4326. services=$(get_ordered_service_dependencies "$target_service") || return 1
  4327. for service in $services; do
  4328. [ "${entries[$service]}" ] && continue || entries[$service]=1
  4329. if cla_contains "$service" "${services[@]}"; then
  4330. base=true
  4331. else
  4332. base=
  4333. fi
  4334. _graph_service "$service" "$base"
  4335. done
  4336. done
  4337. echo "}"
  4338. }
  4339. cached_wget() {
  4340. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  4341. url="$1"
  4342. if [ -e "$cache_file" ]; then
  4343. cat "$cache_file"
  4344. touch "$cache_file"
  4345. return 0
  4346. fi
  4347. wget -O- "${url}" |
  4348. tee "$cache_file"
  4349. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4350. rm "$cache_file"
  4351. die "Unable to fetch '$url'."
  4352. return 1
  4353. fi
  4354. }
  4355. export -f cached_wget
  4356. [ "$SOURCED" ] && return 0
  4357. trap_add "EXIT" clean_cache
  4358. export COMPOSE_DOCKER_REGISTRY="${COMPOSE_DOCKER_REGISTRY:-docker.0k.io}"
  4359. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  4360. if [ -r /etc/default/charm ]; then
  4361. . "/etc/default/charm"
  4362. fi
  4363. if [ -r "/etc/default/$exname" ]; then
  4364. . "/etc/default/$exname"
  4365. fi
  4366. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  4367. ## userdir ? and global /etc/compose.yml ?
  4368. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  4369. /etc/default/compose /etc/compose/local.conf; do
  4370. [ -e "$cfgfile" ] || continue
  4371. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  4372. done
  4373. fi
  4374. _setup_state_dir
  4375. mkdir -p "$CACHEDIR" || exit 1
  4376. log () { cat; }
  4377. export -f log
  4378. ##
  4379. ## Argument parsing
  4380. ##
  4381. wrap_opts=()
  4382. services=()
  4383. remainder_args=()
  4384. compose_opts=()
  4385. compose_contents=()
  4386. action_opts=()
  4387. services_args=()
  4388. pos_arg_ct=0
  4389. no_hooks=
  4390. no_init=
  4391. action=
  4392. stage="main" ## switches from 'main', to 'action', 'remainder'
  4393. is_docker_compose_action=
  4394. is_docker_compose_action_multi_service=
  4395. rebuild_relations_to_service=()
  4396. color=
  4397. declare -A without_relations
  4398. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  4399. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  4400. while read-0 arg; do
  4401. case "$stage" in
  4402. "main")
  4403. case "$arg" in
  4404. --help|-h)
  4405. no_init=true ; no_hooks=true ; no_relations=true
  4406. display_help
  4407. exit 0
  4408. ;;
  4409. --verbose|-v)
  4410. export VERBOSE=true
  4411. compose_opts+=("--verbose")
  4412. ;;
  4413. --quiet|-q)
  4414. export QUIET=true
  4415. export wrap_opts+=("-q")
  4416. log () { cat >&2; }
  4417. export -f log
  4418. ;;
  4419. --version|-V)
  4420. print_version
  4421. docker-compose --version
  4422. docker --version
  4423. exit 0
  4424. ;;
  4425. -f|--file)
  4426. read-0 value
  4427. [ -e "$value" ] || die "File $value doesn't exists"
  4428. export COMPOSE_YML_FILE="$value"
  4429. shift
  4430. ;;
  4431. -p|--project-name)
  4432. read-0 value
  4433. export DEFAULT_PROJECT_NAME="$value"
  4434. compose_opts+=("--project-name $value")
  4435. shift
  4436. ;;
  4437. --color|-c)
  4438. if [ "$color" == "0" ]; then
  4439. err "Conflicting option --color with previous --no-ansi."
  4440. exit 1
  4441. fi
  4442. color=1
  4443. ansi_color yes
  4444. ;;
  4445. --no-ansi)
  4446. if [ "$color" == "1" ]; then
  4447. err "Conflicting option --no-ansi with previous --color."
  4448. exit 1
  4449. fi
  4450. color=0
  4451. ansi_color no
  4452. compose_opts+=("--no-ansi")
  4453. ;;
  4454. --no-relations)
  4455. export no_relations=true
  4456. ;;
  4457. --without-relation)
  4458. read-0 value
  4459. without_relations["$value"]=1
  4460. shift
  4461. ;;
  4462. --no-hooks)
  4463. export no_hooks=true
  4464. ;;
  4465. --no-init)
  4466. export no_init=true
  4467. ;;
  4468. --no-post-deploy)
  4469. export no_post_deploy=true
  4470. ;;
  4471. --no-pre-deploy)
  4472. export no_pre_deploy=true
  4473. ;;
  4474. --rebuild-relations-to-service|-R)
  4475. read-0 value
  4476. rebuild_relations_to_service+=("$value")
  4477. shift
  4478. ;;
  4479. --push-builds)
  4480. export COMPOSE_PUSH_TO_REGISTRY=1
  4481. ;;
  4482. --debug|-d)
  4483. export DEBUG=true
  4484. export VERBOSE=true
  4485. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  4486. ;;
  4487. --add-compose-content|-Y)
  4488. read-0 value
  4489. compose_contents+=("$value")
  4490. shift
  4491. ;;
  4492. --dirs)
  4493. echo "CACHEDIR: $CACHEDIR"
  4494. echo "VARDIR: $VARDIR"
  4495. exit 0
  4496. ;;
  4497. --get-project-name)
  4498. project=$(get_default_project_name) || exit 1
  4499. echo "$project"
  4500. exit 0
  4501. ;;
  4502. --get-available-actions)
  4503. get_docker_charm_action
  4504. exit $?
  4505. ;;
  4506. --dry-compose-run)
  4507. export DRY_COMPOSE_RUN=true
  4508. ;;
  4509. --*|-*)
  4510. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4511. read-0 value
  4512. compose_opts+=("$arg" "$value")
  4513. shift;
  4514. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4515. compose_opts+=("$arg")
  4516. else
  4517. err "Unknown option '$arg'. Please check help:"
  4518. display_help >&2
  4519. exit 1
  4520. fi
  4521. ;;
  4522. *)
  4523. action="$arg"
  4524. stage="action"
  4525. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  4526. is_docker_compose_action=true
  4527. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  4528. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  4529. if [ "$DC_MATCH_MULTI" ]; then
  4530. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  4531. fi
  4532. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  4533. pos_args=("${pos_args[@]:1}")
  4534. if [[ "${pos_args[0]}" == "[SERVICE...]" ]]; then
  4535. is_docker_compose_action_multi_service=1
  4536. elif [[ "${pos_args[0]}" == "SERVICE" ]]; then
  4537. is_docker_compose_action_multi_service=0
  4538. fi
  4539. # echo "USAGE: $DC_USAGE"
  4540. # echo "pos_args: ${pos_args[@]}"
  4541. # echo "MULTI: $DC_MATCH_MULTI"
  4542. # echo "SINGLE: $DC_MATCH_SINGLE"
  4543. # exit 1
  4544. else
  4545. stage="remainder"
  4546. fi
  4547. ;;
  4548. esac
  4549. ;;
  4550. "action") ## Only for docker-compose actions
  4551. case "$arg" in
  4552. --help|-h)
  4553. no_init=true ; no_hooks=true ; no_relations=true
  4554. action_opts+=("$arg")
  4555. ;;
  4556. --*|-*)
  4557. if [ "$is_docker_compose_action" ]; then
  4558. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4559. read-0 value
  4560. action_opts+=("$arg" "$value")
  4561. shift
  4562. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4563. action_opts+=("$arg")
  4564. else
  4565. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  4566. docker-compose "$action" --help |
  4567. filter_docker_compose_help_message >&2
  4568. exit 1
  4569. fi
  4570. fi
  4571. ;;
  4572. *)
  4573. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  4574. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  4575. services_args+=("$arg")
  4576. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  4577. services_args=("$arg") || exit 1
  4578. stage="remainder"
  4579. else
  4580. action_posargs+=("$arg")
  4581. ((pos_arg_ct++))
  4582. fi
  4583. ;;
  4584. esac
  4585. ;;
  4586. "remainder")
  4587. remainder_args+=("$arg")
  4588. while read-0 arg; do
  4589. remainder_args+=("$arg")
  4590. done
  4591. break 3
  4592. ;;
  4593. esac
  4594. shift
  4595. done < <(cla.normalize "$@")
  4596. ## These actions are additions to docker-compose actions and charm
  4597. ## actions
  4598. more_actions=(status)
  4599. if [[ "$action" == *" "* ]]; then
  4600. err "Invalid action name containing spaces: ${DARKCYAN}$action${NORMAL}"
  4601. exit 1
  4602. fi
  4603. is_more_action=
  4604. [[ " ${more_actions[*]} " == *" $action "* ]] && is_more_action=true
  4605. [ -n "$CACHEDIR" ] || die "No cache directory defined."
  4606. [ -d "$CACHEDIR" ] || die "Cache directory '$CACHEDIR' doesn't exists."
  4607. case "$action" in
  4608. cache)
  4609. case "${remainder_args[0]}" in
  4610. clean)
  4611. clean_cache
  4612. exit 0
  4613. ;;
  4614. clear)
  4615. Wrap "${wrap_opts[@]}" -v -d "clear cache directory" -- rm -rf "$CACHEDIR/"*
  4616. ## clear all docker caches
  4617. ## image name are like '[$COMPOSE_DOCKER_REGISTRY]cache/charm/CHARM_NAME:HASH'
  4618. Wrap "${wrap_opts[@]}" -v -d "clear docker cache" <<EOF
  4619. docker images --format "{{.Repository}}:{{.Tag}}" |
  4620. egrep "^($COMPOSE_DOCKER_REGISTRY/)?cache/charm/[a-zA-Z0-9._-]+:[0-9a-f]{32,32}$" |
  4621. while read -r image; do
  4622. docker rmi "\$image" || true
  4623. done
  4624. EOF
  4625. exit 0
  4626. ;;
  4627. *)
  4628. err "Unknown cache command: ${DARKCYAN}${remainder_args[0]}${NORMAL}"
  4629. exit 1
  4630. ;;
  4631. esac
  4632. ;;
  4633. status)
  4634. state_inner_cols=(name charm type state root)
  4635. state_all_services=
  4636. state_services=()
  4637. state_columns=()
  4638. state_columns_default=(name charm type state version)
  4639. state_filters=()
  4640. state_columns_default_msg=""
  4641. for col in "${state_columns_default[@]}"; do
  4642. if [ -n "$state_columns_default_msg" ]; then
  4643. state_columns_default_msg+=","
  4644. fi
  4645. state_columns_default_msg+="$col"
  4646. done
  4647. help="\
  4648. Display status information on services.
  4649. If no services are provided, all services in the root compose file
  4650. will be displayed. Use the --all option to display status of all
  4651. services (including dependencies).
  4652. $exname offers a few possible columns that can be complete on a charm
  4653. level by implementing an \`actions/get-COLNAME\` script.
  4654. These are the compose's columns: ${state_inner_cols[@]}.
  4655. Usage: status [options] [SERVICE...]
  4656. Options:
  4657. -h, --help Print this message and quit
  4658. -a, --all Display status of all services (removes all
  4659. filter, and will add a 'root' first column by
  4660. default)
  4661. -c, --column Columns to display, can provide several separated
  4662. by commas, or option can be repeated. You can add
  4663. a sign prefix to the name of the column to force
  4664. the alignment of the column (+: right, -: left),
  4665. (default: ${state_columns_default_msg})
  4666. -f, --filter Filter services by a key=value pair,
  4667. separated by commas or can be repeated.
  4668. (default: --filter root=yes)
  4669. -r, --raw Raw data output (no colors nor alignment)
  4670. -0 Separate field with NUL char. Implies raw data
  4671. output.
  4672. "
  4673. while read-0 arg; do
  4674. case "$arg" in
  4675. --help|-h)
  4676. echo "$help"
  4677. exit 0
  4678. ;;
  4679. --raw|-r|-0)
  4680. state_raw_output="$arg";
  4681. ## check if any state_columns have alignements specs
  4682. for col in "${state_columns[@]}"; do
  4683. if [[ "$col" == [-+]* ]]; then
  4684. err "Cannot use $arg and provide columns with alignment specs."
  4685. exit 1
  4686. fi
  4687. done
  4688. if [[ "$arg" == "-0" ]]; then
  4689. state_raw_output_nul=1
  4690. fi
  4691. ;;
  4692. --all|-a)
  4693. if [ "${#state_services[@]}" -gt 0 ]; then
  4694. err "Cannot use --all and provide services at the same time."
  4695. exit 1
  4696. fi
  4697. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4698. err "Cannot use --all and provide filters at the same time."
  4699. exit 1
  4700. fi
  4701. state_all_services=1
  4702. ;;
  4703. --column|-c)
  4704. read-0 value
  4705. if [[ "$value" == *,* ]]; then
  4706. state_columns_candidate=(${value//,/ })
  4707. else
  4708. state_columns_candidate=("$value")
  4709. fi
  4710. if [[ -n "$state_raw_output" ]]; then
  4711. for col in "${state_columns_candidate[@]}"; do
  4712. if [[ "$col" == [-+]* ]]; then
  4713. err "Cannot use ${state_raw_output} and provide columns with alignment specs."
  4714. exit 1
  4715. fi
  4716. done
  4717. fi
  4718. state_columns+=("${state_columns_candidate[@]}")
  4719. ;;
  4720. --filter|-f)
  4721. if [ "${#state_services[@]}" -gt 0 ]; then
  4722. err "Cannot use --filter and provide services at the same time."
  4723. exit 1
  4724. fi
  4725. if [ -n "$state_all_services" ]; then
  4726. err "Cannot use --all and provide filters at the same time."
  4727. exit 1
  4728. fi
  4729. read-0 value
  4730. if [[ "$value" == *,* ]]; then
  4731. state_filters+=(${value//,/ })
  4732. else
  4733. state_filters+=("$value")
  4734. fi
  4735. ;;
  4736. --*|-*)
  4737. err "Unknown option '$arg'. Please check help:"
  4738. echo "$help" >&2
  4739. ;;
  4740. *)
  4741. if [ -n "$state_all_services" ]; then
  4742. err "Cannot use --all and provide services at the same time."
  4743. exit 1
  4744. fi
  4745. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4746. err "Cannot use --filter and provide filters at the same time."
  4747. exit 1
  4748. fi
  4749. state_services+=("$arg")
  4750. ;;
  4751. esac
  4752. done < <(cla.normalize "${remainder_args[@]}")
  4753. if [ "${#state_columns[@]}" == 0 ]; then
  4754. state_columns=("${state_columns_default[@]}")
  4755. fi
  4756. ;;
  4757. esac
  4758. export compose_contents
  4759. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  4760. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  4761. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  4762. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  4763. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  4764. aexport remainder_args
  4765. ##
  4766. ## Actual code
  4767. ##
  4768. if [ -n "$DEBUG" ]; then
  4769. Elt "compute hashes"
  4770. start=$(time_now)
  4771. fi
  4772. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  4773. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  4774. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || exit 1
  4775. CHARM_STORE_HASH=$(charm.store_metadata_hash) || exit 1
  4776. COMBINED_HASH=$(H "$COMPOSE_YML_CONTENT_HASH" "$CHARM_STORE_HASH") || exit 1
  4777. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT COMPOSE_YML_CONTENT_HASH CHARM_STORE_HASH COMBINED_HASH
  4778. if [ -n "$DEBUG" ]; then
  4779. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4780. print_info "$(printf "%.3fs" "$elapsed")"
  4781. Feedback
  4782. fi
  4783. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  4784. ##
  4785. ## Get services in command line.
  4786. ##
  4787. if [ -z "$is_docker_compose_action" ] && [ -z "$is_more_action" ] && [ -n "$action" ]; then
  4788. action_service=${remainder_args[0]}
  4789. if [ -z "$action_service" ]; then
  4790. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  4791. display_commands_help
  4792. exit 1
  4793. fi
  4794. services_args=($(compose:yml:root:services)) || return 1
  4795. ## Required by has_service_action
  4796. service:all:set_relations_hash
  4797. remainder_args=("${remainder_args[@]:1}")
  4798. if has_service_action "$action_service" "$action" >/dev/null; then
  4799. is_service_action=true
  4800. services_args=("$action_service")
  4801. {
  4802. read-0 action_type
  4803. case "$action_type" in
  4804. "relation")
  4805. read-0 _ target_service _target_charm relation_name _ action_script_path
  4806. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  4807. services_args+=("$target_service")
  4808. ;;
  4809. "direct")
  4810. read-0 _ action_script_path
  4811. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  4812. ;;
  4813. esac
  4814. } < <(has_service_action "$action_service" "$action")
  4815. get_all_relations "${services_args[@]}" >/dev/null || {
  4816. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  4817. exit 1
  4818. }
  4819. ## Divert logging to stdout to stderr
  4820. log () { cat >&2; }
  4821. export -f log
  4822. else
  4823. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  4824. fi
  4825. else
  4826. case "$action" in
  4827. ps|up)
  4828. if [ "${#services_args[@]}" == 0 ]; then
  4829. services_args=($(compose:yml:root:services)) || return 1
  4830. fi
  4831. ;;
  4832. status)
  4833. services_args=("${state_services[@]}")
  4834. if [ "${#services_args[@]}" == 0 ] && [ -z "$state_all_services" ]; then
  4835. services_args=($(compose:yml:root:services)) || return 1
  4836. fi
  4837. ;;
  4838. config)
  4839. services_args=("${action_posargs[@]}")
  4840. ;;
  4841. esac
  4842. fi
  4843. export COMPOSE_ACTION="$action"
  4844. NO_CONSTRAINT_CHECK=True
  4845. case "$action" in
  4846. up|status|run)
  4847. NO_CONSTRAINT_CHECK=
  4848. if [ -n "$DEBUG" ]; then
  4849. Elt "solve all relations"
  4850. start=$(time_now)
  4851. fi
  4852. service:all:set_relations_hash || exit 1
  4853. if [ -n "$DEBUG" ]; then
  4854. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4855. print_info "$(printf "%.3fs" "$elapsed")"
  4856. Feedback
  4857. fi
  4858. all_services=($(get_all_services)) || exit 1
  4859. ## check that services_args is a subset of all_services
  4860. for service in "${services_args[@]}"; do
  4861. [[ " ${all_services[*]} " == *" $service "* ]] || {
  4862. err "Service ${DARKYELLOW}$service${NORMAL} is not defined in the current compose file."
  4863. echo " Neither is is a dependency of a service in the compose file." >&2
  4864. echo " These are the services directly or indirectly available from current compose file:" >&2
  4865. for service in "${all_services[@]}"; do
  4866. echo " - ${DARKYELLOW}$service${NORMAL}" >&2
  4867. done
  4868. exit 1
  4869. }
  4870. done
  4871. ;;
  4872. esac
  4873. case "$action" in
  4874. up)
  4875. PROJECT_NAME=$(get_default_project_name) || exit 1
  4876. ## Remove all intents (*ing states)
  4877. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*ing || true
  4878. ## Notify that we have the intent to bring up all these
  4879. ## This will be use in inner or concurrent 'run' to include the
  4880. ## services that are supposed to be up.
  4881. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME" || exit 1
  4882. services_args_deps=($(get_ordered_service_dependencies "${services_args[@]}")) || exit 1
  4883. for service in "${services_args_deps[@]}"; do
  4884. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service" || exit 1
  4885. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/up ] || {
  4886. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/deploying || exit 1
  4887. }
  4888. done
  4889. ## remove services not included in compose.yml anymore
  4890. all_services_deps=($(get_ordered_service_dependencies "${all_services[@]}")) || exit 1
  4891. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/up; do
  4892. [ -e "$service" ] || continue
  4893. state=${service##*/}
  4894. service=${service%/$state}
  4895. service=${service##*/}
  4896. if [[ " ${all_services_deps[*]} " != *" ${service} "* ]]; then
  4897. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  4898. fi
  4899. done
  4900. ;;
  4901. run)
  4902. PROJECT_NAME=$(get_default_project_name) || return 1
  4903. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  4904. ## Notify that we have the intent to bring up all these
  4905. ## This will be use in inner or concurrent 'run' to include the
  4906. ## services that are supposed to be up.
  4907. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/{up,deploying}; do
  4908. [ -e "$service" ] || continue
  4909. state=${service##*/}
  4910. service=${service%/$state}
  4911. service=${service##*/}
  4912. ## don't add if orphaning
  4913. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning ] && continue
  4914. done
  4915. fi
  4916. ;;
  4917. status)
  4918. if [ -n "${state_all_services}" ] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  4919. services_args=("${all_services[@]}")
  4920. fi
  4921. ;;
  4922. esac
  4923. if [ -n "$DEBUG" ]; then
  4924. Elt "get relation subset"
  4925. start=$(time_now)
  4926. fi
  4927. get_subset_relations "${services_args[@]}" >/dev/null || exit 1
  4928. if [ -n "$DEBUG" ]; then
  4929. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4930. print_info "$(printf "%.3fs" "$elapsed")"
  4931. Feedback
  4932. fi
  4933. if [ -n "$is_docker_compose_action" ] && [ "${#services_args[@]}" -gt 0 ]; then
  4934. services=($(get_master_services "${services_args[@]}")) || exit 1
  4935. if [ "$action" == "up" ]; then
  4936. action_posargs+=($(services:get:upable "${services_args[@]}")) || exit 1
  4937. elif [ "$is_docker_compose_action_multi_service" == "1" ]; then
  4938. action_posargs+=("${services[@]}")
  4939. elif [ "$is_docker_compose_action_multi_service" == "0" ]; then
  4940. action_posargs+=("${services[0]}") ## only the first service is the legit one
  4941. fi
  4942. ## Get rid of subordinates
  4943. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  4944. fi
  4945. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  4946. err "Fails to compile base 'docker-compose.yml'"
  4947. exit 1
  4948. }
  4949. ##
  4950. ## Pre-action
  4951. ##
  4952. full_init=
  4953. case "$action" in
  4954. build)
  4955. full_init=true ## will actually stop after build
  4956. ;;
  4957. up|run)
  4958. full_init=true
  4959. post_hook=true
  4960. ;;
  4961. ""|down|restart|logs|config|ps|status)
  4962. full_init=
  4963. ;;
  4964. *)
  4965. if [ "$is_service_action" ]; then
  4966. full_init=true
  4967. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4968. for keyword in "${keywords[@]}"; do
  4969. case "$keyword" in
  4970. no-hooks)
  4971. no_hooks=true
  4972. ;;
  4973. hooks)
  4974. full_init=true
  4975. ;;
  4976. esac
  4977. done
  4978. fi
  4979. ;;
  4980. esac
  4981. if [ -n "$full_init" ]; then
  4982. if [[ "$action" == "build" ]] || [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4983. [[ "$action" == "build" ]] || Section "acquire charm's images"
  4984. run_service_acquire_images "${services_args[@]}" || exit 1
  4985. Feed
  4986. [ "$action" == "build" ] && {
  4987. exit 0
  4988. }
  4989. Section setup host resources
  4990. setup_host_resources "${services_args[@]}" || exit 1
  4991. ## init in order
  4992. Section initialisation
  4993. run_service_hook init "${services_args[@]}" || exit 1
  4994. fi
  4995. ## Get relations
  4996. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4997. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4998. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4999. rebuild_relations_to_service=($rebuild_relations_to_service)
  5000. project=$(get_default_project_name) || return 1
  5001. for service in "${rebuild_relations_to_service[@]}"; do
  5002. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  5003. [ -d "$dir" ] && {
  5004. debug rm -rf "$dir"
  5005. rm -rf "$dir"
  5006. }
  5007. done
  5008. done
  5009. fi
  5010. run_service_relations "${services_args[@]}" || exit 1
  5011. fi
  5012. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  5013. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  5014. fi
  5015. fi | log
  5016. if [ "${PIPESTATUS[0]}" != 0 ]; then
  5017. exit 1
  5018. fi
  5019. [ "$action" == "build" ] && exit 0
  5020. state:fields:resolve-parallel() {
  5021. local cols rowsservice jobs state_msg out errlvl col
  5022. first_job=1
  5023. tick_pid=
  5024. concurrent_jobs=0
  5025. MAX_CONCURRENT_JOBS=$((3 + $(nproc)))
  5026. rows=()
  5027. cols=()
  5028. while [ "$#" -gt 0 ]; do
  5029. case "$1" in
  5030. --) shift; rows=("$@"); break;;
  5031. *) cols+=("$1") ;;
  5032. esac
  5033. shift
  5034. done
  5035. for col in "${cols[@]}"; do
  5036. for service in "${rows[@]}"; do
  5037. if [ "$concurrent_jobs" -ge "$MAX_CONCURRENT_JOBS" ]; then
  5038. wait -n # -p job_id ## not supported in this version of bash
  5039. ## job list is not accurate, but the number of elt is
  5040. ((concurrent_jobs--))
  5041. fi
  5042. (
  5043. p0 "$service" "$col" "-1" "" ## started
  5044. out=$(
  5045. case "${col//_/-}" in
  5046. root)
  5047. if [[ " ${compose_yml_services[*]} " == *" ${service} "* ]]; then
  5048. echo "1"
  5049. else
  5050. echo "0"
  5051. fi
  5052. ;;
  5053. name) e "$service" ;;
  5054. charm) get_service_charm "$service" ;;
  5055. state) service:state "$service" ;;
  5056. type) get_service_type "$service" ;;
  5057. upstream-version) service:upstream-version "$service" ;;
  5058. *)
  5059. if has_service_action "$service" "get-$col" >/dev/null; then
  5060. state_msg=$(run_service_action "$service" "get-$col") || exit 1
  5061. if [[ "$state_msg" == *$'\n'* ]]; then
  5062. e "${state_msg%%$'\n'*}"
  5063. else
  5064. e "${state_msg}"
  5065. fi
  5066. fi
  5067. ;;
  5068. esac 2>&1
  5069. )
  5070. errlvl="$?"
  5071. p0 "$service" "$col" "$errlvl" "$out"
  5072. ) &
  5073. jobs=("${jobs[@]}" $!)
  5074. ((concurrent_jobs++))
  5075. if [ -n "$first_job" ]; then
  5076. ## launch tick
  5077. (
  5078. while true; do
  5079. sleep 0.1
  5080. p0 "" "" "" ""
  5081. done
  5082. ) &
  5083. tick_pid=$!
  5084. first_job=
  5085. fi
  5086. done
  5087. done
  5088. wait "${jobs[@]}"
  5089. if [ -n "$tick_pid" ]; then
  5090. kill "$tick_pid"
  5091. fi
  5092. }
  5093. export -f state:fields:resolve-parallel
  5094. if [ "$action" == "status" ]; then
  5095. if [ -n "$DEBUG" ]; then
  5096. start=$(time_now)
  5097. fi
  5098. if ! [ -t 1 ]; then
  5099. state_raw_output=1
  5100. fi
  5101. if [[ -n "${state_all_services}" ]] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  5102. compose_yml_services=($(compose:yml:root:services)) || exit 1
  5103. fi
  5104. if [[ -n "${state_all_services}" ]]; then
  5105. state_columns=("root" ${state_columns[@]})
  5106. fi
  5107. state_columns_raw=()
  5108. for col in "${state_columns[@]}"; do
  5109. if [[ "$col" =~ ^[+-] ]]; then
  5110. col=${col:1}
  5111. fi
  5112. state_columns_raw+=("${col//-/_}")
  5113. done
  5114. state_columns_align=""
  5115. for col in "${state_columns[@]}"; do
  5116. if [[ "$col" == "-"* ]]; then
  5117. state_columns_align+="-"
  5118. elif [[ "$col" == "+"* ]]; then
  5119. state_columns_align+="+"
  5120. else
  5121. case "${col//_/-}" in
  5122. version|upstream-version) state_columns_align+="+";;
  5123. *) state_columns_align+="-";;
  5124. esac
  5125. fi
  5126. done
  5127. declare -A state_columns_idx=()
  5128. declare -A filter_idx=()
  5129. filter_cols=()
  5130. non_filter_cols=("${state_columns_raw[@]}")
  5131. for filter in "${state_filters[@]}"; do
  5132. IFS="=" read -r key value <<<"$filter"
  5133. if [[ " ${non_filter_cols[*]} " == *" $key "* ]]; then
  5134. ## remove from non_filter_cols
  5135. non_filter_cols=(${non_filter_cols[*]/$key})
  5136. fi
  5137. state_columns_idx["$col"]="${#filter_cols[@]}"
  5138. filter_cols+=("${key}")
  5139. done
  5140. tot_nb_cols=$(( ${#non_filter_cols[@]} + ${#filter_cols[@]} ))
  5141. ## make services_idx
  5142. declare -A services_idx=()
  5143. idx=0
  5144. for service in "${services_args[@]}"; do
  5145. services_idx["$service"]=$((idx++))
  5146. done
  5147. ## make state_columns_idx
  5148. idx=0
  5149. for col in "${non_filter_cols[@]}"; do
  5150. state_columns_idx["$col"]=$((${#filter_cols[@]} + idx++))
  5151. done
  5152. values=() ## all values
  5153. new_service_args=("${services_args[@]}") ## will remove service not satisfying filters
  5154. while read-0 service col E out; do
  5155. if [[ " ${new_service_args[*]} " != *" $service "* ]]; then
  5156. continue
  5157. fi
  5158. col_index="${state_columns_idx[$col]}"
  5159. service_index="${services_idx[$service]}"
  5160. values[service_index * tot_nb_cols + col_index]="$out"
  5161. ## check if all filter are valuated and satisfied
  5162. for filter in "${state_filters[@]}"; do
  5163. IFS="=" read -r key value <<<"$filter"
  5164. col_index="${state_columns_idx[$key]}"
  5165. if [ -z "${values[$((service_index * tot_nb_cols + col_index))]}" ]; then
  5166. break
  5167. fi
  5168. if [ "${values[$((service_index * tot_nb_cols + col_index))]}" != "$value" ]; then
  5169. new_service_args=(${new_service_args[*]/"$service"})
  5170. break
  5171. fi
  5172. done
  5173. done < <(state:fields:resolve-parallel "${filter_cols[@]}" -- "${services_args[@]}")
  5174. services_args=("${new_service_args[@]}")
  5175. if [ "${#services_args[@]}" == 0 ]; then
  5176. warn "No services found matching the filters." >&2
  5177. exit 0
  5178. fi
  5179. spinner_chars="⠋⠙⠸⠴⠤⠦⠇"
  5180. spinner_idx=0
  5181. SPINNERGRAY=$'\e[38;5;16;48;5;234m'
  5182. SPINNERRUNNING=$'\e[38;5;28;48;5;234m'
  5183. first_draw=1
  5184. last_draw=
  5185. if [ -z "$state_raw_output" ]; then
  5186. echo -en "\e[?25l"; stty -echo 2>/dev/null
  5187. trap_add EXIT,ERR "echo -en '\e[?25h'; stty echo 2>/dev/null"
  5188. fi
  5189. errors=()
  5190. declare -A errors_hash_idx=()
  5191. error_idx=0
  5192. values_valued=0
  5193. values_total=$(( ${#services_args[@]} * ${#state_columns_raw[@]} ))
  5194. values_threshold=$(( values_total / 2 ))
  5195. while read-0 service col E out; do
  5196. if [ -n "$service" ]; then
  5197. col_index="${state_columns_idx[$col]}"
  5198. service_index="${services_idx[$service]}"
  5199. if [[ "$E" -gt 0 ]]; then
  5200. error_hash=$(H "$col" "$E" "$out")
  5201. matching_error_idx="${errors_hash_idx[$error_hash]}"
  5202. if [[ -z "${matching_error_idx}" ]]; then
  5203. errors+=("$error_idx:$service:$col:$E:$out")
  5204. out="!Err[$((error_idx))]"
  5205. errors_hash_idx["$error_hash"]="$error_idx"
  5206. error_idx=$((error_idx + 1))
  5207. else
  5208. ## find the error to add the service
  5209. error="${errors[$matching_error_idx]}"
  5210. error="${error#*:}"
  5211. error_service="${error%%:*}"
  5212. error_tail="${error#*:}"
  5213. errors[matching_error_idx]="$matching_error_idx:$error_service,$service:$error_tail"
  5214. out="!Err[$((matching_error_idx))]"
  5215. fi
  5216. elif [[ "$E" == -1 ]]; then
  5217. values[service_index * tot_nb_cols + col_index]=$'\t'
  5218. continue
  5219. fi
  5220. values[service_index * tot_nb_cols + col_index]="$out"
  5221. values_valued=$((values_valued + 1))
  5222. if [[ "$values_valued" == "$values_total" ]]; then
  5223. last_draw=1
  5224. else
  5225. continue
  5226. fi
  5227. fi
  5228. [ -n "$state_raw_output" ] && continue
  5229. [[ $((values_valued)) -lt $((values_threshold)) ]] && continue
  5230. ## Draw table
  5231. if [ -n "$first_draw" ]; then
  5232. first_draw=
  5233. full_table=""
  5234. else
  5235. ## move up one line per service
  5236. full_table=$'\e'"[${#services_args[@]}A"
  5237. fi
  5238. spinner_idx=$(( (spinner_idx + 1) % ${#spinner_chars} ))
  5239. while read-0-err E "${state_columns_raw[@]}"; do
  5240. line_values=()
  5241. for col in "${state_columns_raw[@]}"; do
  5242. color=
  5243. value="${!col}"
  5244. read -r -- value_trim <<<"${!col}"
  5245. case "${value_trim}" in
  5246. "N/A") color=gray ;;
  5247. "!Err"*) color=darkred ;;
  5248. "⠿") color=spinnergray ;;
  5249. *)
  5250. if [[ "$spinner_chars" == *"$value_trim"* ]]; then
  5251. color=spinnerrunning
  5252. else
  5253. case "${col//_/-}" in
  5254. root)
  5255. case "$value_trim" in
  5256. 0) value=" ";;
  5257. 1) value="*";;
  5258. esac
  5259. ;;
  5260. name) color=darkyellow;;
  5261. charm) color=darkpink;;
  5262. state)
  5263. case "$value_trim" in
  5264. up) color=green;;
  5265. down) color=gray;;
  5266. deploying) color=yellow;;
  5267. *) color=red;;
  5268. esac
  5269. ;;
  5270. type)
  5271. case "$value_trim" in
  5272. run-once) color=gray;;
  5273. stub) color=gray;;
  5274. *) color=darkcyan;;
  5275. esac
  5276. ;;
  5277. *)
  5278. ;;
  5279. esac
  5280. fi
  5281. ;;
  5282. esac
  5283. color="${color^^}"
  5284. if [ -n "$color" ]; then
  5285. line_values+=("${!color}$value${NORMAL}")
  5286. else
  5287. line_values+=("$value")
  5288. fi
  5289. done
  5290. first=1
  5291. full_line=""
  5292. for value in "${line_values[@]}"; do
  5293. if [ -n "$first" ]; then
  5294. first=
  5295. else
  5296. full_line+=" "
  5297. fi
  5298. full_line+="$value"
  5299. done
  5300. full_table+="$full_line"$'\e[K\n'
  5301. done < <(
  5302. set -o pipefail
  5303. for service in "${services_args[@]}"; do
  5304. for col in "${state_columns_raw[@]}"; do
  5305. col_index="${state_columns_idx[$col]}"
  5306. service_index="${services_idx[$service]}"
  5307. value_idx="$((service_index * tot_nb_cols + col_index))"
  5308. if ! [[ -v "values[value_idx]" ]]; then
  5309. p0 " ⠿ "
  5310. continue
  5311. fi
  5312. value="${values[value_idx]}"
  5313. if [[ "$value" == $'\t' ]]; then
  5314. p0 " ${spinner_chars:$spinner_idx:1} "
  5315. elif [ -z "$value" ]; then
  5316. p0 "N/A"
  5317. else
  5318. p0 "$value"
  5319. fi
  5320. done
  5321. done | {
  5322. if [ -z "$state_raw_output" ]; then
  5323. col-0:normalize:size "${state_columns_align}"
  5324. else
  5325. cat
  5326. fi
  5327. }
  5328. echo 0
  5329. )
  5330. printf "%s" "$full_table"
  5331. if [ "$E" != 0 ]; then
  5332. err "Unexpected failure while drawing table"
  5333. exit $E
  5334. fi
  5335. done < <(state:fields:resolve-parallel "${non_filter_cols[@]}" -- "${services_args[@]}")
  5336. for error in "${errors[@]}"; do
  5337. echo "" >&2
  5338. idx=${error%%:*}; error=${error#*:}
  5339. service=${error%%:*}; error=${error#*:}
  5340. col=${error%%:*}; error=${error#*:}
  5341. E=${error%%:*}; error=${error#*:}
  5342. service_list_str=""
  5343. services=(${service//,/ })
  5344. first=1
  5345. for service in "${services[@]}"; do
  5346. if [ -n "$first" ]; then
  5347. first=
  5348. else
  5349. service_list_str+=", "
  5350. fi
  5351. service_list_str+="${DARKYELLOW}$service${NORMAL}"
  5352. done
  5353. echo "${RED}Error${DARKRED}[$idx]:${NORMAL} while computing" \
  5354. "${WHITE}$col${NORMAL} for $service_list_str" >&2
  5355. echo "$error" | prefix " ${GRAY}|${NORMAL} " >&2
  5356. echo " ${GRAY}..${NORMAL} ${WHITE}Exited${NORMAL} with errorlevel ${DARKRED}$E${NORMAL}" >&2
  5357. done
  5358. if [[ "${#errors[@]}" -gt 0 ]]; then
  5359. if [ -n "$DEBUG" ]; then
  5360. Elt "table computation ${DARKRED}failed${NORMAL}"
  5361. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  5362. print_info "${elapsed}s"
  5363. Feedback
  5364. fi
  5365. exit 1
  5366. fi
  5367. if [ -n "$state_raw_output" ]; then
  5368. for service in "${services_args[@]}"; do
  5369. first=1
  5370. for col in "${state_columns_raw[@]}"; do
  5371. col_index="${state_columns_idx[$col]}"
  5372. service_index="${services_idx[$service]}"
  5373. value_idx="$((service_index * tot_nb_cols + col_index))"
  5374. value="${values[$value_idx]}"
  5375. if [ -n "$first" ]; then
  5376. first=
  5377. else
  5378. if [ -n "$state_raw_output_nul" ]; then
  5379. printf "\0"
  5380. else
  5381. printf " "
  5382. fi
  5383. fi
  5384. printf "%s" "$value"
  5385. done
  5386. if [ -n "$state_raw_output_nul" ]; then
  5387. printf "\0"
  5388. else
  5389. printf "\n"
  5390. fi
  5391. done
  5392. fi
  5393. if [ -n "$DEBUG" ]; then
  5394. Elt "table computation ${GREEN}successful${NORMAL}"
  5395. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  5396. print_info "${elapsed}s"
  5397. Feedback
  5398. fi
  5399. exit 0
  5400. fi
  5401. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  5402. charm=$(get_service_charm "${services_args[0]}") || exit 1
  5403. metadata=$(charm.metadata "$charm") || exit 1
  5404. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  5405. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5406. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  5407. fi
  5408. fi
  5409. export SERVICE_PACK="${services_args[*]}"
  5410. ##
  5411. ## Docker-compose
  5412. ##
  5413. errlvl="0"
  5414. case "$action" in
  5415. up|start|stop|build|run)
  5416. ## force daemon mode for up
  5417. if [[ "$action" == "up" ]]; then
  5418. if ! array_member action_opts -d; then
  5419. action_opts+=("-d")
  5420. fi
  5421. if ! array_member action_opts --remove-orphans; then
  5422. action_opts+=("--remove-orphans")
  5423. fi
  5424. fi
  5425. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5426. ;;
  5427. logs)
  5428. if ! array_member action_opts --tail; then ## force daemon mode for up
  5429. action_opts+=("--tail" "10")
  5430. fi
  5431. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5432. ;;
  5433. "")
  5434. launch_docker_compose "${compose_opts[@]}"
  5435. ;;
  5436. graph)
  5437. graph $SERVICE_PACK
  5438. ;;
  5439. config)
  5440. ## removing the services
  5441. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  5442. ## forcing docker-compose config to output the config file to stdout and not stderr
  5443. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  5444. echo "$out"
  5445. exit 1
  5446. }
  5447. echo "$out"
  5448. warn "Runtime configuration modification (from relations) are not included here."
  5449. ;;
  5450. down)
  5451. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  5452. debug "Adding a default argument of '--remove-orphans'"
  5453. action_opts+=("--remove-orphans")
  5454. fi
  5455. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  5456. ;;
  5457. *)
  5458. if [ "$is_service_action" ]; then
  5459. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  5460. errlvl="$?"
  5461. errlvl "$errlvl"
  5462. else
  5463. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5464. fi
  5465. ;;
  5466. esac || exit 1
  5467. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  5468. run_service_hook post_deploy "${services_args[@]}" || exit 1
  5469. fi
  5470. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  5471. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5472. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  5473. fi
  5474. fi
  5475. case "$action" in
  5476. up)
  5477. ## Notify that services in 'deploying' states have been deployed
  5478. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/deploying; do
  5479. [ -e "$service" ] || continue
  5480. state=${service##*/}
  5481. service=${service%/$state}
  5482. service=${service##*/}
  5483. mv "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/{deploying,up} || exit 1
  5484. done
  5485. ## Notify that services in 'orphaning' states have been removed
  5486. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/orphaning; do
  5487. [ -e "$service" ] || continue
  5488. state=${service##*/}
  5489. service=${service%/$state}
  5490. service=${service##*/}
  5491. rm "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  5492. done
  5493. ;;
  5494. down)
  5495. PROJECT_NAME=$(get_default_project_name) || return 1
  5496. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  5497. if ! dir_is_empty "$SERVICE_STATE_PATH/$PROJECT_NAME"; then
  5498. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*
  5499. fi
  5500. rmdir "$SERVICE_STATE_PATH/$PROJECT_NAME"/{*,}
  5501. fi
  5502. ;;
  5503. esac
  5504. clean_unused_docker_compose || exit 1
  5505. exit "$errlvl"