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.

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