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.

5942 lines
201 KiB

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