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.

5895 lines
200 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. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1177. result
  1178. if [ -e "$cache_file" ]; then
  1179. #debug "$FUNCNAME: SESSION cache hit"
  1180. cat "$cache_file" || return 1
  1181. return 0
  1182. fi
  1183. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  1184. docker_compose=$(get_compose_yml_content) || return 1
  1185. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  1186. charm=$(echo "$result" | shyaml get-value charm 2>/dev/null) || return 1
  1187. metadata=$(charm.metadata "$charm") || return 1
  1188. if default_options=$(printf "%s" "$metadata" | shyaml -y -q get-value default-options); then
  1189. default_options=$(yaml_key_val_str "options" "$default_options") || return 1
  1190. result=$(merge_yaml_str "$default_options" "$result") || return 1
  1191. fi
  1192. echo "$result" | tee "$cache_file" || return 1
  1193. }
  1194. export -f get_compose_service_def
  1195. _get_service_charm_cached () {
  1196. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1197. if [ -e "$cache_file" ]; then
  1198. # debug "$FUNCNAME: cache hit $1"
  1199. cat "$cache_file" &&
  1200. touch "$cache_file" || return 1
  1201. return 0
  1202. fi
  1203. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  1204. if [ -z "$charm" ]; then
  1205. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  1206. return 1
  1207. fi
  1208. echo "$charm" | tee "$cache_file" || return 1
  1209. }
  1210. export -f _get_service_charm_cached
  1211. get_service_charm () {
  1212. local service="$1"
  1213. if [ -z "$service" ]; then
  1214. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  1215. return 1
  1216. fi
  1217. service_def=$(get_compose_service_def "$service") || return 1
  1218. _get_service_charm_cached "$service" "$service_def"
  1219. }
  1220. export -f get_service_charm
  1221. ## built above the docker-compose abstraction, so it relies on the
  1222. ## full docker-compose.yml to be already built.
  1223. get_service_def () {
  1224. local service="$1" def
  1225. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  1226. err "${FUNCNAME[0]} is meant to be called after"\
  1227. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  1228. echo " Called by:" >&2
  1229. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  1230. return 1
  1231. fi
  1232. def=$(cat "$_CURRENT_DOCKER_COMPOSE" | shyaml get-value "services.${service//./\\.}" 2>/dev/null)
  1233. if [ -z "$def" ]; then
  1234. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  1235. return 1
  1236. fi
  1237. echo "$def"
  1238. }
  1239. export -f get_service_def
  1240. get_build_hash() {
  1241. local dir="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$1")" hash
  1242. if [ -e "$cache_file" ]; then
  1243. # debug "$FUNCNAME: cache hit ($*)"
  1244. cat "$cache_file"
  1245. return 0
  1246. fi
  1247. ## Check that there's a Dockerfile in this directory
  1248. if [ ! -e "$dir/Dockerfile" ]; then
  1249. err "No 'Dockerfile' found in '$dir'."
  1250. return 1
  1251. fi
  1252. ## use find to md5sum all files in the directory and make a final hash
  1253. hash=$(set -o pipefail; cd "$dir"; env -i find "." -type f -exec md5sum {} \; |
  1254. sort | md5sum | awk '{print $1}') || {
  1255. err "Failed to get hash for '$dir'."
  1256. return 1
  1257. }
  1258. printf "%s" "$hash" | tee "$cache_file"
  1259. return $?
  1260. }
  1261. export -f get_build_hash
  1262. ### Query/Get cached image from registry
  1263. ##
  1264. ## Returns on stdout the name of the image if found, or an empty string if not
  1265. cache:image:registry:get() {
  1266. local charm="$1" hash="$2" service="$3"
  1267. local charm_image_name="cache/charm/$charm"
  1268. local charm_image="$charm_image_name:$hash"
  1269. Elt "pulling ${DARKPINK}$charm${NORMAL} image from $COMPOSE_DOCKER_REGISTRY" >&2
  1270. if out=$(docker pull "$COMPOSE_DOCKER_REGISTRY/$charm_image" 2>&1); then
  1271. docker tag "$COMPOSE_DOCKER_REGISTRY/$charm_image" "$charm_image" || {
  1272. err "Failed set image '$COMPOSE_DOCKER_REGISTRY/$charm_image' as '$charm_image'" \
  1273. "for ${DARKYELLOW}$service${NORMAL}."
  1274. return 1
  1275. }
  1276. print_info "found" >&2
  1277. print_status success >&2
  1278. Feed >&2
  1279. printf "%s" "$charm_image" | tee "$cache_file"
  1280. return $?
  1281. fi
  1282. if [[ "$out" != *"manifest unknown"* ]] && [[ "$out" != *"not found"* ]]; then
  1283. print_status failure >&2
  1284. Feed >&2
  1285. err "Failed to pull image '$COMPOSE_DOCKER_REGISTRY/$charm_image'" \
  1286. "for ${DARKYELLOW}$service${NORMAL}:"
  1287. e "$out"$'\n' | prefix " ${GRAY}|${NORMAL} " >&2
  1288. return 1
  1289. fi
  1290. print_info "not found" >&2
  1291. if test "$type_method" = "long"; then
  1292. __status="[${NOOP}ABSENT${NORMAL}]"
  1293. else
  1294. echo -n "${NOOP}"
  1295. shift; shift;
  1296. echo -n "$*${NORMAL}"
  1297. fi >&2
  1298. Feed >&2
  1299. }
  1300. export -f cache:image:registry:get
  1301. ### Store cached image on registry
  1302. ##
  1303. ## Returns nothing
  1304. cache:image:registry:put() {
  1305. if [ -n "$COMPOSE_DOCKER_REGISTRY" ] && [ -n "$COMPOSE_PUSH_TO_REGISTRY" ]; then
  1306. local charm="$1" hash="$2" service="$3"
  1307. local charm_image_name="cache/charm/$charm"
  1308. local charm_image="$charm_image_name:$hash"
  1309. Wrap -d "pushing ${DARKPINK}$charm${NORMAL} image to $COMPOSE_DOCKER_REGISTRY" <<EOF || return 1
  1310. docker tag "$charm_image" "$COMPOSE_DOCKER_REGISTRY/$charm_image" &&
  1311. docker push "$COMPOSE_DOCKER_REGISTRY/$charm_image"
  1312. EOF
  1313. fi >&2
  1314. }
  1315. export -f cache:image:registry:put
  1316. ### Produce docker cached charm image 'cache/charm/$charm:$hash'
  1317. ##
  1318. ## Either by fetching it from a registry or by building it from a
  1319. ## Dockerfile.
  1320. cache:image:produce() {
  1321. local type="$1" src="$2" charm="$3" hash="$4" service="$5"
  1322. local charm_image_name="cache/charm/$charm"
  1323. local charm_image="$charm_image_name:$hash"
  1324. case "$type" in
  1325. fetch)
  1326. local specified_image="$src"
  1327. ## will not pull upstream image if already present locally
  1328. if ! docker_has_image "${specified_image}"; then
  1329. if ! out=$(docker pull "${specified_image}" 2>&1); then
  1330. err "Failed to pull image '$specified_image' for ${DARKYELLOW}$service${NORMAL}:"
  1331. echo "$out" | prefix " | " >&2
  1332. return 1
  1333. fi
  1334. fi
  1335. # specified_image_id=$(docker_image_id "$specified_image") || return 1
  1336. # charm_image_id=
  1337. # if docker_has_image "${image_dst}"; then
  1338. # charm_image_id=$(docker_image_id "${image_dst}") || return 1
  1339. # fi
  1340. # if [ "$specified_image_id" != "$charm_image_id" ]; then
  1341. docker tag "$specified_image" "${charm_image}" || return 1
  1342. # fi
  1343. ;;
  1344. build)
  1345. local service_build="$src"
  1346. build_opts=()
  1347. if [ "$COMPOSE_ACTION" == "build" ]; then
  1348. while read-0 arg; do
  1349. case "$arg" in
  1350. -t|--tag)
  1351. ## XXXvlab: doesn't seem to be actually a valid option
  1352. if [ -n "$COMPOSE_PUSH_TO_REGISTRY" ]; then
  1353. err "You can't use -t|--tag option when pushing to a registry."
  1354. exit 1
  1355. fi
  1356. has_named_image=true
  1357. read-0 val ## should always be okay because already checked
  1358. build_opts+=("$arg" "$val")
  1359. ;;
  1360. --help|-h)
  1361. docker-compose "$action" --help |
  1362. filter_docker_compose_help_message >&2
  1363. exit 0
  1364. ;;
  1365. --*|-*)
  1366. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  1367. read-0 value
  1368. build_opts+=("$arg" "$value")
  1369. shift
  1370. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  1371. build_opts+=("$arg")
  1372. else
  1373. err "Unexpected error while parsing a second time the build arguments."
  1374. fi
  1375. ;;
  1376. *)
  1377. ## Already parsed
  1378. build_opts+=("$arg")
  1379. ;;
  1380. esac
  1381. done < <(cla.normalize "${action_opts[@]}")
  1382. fi
  1383. if [ -z "$has_named_image" ]; then
  1384. build_opts+=(-t "${charm_image}")
  1385. fi
  1386. Wrap -v -d "Building ${DARKPINK}$charm${NORMAL}:$hash image" -- \
  1387. docker build "$service_build" -t "${charm_image}" "${build_opts[@]}" >&2 || {
  1388. err "Failed to build image '${charm_image}' for ${DARKYELLOW}$service${NORMAL}."
  1389. return 1
  1390. }
  1391. if [ -n "$has_named_image" ]; then
  1392. exit 0
  1393. fi
  1394. ;;
  1395. *)
  1396. err "Unknown type '$type'."
  1397. return 1
  1398. ;;
  1399. esac
  1400. }
  1401. export -f cache:image:produce
  1402. ## Will modify current $_CURRENT_DOCKER_COMPOSE file
  1403. service_ensure_image_ready() {
  1404. if [ -z "$COMBINED_HASH" ]; then
  1405. err "Expected \$COMBINED_HASH to be set."
  1406. return 1
  1407. fi
  1408. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$COMBINED_HASH" \
  1409. master_service service_def service_image service_build service_dockerfile image \
  1410. specified_image specified_image_id charm_image_name hash \
  1411. service_quoted
  1412. if [ -e "$cache_file" ]; then
  1413. #debug "$FUNCNAME: cache hit ($*)"
  1414. touch "$cache_file" || return 1
  1415. cat "$cache_file"
  1416. return 0
  1417. fi
  1418. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  1419. err "${FUNCNAME[0]} is meant to be called after"\
  1420. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  1421. echo " Called by:" >&2
  1422. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  1423. return 1
  1424. fi
  1425. master_service="$(get_top_master_service_for_service "$service")" || {
  1426. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  1427. return 1
  1428. }
  1429. if [ "$master_service" != "$service" ]; then
  1430. image=$(service_ensure_image_ready "$master_service") || return 1
  1431. printf "%s" "$image" | tee "$cache_file"
  1432. return $?
  1433. fi
  1434. ## check if \$_CURRENT_DOCKER_COMPOSE's service def is already correctly setup
  1435. local charm="$(get_service_charm "$service")" || return 1
  1436. local charm_image_name="cache/charm/$charm" || return 1
  1437. local service_def="$(get_service_def "$service")" || {
  1438. err "Could not get docker-compose service definition for $DARKYELLOW$service$NORMAL."
  1439. return 1
  1440. }
  1441. local service_quoted=${service//./\\.}
  1442. if specified_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null); then
  1443. if [ "$specified_image" == "$charm_image_name"* ]; then
  1444. ## Assume we already did the change
  1445. printf "%s" "$specified_image" | tee "$cache_file"
  1446. return 0
  1447. fi
  1448. if [[ "$specified_image" == "${COMPOSE_DOCKER_REGISTRY}/"* ]]; then
  1449. if ! docker_has_image "${specified_image}"; then
  1450. Wrap "${wrap_opts[@]}" \
  1451. -v -d "pulling ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" -- \
  1452. docker pull "${specified_image}" >&2 || return 1
  1453. else
  1454. if [ -n "$DEBUG" ]; then
  1455. Elt "using local ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" >&2
  1456. print_status noop >&2
  1457. Feed >&2
  1458. fi
  1459. fi
  1460. ## Already on the cache server
  1461. printf "%s" "$specified_image" | tee "$cache_file"
  1462. return 0
  1463. fi
  1464. src="$specified_image"
  1465. hash=$(echo "$specified_image" | md5sum | cut -f 1 -d " ") || return 1
  1466. type=fetch
  1467. ## replace image by charm image
  1468. yq -i ".services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1469. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1470. else
  1471. if ! src=$(echo "$service_def" | shyaml get-value build 2>/dev/null); then
  1472. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  1473. echo "$service_def" >&2
  1474. return 1
  1475. fi
  1476. ## According to https://stackoverflow.com/questions/32230577 , if there's a build,
  1477. ## then the built image will get name ${project}_${service}
  1478. hash=$(get_build_hash "$src") || return 1
  1479. type=build
  1480. ## delete build key from service_def and add image to charm_image_name
  1481. yq -i "del(.services.[\"${service_quoted}\"].build) |
  1482. .services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1483. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1484. fi
  1485. if [ "$COMPOSE_ACTION" != "build" ] && docker_has_image "${charm_image_name}:${hash}"; then
  1486. if [ -n "$DEBUG" ]; then
  1487. Elt "using ${DARKPINK}$charm${NORMAL}'s image from local cache" >&2
  1488. print_status noop >&2
  1489. Feed >&2
  1490. fi
  1491. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1492. printf "%s" "${charm_image_name}:${hash}" | tee "$cache_file"
  1493. return $?
  1494. fi
  1495. ## Can we pull it ? Let's check on $COMPOSE_DOCKER_REGISTRY
  1496. if [ "$COMPOSE_ACTION" != "build" ] && [ -n "$COMPOSE_DOCKER_REGISTRY" ]; then
  1497. img=$(cache:image:registry:get "$charm" "$hash" "$service") || {
  1498. err "Failed to get image '$charm_image_name:$hash' from registry for ${DARKYELLOW}$service${NORMAL}."
  1499. return 1
  1500. }
  1501. [ -n "$img" ] && {
  1502. printf "%s" "$img" | tee "$cache_file"
  1503. return $?
  1504. }
  1505. fi
  1506. cache:image:produce "$type" "$src" "$charm" "$hash" "$service" || return 1
  1507. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1508. printf "%s" "${charm_image_name}:$hash" | tee "$cache_file"
  1509. return $?
  1510. }
  1511. export -f service_ensure_image_ready
  1512. get_charm_relation_def () {
  1513. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1514. relation_def metadata
  1515. if [ -e "$cache_file" ]; then
  1516. # debug "$FUNCNAME: cache hit ($*)"
  1517. cat "$cache_file"
  1518. return 0
  1519. fi
  1520. metadata="$(charm.metadata "$charm")" || return 1
  1521. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  1522. echo "$relation_def" | tee "$cache_file"
  1523. }
  1524. export -f get_charm_relation_def
  1525. get_charm_tech_dep_orientation_for_relation() {
  1526. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1527. relation_def value
  1528. if [ -e "$cache_file" ]; then
  1529. # debug "$FUNCNAME: cache hit ($*)"
  1530. cat "$cache_file"
  1531. return 0
  1532. fi
  1533. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  1534. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1535. value=${value:-True}
  1536. printf "%s" "$value" | tee "$cache_file"
  1537. }
  1538. export -f get_charm_tech_dep_orientation_for_relation
  1539. get_service_relation_tech_dep() {
  1540. local service="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1541. charm tech_dep
  1542. if [ -e "$cache_file" ]; then
  1543. # debug "$FUNCNAME: cache hit ($*)"
  1544. cat "$cache_file"
  1545. return 0
  1546. fi
  1547. charm=$(get_service_charm "$service") || return 1
  1548. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$charm" "$relation_name")" || return 1
  1549. printf "%s" "$tech_dep" | tee "$cache_file"
  1550. }
  1551. export -f get_service_relation_tech_dep
  1552. ##
  1553. ## Use compose file to get deps, and relation definition in metadata.yml
  1554. ## for tech-dep attribute.
  1555. get_service_deps() {
  1556. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")"
  1557. if [ -e "$cache_file" ]; then
  1558. # debug "$FUNCNAME: cache hit ($*)"
  1559. cat "$cache_file"
  1560. return 0
  1561. fi
  1562. (
  1563. set -o pipefail
  1564. get_service_relations "$service" | \
  1565. while read-0 relation_name target_service _relation_config tech_dep; do
  1566. echo "$target_service"
  1567. done | tee "$cache_file"
  1568. ) || return 1
  1569. }
  1570. export -f get_service_deps
  1571. ## XXXvlab: cache was disabled because improper. Indeed, this needs to cache
  1572. ## 'depths' full state. Second, it should be
  1573. _rec_get_depth() {
  1574. local elt=$1 dep deps max
  1575. [ "${depths[$elt]}" ] && return 0
  1576. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -pA depths)" "$GLOBAL_ALL_RELATIONS_HASH")"
  1577. if [ -e "$cache_file.depths" ]; then
  1578. #debug "$FUNCNAME: cache hit ($*) - $cache_file.depths"
  1579. while read-0 k v; do
  1580. depths["$k"]="$v"
  1581. done < "$cache_file.depths"
  1582. while read-0 k v; do
  1583. visited["$k"]="$v"
  1584. done < "$cache_file.visited"
  1585. return 0
  1586. fi
  1587. visited[$elt]=1
  1588. #debug "Setting visited[$elt]"
  1589. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1590. deps=$(get_service_deps "$elt") || {
  1591. debug "Failed get_service_deps $elt"
  1592. return 1
  1593. }
  1594. # debug "$elt deps are:" $deps
  1595. max=0
  1596. for dep in $deps; do
  1597. [ "${visited[$dep]}" ] && {
  1598. #debug "Already computing $dep"
  1599. continue
  1600. }
  1601. _rec_get_depth "$dep" || return 1
  1602. #debug "Requesting depth[$dep]"
  1603. if (( ${depths[$dep]} > max )); then
  1604. max="${depths[$dep]}"
  1605. fi
  1606. done
  1607. # debug "Setting depth[$elt] to $((max + 1))"
  1608. depths[$elt]=$((max + 1))
  1609. array_kv_to_stdin depths > "$cache_file.depths"
  1610. array_kv_to_stdin visited > "$cache_file.visited"
  1611. # debug "DEPTHS: $(declare -pA depths)"
  1612. # debug "$FUNCNAME: caching hit ($*) - $cache_file"
  1613. }
  1614. export -f _rec_get_depth
  1615. get_ordered_service_dependencies() {
  1616. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")" \
  1617. i value key heads depths visited
  1618. if [ -e "$cache_file" ]; then
  1619. # debug "$FUNCNAME: cache hit ($*)"
  1620. cat "$cache_file"
  1621. return 0
  1622. fi
  1623. #debug "Figuring ordered deps of $DARKYELLOW${services[@]}$NORMAL"
  1624. if [ -z "${services[*]}" ]; then
  1625. return 0
  1626. # print_syntax_error "$FUNCNAME: no arguments"
  1627. # return 1
  1628. fi
  1629. declare -A depths
  1630. declare -A visited
  1631. heads=("${services[@]}")
  1632. while [ "${#heads[@]}" != 0 ]; do
  1633. array_pop heads head
  1634. _rec_get_depth "$head" || return 1
  1635. done
  1636. i=0
  1637. while [ "${#depths[@]}" != 0 ]; do
  1638. for key in "${!depths[@]}"; do
  1639. value="${depths[$key]}"
  1640. if [ "$value" == "$i" ]; then
  1641. echo "$key"
  1642. unset depths[$key]
  1643. fi
  1644. done
  1645. ((i++))
  1646. done | tee "$cache_file"
  1647. }
  1648. export -f get_ordered_service_dependencies
  1649. ## Modify $_CURRENT_DOCKER_COMPOSE file, and fills cache
  1650. run_service_acquire_images () {
  1651. local service subservice subservices loaded
  1652. _CURRENT_DOCKER_COMPOSE_HASH=$(hash_get < "$_CURRENT_DOCKER_COMPOSE")
  1653. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" "$_CURRENT_DOCKER_COMPOSE_HASH")"
  1654. if [ -e "$cache_file" ]; then
  1655. # debug "$FUNCNAME: cache hit ($*)"
  1656. touch "$cache_file" || return 1
  1657. cp "$cache_file" "$_CURRENT_DOCKER_COMPOSE" || return 1
  1658. return 0
  1659. fi
  1660. declare -A loaded
  1661. for service in "$@"; do
  1662. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1663. for subservice in $subservices; do
  1664. if [ "${loaded[$subservice]}" ]; then
  1665. ## Prevent double inclusion of same service if this
  1666. ## service is deps of two or more of your
  1667. ## requirements.
  1668. continue
  1669. fi
  1670. type=$(get_service_type "$subservice") || return 1
  1671. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1672. if [ "$type" != "stub" ]; then
  1673. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1674. fi
  1675. loaded[$subservice]=1
  1676. done
  1677. done
  1678. cp "$_CURRENT_DOCKER_COMPOSE" "$cache_file" || return 1
  1679. return 0
  1680. }
  1681. run_service_hook () {
  1682. local action="$1" service subservice subservices loaded
  1683. shift
  1684. declare -A loaded
  1685. for service in "$@"; do
  1686. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1687. for subservice in $subservices; do
  1688. if [ "${loaded[$subservice]}" ]; then
  1689. ## Prevent double inclusion of same service if this
  1690. ## service is deps of two or more of your
  1691. ## requirements.
  1692. continue
  1693. fi
  1694. charm=$(get_service_charm "$subservice") || return 1
  1695. charm.has_hook "$charm" "$action" >/dev/null || continue
  1696. type=$(get_service_type "$subservice") || return 1
  1697. PROJECT_NAME=$(get_default_project_name) || return 1
  1698. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1699. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1700. if [ "$type" != "stub" ]; then
  1701. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1702. fi
  1703. Wrap "${wrap_opts[@]}" -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1704. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1705. export SERVICE_NAME=$subservice
  1706. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1707. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1708. export CHARM_NAME="$charm"
  1709. export PROJECT_NAME="$PROJECT_NAME"
  1710. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1711. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1712. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1713. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1714. charm.run_hook "local" "$charm" "$action"
  1715. EOF
  1716. loaded[$subservice]=1
  1717. done
  1718. done
  1719. return 0
  1720. }
  1721. host_resource_get() {
  1722. local location="$1" cfg="$2"
  1723. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1724. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1725. return 1
  1726. }
  1727. if fn.exists host_resource_get_$type; then
  1728. host_resource_get_$type "$location" "$cfg"
  1729. else
  1730. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1731. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1732. "$DARKYELLOW$subservice$NORMAL config."
  1733. return 1
  1734. fi
  1735. }
  1736. export -f host_resource_get
  1737. host_resource_get_git() {
  1738. local location="$1" cfg="$2" branch parent url
  1739. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1740. branch=${branch:-master}
  1741. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1742. parent="$(dirname "$location")"
  1743. (
  1744. mkdir -p "$parent" && cd "$parent" &&
  1745. git clone -b "$branch" "$url" "$(basename "$location")"
  1746. ) || return 1
  1747. }
  1748. export -f host_resource_get_git
  1749. host_resource_get_git-sub() {
  1750. local location="$1" cfg="$2" branch parent url
  1751. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1752. branch=${branch:-master}
  1753. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1754. parent="$(dirname "$location")"
  1755. (
  1756. mkdir -p "$parent" && cd "$parent" &&
  1757. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1758. ) || return 1
  1759. }
  1760. export -f host_resource_get_git-sub
  1761. setup_host_resource () {
  1762. local subservice="$1" service_def location get cfg
  1763. service_def=$(get_compose_service_def "$subservice") || return 1
  1764. while read-0 location cfg; do
  1765. ## XXXvlab: will it be a git resources always ?
  1766. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1767. err "Hum, location '$location' does not seem to be a git directory."
  1768. return 1
  1769. fi
  1770. if [ -d "$location" ]; then
  1771. info "host resource '$location' already set up."
  1772. continue
  1773. fi
  1774. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1775. if [ -z "$get" ]; then
  1776. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1777. "specified for $DARKYELLOW$subservice$NORMAL."
  1778. return 1
  1779. fi
  1780. host_resource_get "$location" "$get" || return 1
  1781. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1782. }
  1783. export -f setup_host_resource
  1784. setup_host_resources () {
  1785. local service subservices subservice loaded
  1786. declare -A loaded
  1787. for service in "$@"; do
  1788. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1789. for subservice in $subservices; do
  1790. if [ "${loaded[$subservice]}" ]; then
  1791. ## Prevent double inclusion of same service if this
  1792. ## service is deps of two or more of your
  1793. ## requirements.
  1794. continue
  1795. fi
  1796. setup_host_resource "$subservice" || return 1
  1797. loaded[$subservice]=1
  1798. done
  1799. done
  1800. return 0
  1801. }
  1802. export -f setup_host_resources
  1803. ## Works on stdin
  1804. cfg-get-value () {
  1805. local key="$1" out
  1806. if [ -z "$key" ]; then
  1807. yaml_get_interpret || return 1
  1808. return 0
  1809. fi
  1810. if ! out=$(shyaml -y get-value "$key" 2>/dev/null); then
  1811. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1812. return 1
  1813. fi
  1814. printf "%s\n" "$out" | yaml_get_interpret
  1815. }
  1816. export -f cfg-get-value
  1817. relation-get () {
  1818. if [ -z "$RELATION_DATA_FILE" ]; then
  1819. err-d "$FUNCNAME: var \$RELATION_DATA_FILE is not set."
  1820. return 1
  1821. fi
  1822. cfg-get-value "$1" < "$RELATION_DATA_FILE"
  1823. }
  1824. export -f relation-get
  1825. expand_vars() {
  1826. local unlikely_prefix="UNLIKELY_PREFIX"
  1827. content=$(cat -)
  1828. ## find first identifier not in content
  1829. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1830. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1831. size_prefix="${#unlikely_prefix}"
  1832. first_matching=$(echo "$remaining_lines" |
  1833. grep -v "^$unlikely_prefix$" |
  1834. uniq -w "$((size_prefix + 1))" -c |
  1835. sort -rn |
  1836. head -n 1)
  1837. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1838. first_matching="${first_matching#* }"
  1839. next_char=${first_matching:$size_prefix:1}
  1840. if [ "$next_char" != "0" ]; then
  1841. unlikely_prefix+="0"
  1842. else
  1843. unlikely_prefix+="1"
  1844. fi
  1845. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1846. done
  1847. eval "cat <<$unlikely_prefix
  1848. $content
  1849. $unlikely_prefix"
  1850. }
  1851. export -f expand_vars
  1852. yaml_get_interpret() {
  1853. local content tag
  1854. content=$(cat -)
  1855. tag=$(echo "$content" | shyaml get-type) || return 1
  1856. content=$(echo "$content" | shyaml get-value) || return 1
  1857. if ! [ "${tag:0:1}" == "!" ]; then
  1858. echo "$content" || return 1
  1859. return 0
  1860. fi
  1861. case "$tag" in
  1862. "!bash-stdout")
  1863. echo "$content" | bash || {
  1864. err "shell code didn't end with errorlevel 0"
  1865. return 1
  1866. }
  1867. ;;
  1868. "!var-expand")
  1869. echo "$content" | expand_vars || {
  1870. err "shell expansion failed"
  1871. return 1
  1872. }
  1873. ;;
  1874. "!file-content")
  1875. source=$(echo "$content" | expand_vars) || {
  1876. err "shell expansion failed"
  1877. return 1
  1878. }
  1879. cat "$source" || return 1
  1880. ;;
  1881. *)
  1882. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1883. return 1
  1884. ;;
  1885. esac
  1886. }
  1887. export -f yaml_get_interpret
  1888. options-get () {
  1889. local key="$1" out
  1890. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1891. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1892. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1893. return 1
  1894. fi
  1895. echo "$out" | yaml_get_interpret
  1896. }
  1897. export -f options-get
  1898. relation-base-compose-get () {
  1899. local key="$1" out
  1900. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1901. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1902. return 1
  1903. fi
  1904. echo "$out" | yaml_get_interpret
  1905. }
  1906. export -f relation-base-compose-get
  1907. relation-target-compose-get () {
  1908. local key="$1" out
  1909. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1910. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1911. return 1
  1912. fi
  1913. echo "$out" | yaml_get_interpret
  1914. }
  1915. export -f relation-target-compose-get
  1916. relation-set () {
  1917. local key="$1" value="$2"
  1918. if [ -z "$RELATION_DATA_FILE" ]; then
  1919. err "$FUNCNAME: relation does not seems to be correctly setup."
  1920. return 1
  1921. fi
  1922. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1923. err "$FUNCNAME: can't read relation's data." >&2
  1924. return 1
  1925. fi
  1926. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1927. }
  1928. export -f relation-set
  1929. _config_merge() {
  1930. local config_filename="$1" mixin="$2"
  1931. touch "$config_filename" &&
  1932. merge_yaml "$config_filename" "$mixin" > "$config_filename.tmp" || return 1
  1933. mv "$config_filename.tmp" "$config_filename"
  1934. }
  1935. export -f _config_merge
  1936. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1937. config-add() {
  1938. local metadata="$1"
  1939. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1940. }
  1941. export -f config-add
  1942. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1943. init-config-add() {
  1944. local metadata="$1"
  1945. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1946. <(yaml_key_val_str "services" "$metadata")
  1947. }
  1948. export -f init-config-add
  1949. docker_get_uid() {
  1950. local service="$1" user="$2" uid
  1951. uid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"") || {
  1952. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1953. return 1
  1954. }
  1955. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid'"
  1956. echo "$uid"
  1957. }
  1958. export -f docker_get_uid
  1959. docker_get_uid_gid() {
  1960. local service="$1" user="$2" group="$3" uid
  1961. uid_gid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"; id -g \"$group\"") || {
  1962. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1963. return 1
  1964. }
  1965. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid_gid'"
  1966. echo "$uid_gid"
  1967. }
  1968. export -f docker_get_uid_gid
  1969. logstdout() {
  1970. local name="$1"
  1971. sed -r 's%^%'"${name}"'> %g'
  1972. }
  1973. export -f logstdout
  1974. logstderr() {
  1975. local name="$1"
  1976. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1977. }
  1978. export -f logstderr
  1979. _run_service_relation () {
  1980. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1981. local errlvl
  1982. charm=$(get_service_charm "$service") || return 1
  1983. target_charm=$(get_service_charm "$target_service") || return 1
  1984. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1985. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1986. [ -n "$base_script_name" ] || [ -n "$target_script_name" ] || return 0
  1987. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1988. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1989. export BASE_SERVICE_NAME=$service
  1990. export BASE_CHARM_NAME=$charm
  1991. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1992. export TARGET_SERVICE_NAME=$target_service
  1993. export TARGET_CHARM_NAME=$target_charm
  1994. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1995. export RELATION_DATA_FILE
  1996. target_errlvl=0
  1997. if [ -z "$target_script_name" ]; then
  1998. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1999. else
  2000. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  2001. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  2002. RELATION_CONFIG="$relation_dir/config_provider"
  2003. type=$(get_service_type "$target_service") || return 1
  2004. if [ "$type" != "stub" ]; then
  2005. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$target_service") || return 1
  2006. fi
  2007. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  2008. {
  2009. (
  2010. SERVICE_NAME=$target_service
  2011. SERVICE_DATASTORE="$DATASTORE/$target_service"
  2012. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  2013. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  2014. charm.run_relation_hook local "$target_charm" "$relation_name" relation-joined
  2015. echo "$?" > "$relation_dir/target_errlvl"
  2016. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  2017. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  2018. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  2019. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  2020. "failed before outputing an errorlevel."
  2021. ((target_errlvl |= "1" ))
  2022. }
  2023. if [ -e "$RELATION_CONFIG" ]; then
  2024. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  2025. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  2026. rm "$RELATION_CONFIG"
  2027. ((target_errlvl |= "$?"))
  2028. fi
  2029. fi
  2030. if [ "$target_errlvl" == 0 ]; then
  2031. errlvl=0
  2032. if [ "$base_script_name" ]; then
  2033. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  2034. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  2035. RELATION_CONFIG="$relation_dir/config_providee"
  2036. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  2037. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$service") || return 1
  2038. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  2039. {
  2040. (
  2041. SERVICE_NAME=$service
  2042. SERVICE_DATASTORE="$DATASTORE/$service"
  2043. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2044. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  2045. charm.run_relation_hook local "$charm" "$relation_name" relation-joined
  2046. echo "$?" > "$relation_dir/errlvl"
  2047. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  2048. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2049. errlvl="$(cat "$relation_dir/errlvl")" || {
  2050. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  2051. "failed before outputing an errorlevel."
  2052. ((errlvl |= "1" ))
  2053. }
  2054. if [ -e "$RELATION_CONFIG" ]; then
  2055. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  2056. rm "$RELATION_CONFIG"
  2057. ((errlvl |= "$?" ))
  2058. fi
  2059. if [ "$errlvl" != 0 ]; then
  2060. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  2061. fi
  2062. else
  2063. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  2064. fi
  2065. else
  2066. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  2067. fi
  2068. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  2069. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  2070. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  2071. return 0
  2072. else
  2073. return 1
  2074. fi
  2075. }
  2076. export -f _run_service_relation
  2077. _get_compose_relations_cached () {
  2078. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2079. relation_name relation_def target_service
  2080. if [ -e "$cache_file" ]; then
  2081. #debug "$FUNCNAME: STATIC cache hit $1"
  2082. cat "$cache_file" &&
  2083. touch "$cache_file" || return 1
  2084. return 0
  2085. fi
  2086. (
  2087. set -o pipefail
  2088. if [ "$compose_service_def" ]; then
  2089. while read-0 relation_name relation_def; do
  2090. ## XXXvlab: could we use braces here instead of parenthesis ?
  2091. (
  2092. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  2093. "str")
  2094. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  2095. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2096. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  2097. ;;
  2098. "sequence")
  2099. while read-0 target_service; do
  2100. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2101. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  2102. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  2103. ;;
  2104. "struct")
  2105. while read-0 target_service relation_config; do
  2106. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  2107. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  2108. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  2109. ;;
  2110. esac
  2111. ) </dev/null >> "$cache_file" || return 1
  2112. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  2113. fi
  2114. )
  2115. if [ "$?" != 0 ]; then
  2116. err "Error while looking for compose relations."
  2117. rm -f "$cache_file" ## no cache
  2118. return 1
  2119. fi
  2120. [ -e "$cache_file" ] && cat "$cache_file"
  2121. return 0
  2122. }
  2123. export -f _get_compose_relations_cached
  2124. get_compose_relations () {
  2125. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2126. compose_def
  2127. if [ -e "$cache_file" ]; then
  2128. #debug "$FUNCNAME: SESSION cache hit $1"
  2129. cat "$cache_file"
  2130. return 0
  2131. fi
  2132. compose_def="$(get_compose_service_def "$service")" || return 1
  2133. _get_compose_relations_cached "$compose_def" > "$cache_file"
  2134. if [ "$?" != 0 ]; then
  2135. rm -f "$cache_file" ## no cache
  2136. return 1
  2137. fi
  2138. cat "$cache_file"
  2139. }
  2140. export -f get_compose_relations
  2141. get_all_services() {
  2142. local services compose_yml_services service
  2143. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2144. err-d "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2145. return 1
  2146. fi
  2147. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$GLOBAL_ALL_RELATIONS_HASH" "$(declare -f "$FUNCNAME")")" \
  2148. s rn ts rc td services service
  2149. if [ -e "$cache_file" ]; then
  2150. #debug "$FUNCNAME: cache hit $1"
  2151. cat "$cache_file"
  2152. return 0
  2153. fi
  2154. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2155. err-d "Can't access global \$GLOBAL_ALL_RELATIONS"
  2156. return 1
  2157. fi
  2158. declare -A services
  2159. while read-0 s _ ts _ _; do
  2160. for service in "$s" "$ts"; do
  2161. [ "${services[$service]}" ] && continue
  2162. services["$service"]=1
  2163. echo "$service"
  2164. done
  2165. done < "$GLOBAL_ALL_RELATIONS" > "$cache_file.wip"
  2166. compose_yml_services=($(compose:yml:root:services)) || return 1
  2167. for service in "${compose_yml_services[@]}"; do
  2168. [ "${services[$service]}" ] && continue
  2169. services["$service"]=1
  2170. echo "$service"
  2171. done >> "$cache_file.wip"
  2172. mv "$cache_file"{.wip,} || return 1
  2173. cat "$cache_file"
  2174. }
  2175. export -f get_all_services
  2176. get_service_relations () {
  2177. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH")" \
  2178. s rn ts rc td
  2179. if [ -e "$cache_file" ]; then
  2180. #debug "$FUNCNAME: SESSION cache hit $1"
  2181. cat "$cache_file"
  2182. return 0
  2183. fi
  2184. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2185. err-d "Can't access global \$GLOBAL_ALL_RELATIONS"
  2186. return 1
  2187. fi
  2188. while read-0 s rn ts rc td; do
  2189. [[ "$s" == "$service" ]] || continue
  2190. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  2191. done < <(cat "$GLOBAL_ALL_RELATIONS") > "$cache_file"
  2192. cat "$cache_file"
  2193. }
  2194. export -f get_service_relations
  2195. get_service_relation() {
  2196. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  2197. rn ts rc td
  2198. if [ -e "$cache_file" ]; then
  2199. #debug "$FUNCNAME: SESSION cache hit $1"
  2200. cat "$cache_file"
  2201. return 0
  2202. fi
  2203. while read-0-err E rn ts rc td; do
  2204. [ "$relation" == "$rn" ] && {
  2205. printf "%s\0" "$ts" "$rc" "$td"
  2206. break
  2207. }
  2208. done < <(p-err get_service_relations "$service") > "${cache_file}.wip"
  2209. if [ "$?" != 0 ]; then
  2210. return 1
  2211. fi
  2212. if [ "$E" != 0 ]; then
  2213. return 1
  2214. fi
  2215. mv "${cache_file}"{.wip,} || return 1
  2216. cat "$cache_file"
  2217. }
  2218. export -f get_service_relation
  2219. ## From a service and a relation, get all relations targeting given
  2220. ## service with given relation.
  2221. ##
  2222. ## Returns a NUL separated list of couple of:
  2223. ## (base_service, relation_config)
  2224. ##
  2225. get_service_incoming_relations() {
  2226. if [ -z "$SUBSET_ALL_RELATIONS_HASH" ]; then
  2227. err-d "Expected \$SUBSET_ALL_RELATIONS_HASH to be set."
  2228. return 1
  2229. fi
  2230. local service="$1" relation="$2" \
  2231. cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$SUBSET_ALL_RELATIONS_HASH")" \
  2232. s rn ts rc td
  2233. if [ -e "$cache_file" ]; then
  2234. #debug "$FUNCNAME: SESSION cache hit $1"
  2235. cat "$cache_file"
  2236. return 0
  2237. fi
  2238. while read-0 s rn ts rc _td; do
  2239. [[ "$ts" == "$service" ]] || continue
  2240. [[ "$rn" == "$relation" ]] || continue
  2241. relation_data_file=$(get_relation_data_file "$s" "$ts" "$rn" "$rc") || return 1
  2242. printf "%s\0" "$s" "$(cat "$relation_data_file")" || return 1
  2243. debug "Found relation $rn from $s to $ts" >&2
  2244. done < "$SUBSET_ALL_RELATIONS" > "$cache_file.wip"
  2245. mv "$cache_file"{.wip,} || return 1
  2246. cat "$cache_file"
  2247. }
  2248. export -f get_service_incoming_relations
  2249. export TRAVERSE_SEPARATOR=:
  2250. ## Traverse on first service satisfying relation
  2251. service:traverse() {
  2252. local service_path="$1"
  2253. {
  2254. SEPARATOR=:
  2255. read -d "$TRAVERSE_SEPARATOR" service
  2256. while read -d "$TRAVERSE_SEPARATOR" relation; do
  2257. ## XXXvlab: Take only first service
  2258. if ! read-0 ts _ _ < <(get_service_relation "${service}" "${relation}"); then
  2259. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2260. "from ${DARKYELLOW}$service${NORMAL}."
  2261. return 1
  2262. fi
  2263. service="$ts"
  2264. done
  2265. echo "$service"
  2266. } < <(e "${service_path}${TRAVERSE_SEPARATOR}")
  2267. }
  2268. export -f service:traverse
  2269. service:relation-file() {
  2270. local service_path="$1" relation service relation_file
  2271. if ! [[ "$service_path" == *"$TRAVERSE_SEPARATOR"* ]]; then
  2272. err "Invalid argument '$service_path'." \
  2273. "Must provide a service path (no '${TRAVERSE_SEPARATOR}' found)."
  2274. return 1
  2275. fi
  2276. relation="${service_path##*${TRAVERSE_SEPARATOR}}"
  2277. service=$(service:traverse "${service_path%${TRAVERSE_SEPARATOR}*}") || return 1
  2278. if ! read-0 ts rc _ < <(get_service_relation "${service}" "${relation}"); then
  2279. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2280. "from ${DARKYELLOW}$service${NORMAL}."
  2281. return 1
  2282. fi
  2283. relation_dir=$(get_relation_data_dir "$service" "$ts" "$relation") || {
  2284. err "Failed to find relation file"
  2285. return 1
  2286. }
  2287. relation_file="$relation_dir/data"
  2288. if ! [ -e "$relation_file" ]; then
  2289. e "$rc" > "$relation_file"
  2290. chmod go-rwx "$relation_file" ## protecting this file
  2291. fi
  2292. echo "$relation_file"
  2293. }
  2294. export -f service:relation-file
  2295. service:relation-options() {
  2296. local service_path="$1" relation_file
  2297. relation_file=$(service:relation-file "$service_path") || {
  2298. err "Failed to find relation file"
  2299. return 1
  2300. }
  2301. cat "$relation_file"
  2302. }
  2303. export -f service:relation-options
  2304. relation:get() {
  2305. local service_path="$1" query="$2" relation_file
  2306. relation_file=$(service:relation-file "$service_path") || {
  2307. err "Failed to find relation file"
  2308. return 1
  2309. }
  2310. cfg-get-value "$query" < "$relation_file"
  2311. }
  2312. export -f relation:get
  2313. services:get:upable() {
  2314. if [ -z "$CHARM_STORE_HASH" ]; then
  2315. err-d "Expected \$CHARM_STORE_HASH to be set."
  2316. return 1
  2317. fi
  2318. local services_args=("$@") cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$CHARM_STORE_HASH" "$@")"
  2319. if [ -e "$cache_file" ]; then
  2320. touch "$cache_file" || return 1
  2321. cat "$cache_file"
  2322. return 0
  2323. fi
  2324. declare -A seen
  2325. services=($(get_ordered_service_dependencies "${services_args[@]}")) || exit 1
  2326. for service in "${services[@]}"; do
  2327. mservice=$(get_master_service_for_service "$service") || exit 1
  2328. [ "${seen[$mservice]}" ] && continue
  2329. type="$(get_service_type "$mservice")" || exit 1
  2330. ## remove run-once
  2331. [ "$type" == "run-once" ] && continue
  2332. [ "$type" == "stub" ] && continue
  2333. seen[$mservice]=1
  2334. echo "$mservice"
  2335. done > "$cache_file".wip
  2336. mv "$cache_file".wip "$cache_file"
  2337. cat "$cache_file"
  2338. }
  2339. export -f services:get:upable
  2340. service:state() {
  2341. local service="$1" states state
  2342. project_name=$(get_default_project_name) || return 1
  2343. states=()
  2344. for state in "$SERVICE_STATE_PATH"/"$project_name"/"$service"/*; do
  2345. [ -e "$state" ] || continue
  2346. state=${state##*/}
  2347. states+=("$state")
  2348. done
  2349. if [[ " ${states[*]} " == *" deploying "* ]]; then
  2350. echo "deploying"
  2351. elif [[ " ${states[*]} " == *" up "* ]]; then
  2352. echo "up"
  2353. else
  2354. echo "down"
  2355. fi
  2356. }
  2357. export -f service:state
  2358. _get_charm_metadata_uses() {
  2359. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2360. if [ -e "$cache_file" ]; then
  2361. #debug "$FUNCNAME: SESSION cache hit $1"
  2362. cat "$cache_file" || return 1
  2363. return 0
  2364. fi
  2365. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  2366. }
  2367. export -f _get_charm_metadata_uses
  2368. _get_service_metadata() {
  2369. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2370. charm
  2371. if [ -e "$cache_file" ]; then
  2372. #debug "$FUNCNAME: SESSION cache hit $1"
  2373. cat "$cache_file"
  2374. return 0
  2375. fi
  2376. charm="$(get_service_charm "$service")" || return 1
  2377. charm.metadata "$charm" > "$cache_file"
  2378. if [ "$?" != 0 ]; then
  2379. rm -f "$cache_file" ## no cache
  2380. return 1
  2381. fi
  2382. cat "$cache_file"
  2383. }
  2384. export -f _get_service_metadata
  2385. _get_service_uses() {
  2386. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2387. metadata
  2388. if [ -e "$cache_file" ]; then
  2389. #debug "$FUNCNAME: SESSION cache hit $1"
  2390. cat "$cache_file"
  2391. return 0
  2392. fi
  2393. metadata="$(_get_service_metadata "$service")" || return 1
  2394. _get_charm_metadata_uses "$metadata" > "$cache_file"
  2395. if [ "$?" != 0 ]; then
  2396. rm -f "$cache_file" ## no cache
  2397. return 1
  2398. fi
  2399. cat "$cache_file"
  2400. }
  2401. export -f _get_service_uses
  2402. _get_services_uses() {
  2403. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2404. service rn rd
  2405. if [ -e "$cache_file" ]; then
  2406. #debug "$FUNCNAME: SESSION cache hit $1"
  2407. cat "$cache_file"
  2408. return 0
  2409. fi
  2410. for service in "$@"; do
  2411. _get_service_uses "$service" | while read-0 rn rd; do
  2412. printf "%s\0" "$service" "$rn" "$rd"
  2413. done
  2414. [ "${PIPESTATUS[0]}" == 0 ] || {
  2415. return 1
  2416. }
  2417. done > "${cache_file}.wip"
  2418. mv "${cache_file}"{.wip,} &&
  2419. cat "$cache_file" || return 1
  2420. }
  2421. export -f _get_services_uses
  2422. _get_provides_provides() {
  2423. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2424. service rn rd
  2425. if [ -e "$cache_file" ]; then
  2426. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  2427. cat "$cache_file"
  2428. return 0
  2429. fi
  2430. type=$(printf "%s" "$provides" | shyaml get-type)
  2431. case "$type" in
  2432. sequence)
  2433. while read-0 prov; do
  2434. printf "%s\0" "$prov" ""
  2435. done < <(echo "$provides" | shyaml get-values-0)
  2436. ;;
  2437. struct)
  2438. printf "%s" "$provides" | shyaml key-values-0
  2439. ;;
  2440. str)
  2441. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  2442. ;;
  2443. *)
  2444. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  2445. return 1
  2446. esac | tee "$cache_file"
  2447. return "${PIPESTATUS[0]}"
  2448. }
  2449. _get_metadata_provides() {
  2450. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2451. service rn rd
  2452. if [ -e "$cache_file" ]; then
  2453. #debug "$FUNCNAME: CACHEDIR cache hit"
  2454. cat "$cache_file"
  2455. return 0
  2456. fi
  2457. provides=$(printf "%s" "$metadata" | shyaml -q get-value -y provides "")
  2458. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  2459. _get_provides_provides "$provides" | tee "$cache_file"
  2460. return "${PIPESTATUS[0]}"
  2461. }
  2462. _get_services_provides() {
  2463. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2464. service rn rd
  2465. if [ -e "$cache_file" ]; then
  2466. #debug "$FUNCNAME: SESSION cache hit $1"
  2467. cat "$cache_file"
  2468. return 0
  2469. fi
  2470. ## YYY: replace the inner loop by a cached function
  2471. for service in "$@"; do
  2472. metadata="$(_get_service_metadata "$service")" || return 1
  2473. while read-0 rn rd; do
  2474. printf "%s\0" "$service" "$rn" "$rd"
  2475. done < <(_get_metadata_provides "$metadata")
  2476. done > "$cache_file"
  2477. if [ "$?" != 0 ]; then
  2478. rm -f "$cache_file" ## no cache
  2479. return 1
  2480. fi
  2481. cat "$cache_file"
  2482. }
  2483. export -f _get_services_provides
  2484. _get_charm_provides() {
  2485. if [ -z "$CHARM_STORE_HASH" ]; then
  2486. err-d "Expected \$CHARM_STORE_HASH to be set."
  2487. return 1
  2488. fi
  2489. local cache_file="$CACHEDIR/$FUNCNAME.cache.$CHARM_STORE_HASH" errlvl
  2490. if [ -e "$cache_file" ]; then
  2491. #debug "$FUNCNAME: SESSION cache hit"
  2492. cat "$cache_file"
  2493. return 0
  2494. fi
  2495. start="$SECONDS"
  2496. debug "Getting charm provider list..."
  2497. while read-0 charm _ realpath metadata; do
  2498. metadata="$(charm.metadata "$charm")" || continue
  2499. # echo "reading $charm" >&2
  2500. while read-0 rn rd; do
  2501. printf "%s\0" "$charm" "$rn" "$rd"
  2502. done < <(_get_metadata_provides "$metadata")
  2503. done < <(charm.ls) | tee "$cache_file"
  2504. errlvl="${PIPESTATUS[0]}"
  2505. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  2506. return "$errlvl"
  2507. }
  2508. _get_charm_providing() {
  2509. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2510. relation="$1"
  2511. if [ -e "$cache_file" ]; then
  2512. #debug "$FUNCNAME: SESSION cache hit $1"
  2513. cat "$cache_file"
  2514. return 0
  2515. fi
  2516. while read-0 charm relation_name relation_def; do
  2517. [ "$relation_name" == "$relation" ] || continue
  2518. printf "%s\0" "$charm" "$relation_def"
  2519. done < <(_get_charm_provides) > "$cache_file"
  2520. if [ "$?" != 0 ]; then
  2521. rm -f "$cache_file" ## no cache
  2522. return 1
  2523. fi
  2524. cat "$cache_file"
  2525. }
  2526. _get_services_providing() {
  2527. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2528. relation="$1"
  2529. shift ## services is "$@"
  2530. if [ -e "$cache_file" ]; then
  2531. #debug "$FUNCNAME: SESSION cache hit $1"
  2532. cat "$cache_file"
  2533. return 0
  2534. fi
  2535. while read-0 service relation_name relation_def; do
  2536. [ "$relation_name" == "$relation" ] || continue
  2537. printf "%s\0" "$service" "$relation_def"
  2538. done < <(_get_services_provides "$@") > "$cache_file"
  2539. if [ "$?" != 0 ]; then
  2540. rm -f "$cache_file" ## no cache
  2541. return 1
  2542. fi
  2543. cat "$cache_file"
  2544. }
  2545. export -f _get_services_provides
  2546. _out_new_relation_from_defs() {
  2547. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  2548. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2549. ## YYYvlab: should be seen even in no debug mode no ?
  2550. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2551. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  2552. td=${td:-True}
  2553. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  2554. after=$(_out_after_value_from_def "$service" "$rn" "$rel_def") || return 1
  2555. printf "%s\0" "$after" "$service" "$relation_name" "$ts" "$rc" "$td"
  2556. }
  2557. _out_after_value_from_def() {
  2558. local service="$1" relation_name="$2" relation_def="$3" after_t after
  2559. if after_t=$(echo "$relation_def" | shyaml get-type after 2>/dev/null); then
  2560. case "$after_t" in
  2561. sequence)
  2562. after="$(echo "$relation_def" | shyaml get-values after 2>/dev/null)" || return 1
  2563. after=",$service:${after//$'\n'/,$service:},"
  2564. ;;
  2565. struct)
  2566. err "Invalid type for ${WHITE}after${NORMAL}'s value in ${DARKBLUE}$relation_name${NORMAL}'s definition."
  2567. return 1
  2568. ;;
  2569. str)
  2570. after=",$service:$(echo "$relation_def" | shyaml get-value after "" 2>/dev/null)," || return 1
  2571. ;;
  2572. esac
  2573. else
  2574. after=""
  2575. fi
  2576. e "$after"
  2577. }
  2578. get_all_compose_yml_service() {
  2579. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2580. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2581. err "Failed to get compose yml hash"
  2582. return 1
  2583. }
  2584. fi
  2585. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2586. if [ -e "${cache_file}" ]; then
  2587. #debug "$FUNCNAME: cache hit: ${cache_file}"
  2588. cat "${cache_file}"
  2589. return 0
  2590. fi
  2591. compose_yml_content=$(get_compose_yml_content) || return 1
  2592. printf "%s" "${compose_yml_content}" | shyaml keys-0 2>/dev/null > "${cache_file}.wip" || {
  2593. err "Failed to get keys of compose content."
  2594. return 1
  2595. }
  2596. mv "${cache_file}"{.wip,} || return 1
  2597. cat "${cache_file}"
  2598. }
  2599. ## Outputs all relations array.
  2600. _service:all:relations_cached() {
  2601. local services service E
  2602. services=($(compose:yml:root:services)) || return 1
  2603. get_all_relations "${services[@]}" || return 1
  2604. }
  2605. ## Outputs all relations array.
  2606. service:all:relations() {
  2607. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2608. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2609. err "Failed to get compose yml hash."
  2610. return 1
  2611. }
  2612. fi
  2613. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2614. if [ -e "${cache_file}" ]; then
  2615. # debug "$FUNCNAME: SESSION cache hit $1"
  2616. cat "${cache_file}"
  2617. return 0
  2618. fi
  2619. _service:all:relations_cached > "${cache_file}.wip" || {
  2620. err-d "Failed to compute all relations."
  2621. return 1
  2622. }
  2623. mv "${cache_file}"{.wip,} || return 1
  2624. cat "${cache_file}"
  2625. }
  2626. _service:all:relations_hash_cached() {
  2627. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2628. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || {
  2629. err "Failed to get compose yml hash."
  2630. return 1
  2631. }
  2632. fi
  2633. local cache_file="$CACHEDIR/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH" \
  2634. hash
  2635. if [ -e "${cache_file}" ]; then
  2636. # debug "$FUNCNAME: SESSION cache hit $1"
  2637. cat "${cache_file}"
  2638. return 0
  2639. fi
  2640. service:all:relations > "${cache_file}.pre" || {
  2641. err-d "Failed to get all relations."
  2642. return 1
  2643. }
  2644. {
  2645. p0 "$(hash_get < "${cache_file}.pre")" || return 1
  2646. cat "${cache_file}.pre"
  2647. rm "${cache_file}.pre"
  2648. } > "${cache_file}".wip || return 1
  2649. mv "${cache_file}"{.wip,} || return 1
  2650. cat "${cache_file}"
  2651. }
  2652. ## Get all relations from all services in the current compose file.
  2653. ## Sets GLOBAL_ALL_RELATIONS_HASH and returns all relations array.
  2654. service:all:set_relations_hash() {
  2655. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2656. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2657. err "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2658. echo " (despite \$GLOBAL_ALL_RELATIONS being set)" >&2
  2659. return 1
  2660. fi
  2661. return 0
  2662. fi
  2663. ## sets COMPOSE_YML_CONTENT_HASH
  2664. _service:all:relations_hash_cached >/dev/null || return 1
  2665. {
  2666. read-0 GLOBAL_ALL_RELATIONS_HASH || return 1
  2667. export GLOBAL_ALL_RELATIONS_HASH
  2668. ## transfer to statedir
  2669. export GLOBAL_ALL_RELATIONS="$state_tmpdir/$FUNCNAME.cache.$COMPOSE_YML_CONTENT_HASH"
  2670. cat > "$GLOBAL_ALL_RELATIONS"
  2671. } < <(_service:all:relations_hash_cached)
  2672. if [ -z "$GLOBAL_ALL_RELATIONS" ]; then
  2673. err "Failed to set \$GLOBAL_ALL_RELATIONS."
  2674. return 1
  2675. fi
  2676. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2677. err "Failed to set \$GLOBAL_ALL_RELATIONS_HASH."
  2678. return 1
  2679. fi
  2680. }
  2681. get_subset_relations () {
  2682. local service all_services services start
  2683. if [ -n "$SUBSET_ALL_RELATIONS" ]; then
  2684. return 0
  2685. fi
  2686. if [ -z "$GLOBAL_ALL_RELATIONS_HASH" ]; then
  2687. err-d "Can't access global \$GLOBAL_ALL_RELATIONS_HASH"
  2688. return 1
  2689. fi
  2690. cache_hash=$(H "$@" "$GLOBAL_ALL_RELATIONS_HASH" "$(declare -f "$FUNCNAME")")
  2691. local cache_file="$CACHEDIR/$FUNCNAME.cache.$cache_hash"
  2692. if [ -e "${cache_file}" ]; then
  2693. export SUBSET_ALL_RELATIONS="$cache_file"
  2694. hash=$(hash_get < "$cache_file") || return 1
  2695. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2696. cat "${cache_file}"
  2697. return 0
  2698. fi
  2699. ## collect all connected services first
  2700. all_services=("$@")
  2701. declare -A services
  2702. while [ "${#all_services[@]}" != 0 ]; do
  2703. array_pop all_services service
  2704. # debug " Getting relations for $DARKYELLOW$service$NORMAL"
  2705. while read-0 s rn ts rc td; do
  2706. [[ "$s" == "$service" ]] || continue
  2707. # debug " adding relation $DARKBLUE$rn$NORMAL to $DARKYELLOW$ts$NORMAL"
  2708. p0 "$service" "$rn" "$ts" "$rc" "$td"
  2709. if [ -z "${services[$ts]}" ] && [[ " ${all_services[@]} " != *" $ts "* ]]; then
  2710. all_services+=("$ts")
  2711. fi
  2712. done < "$GLOBAL_ALL_RELATIONS"
  2713. services["$service"]=1
  2714. done > "$cache_file.wip"
  2715. mv "$cache_file"{.wip,} || return 1
  2716. export SUBSET_ALL_RELATIONS="$cache_file"
  2717. hash=$(hash_get < "$cache_file") || return 1
  2718. export SUBSET_ALL_RELATIONS_HASH="$hash"
  2719. cat "$cache_file"
  2720. }
  2721. export -f get_subset_relations
  2722. get_all_relations () {
  2723. if [ -z "$COMPOSE_YML_CONTENT_HASH" ]; then
  2724. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || return 1
  2725. fi
  2726. if [ -n "$GLOBAL_ALL_RELATIONS" ]; then
  2727. cat "$GLOBAL_ALL_RELATIONS" || return 1
  2728. return 0
  2729. fi
  2730. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$COMPOSE_YML_CONTENT_HASH" "$(declare -p without_relations)")" \
  2731. services all_services service services_uses services_provides \
  2732. changed summon required recommended optional
  2733. if [ -e "${cache_file}" ]; then
  2734. #debug "$FUNCNAME: SESSION cache hit $1"
  2735. export GLOBAL_ALL_RELATIONS="$cache_file"
  2736. cat "${cache_file}"
  2737. return 0
  2738. fi
  2739. declare -A services
  2740. services_uses=()
  2741. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2742. _get_services_uses "$@" >/dev/null || return 1
  2743. array_read-0 services_uses < <(_get_services_uses "$@")
  2744. services_provides=()
  2745. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2746. _get_services_provides "$@" >/dev/null || return 1
  2747. array_read-0 services_provides < <(_get_services_provides "$@")
  2748. for service in "$@"; do
  2749. services[$service]=1
  2750. done
  2751. all_services=("$@")
  2752. while [ "${#all_services[@]}" != 0 ]; do
  2753. array_pop all_services service
  2754. while read-0-err E relation_name ts relation_config tech_dep; do
  2755. [ "${without_relations[$service:$relation_name]}" ] && {
  2756. debug "Ignoring compose $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> ${DARKYELLOW}$ts$NORMAL"
  2757. continue
  2758. }
  2759. ## First is priority, that can be adjusted in second step
  2760. printf "%s\0" "" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  2761. ## adding target services ?
  2762. [ "${services[$ts]}" ] && continue
  2763. array_read-0 services_uses < <(_get_services_uses "$ts")
  2764. all_services+=("$ts")
  2765. services[$ts]=1
  2766. done < <(p-err get_compose_relations "$service")
  2767. if [ "$E" != 0 ]; then
  2768. err "Failed to get relations for $DARKYELLOW$service$NORMAL."
  2769. return 1
  2770. fi
  2771. done > "${cache_file}.wip"
  2772. while true; do
  2773. changed=
  2774. new_services_uses=()
  2775. summon=()
  2776. required=()
  2777. recommended=()
  2778. optional=()
  2779. while [ "${#services_uses[@]}" != 0 ]; do
  2780. service="${services_uses[0]}"
  2781. relation_name="${services_uses[1]}"
  2782. relation_def="${services_uses[2]}"
  2783. services_uses=("${services_uses[@]:3}")
  2784. [ "${without_relations[$service:$relation_name]}" ] && {
  2785. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2786. continue
  2787. }
  2788. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2789. after=$(_out_after_value_from_def "$service" "$relation_name" "$relation_def") || return 1
  2790. ## is this "use" declaration satisfied ?
  2791. found=
  2792. while read-0 p s rn ts rc td; do
  2793. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  2794. if [ "$default_options" ]; then
  2795. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2796. fi
  2797. found="$ts"
  2798. p="$after"
  2799. fi
  2800. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td"
  2801. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2802. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2803. if [ "$found" ]; then ## this "use" declaration was satisfied
  2804. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation" \
  2805. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2806. continue
  2807. fi
  2808. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2809. auto=${auto:-pair}
  2810. case "$auto" in
  2811. "pair"|"summon")
  2812. service_list=()
  2813. array_read-0 service_list < <(array_keys_to_stdin services)
  2814. providers=()
  2815. providers_def=()
  2816. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2817. if [ "${#providers[@]}" == 1 ]; then
  2818. ts="${providers[0]}"
  2819. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2820. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2821. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2822. "${providers_def[0]}" "$relation_def" \
  2823. >> "${cache_file}.wip" || return 1
  2824. ## Adding service
  2825. [ "${services[$ts]}" ] && continue
  2826. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2827. services[$ts]=1
  2828. changed=1
  2829. continue
  2830. fi
  2831. if [ "${#providers[@]}" -gt 1 ]; then
  2832. msg=""
  2833. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2834. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2835. "(> 1 provider)."
  2836. elif [ "$auto" == "summon" ]; then ## no provider
  2837. summon+=("$service" "$relation_name" "$relation_def")
  2838. fi
  2839. ;;
  2840. null|disable|disabled)
  2841. :
  2842. ;;
  2843. *)
  2844. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2845. return 1
  2846. ;;
  2847. esac
  2848. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2849. constraint=${constraint:-optional}
  2850. case "$constraint" in
  2851. "required")
  2852. required+=("$service" "$relation_name" "$relation_def")
  2853. ;;
  2854. "recommended")
  2855. recommended+=("$service" "$relation_name" "$relation_def")
  2856. ;;
  2857. "optional")
  2858. optional+=("$service" "$relation_name" "$relation_def")
  2859. ;;
  2860. *)
  2861. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2862. return 1
  2863. ;;
  2864. esac
  2865. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2866. done
  2867. services_uses=("${new_services_uses[@]}")
  2868. if [ "$changed" ]; then
  2869. continue
  2870. fi
  2871. ## situation is stable
  2872. if [ "${#summon[@]}" != 0 ]; then
  2873. declare -A summon_requeued=()
  2874. while [ "${#summon[@]}" != 0 ]; do
  2875. service="${summon[0]}"
  2876. relation_name="${summon[1]}"
  2877. relation_def="${summon[2]}"
  2878. summon=("${summon[@]:3}")
  2879. providers=()
  2880. providers_def=()
  2881. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2882. ## select first provider that is not a stub
  2883. new_providers=()
  2884. new_providers_def=()
  2885. while [[ "${#providers[@]}" != 0 ]]; do
  2886. provider="${providers[0]}"
  2887. provider_def="${providers_def[0]}"
  2888. providers=("${providers[@]:1}")
  2889. providers_def=("${providers_def[@]:1}")
  2890. type="$(get_service_type "$provider")" || true
  2891. [ "$type" == "stub" ] && continue
  2892. new_providers+=("$provider")
  2893. new_providers_def+=("$provider_def")
  2894. done
  2895. providers=("${new_providers[@]}")
  2896. providers_def=("${new_providers_def[@]}")
  2897. if [ "${#providers[@]}" == 0 ]; then
  2898. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2899. return 1
  2900. fi
  2901. if [ "${#providers[@]}" -gt 1 ]; then
  2902. ## if there are multiple providers (for instance
  2903. ## sql-database), there are some case where other
  2904. ## services will also summon a more specific
  2905. ## postgres-database, that will solve our
  2906. ## constraint. So we'd rather pass (and requeue)
  2907. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2908. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2909. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2910. "(> 1 provider). Requeuing."
  2911. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2912. summon_requeued["$service/$relation_name"]=1
  2913. continue
  2914. else
  2915. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2916. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2917. "(> 1 provider). Choosing first."
  2918. fi
  2919. fi
  2920. ts="${providers[0]}"
  2921. ## YYYvlab: should be seen even in no debug mode no ?
  2922. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2923. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2924. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2925. "${providers_def[0]}" "$relation_def" \
  2926. >> "${cache_file}.wip" || return 1
  2927. ## Adding service
  2928. [ "${services[$ts]}" ] && continue
  2929. array_read-0 services_uses < <(_get_services_uses "$ts")
  2930. services[$ts]=1
  2931. changed=1
  2932. continue 2
  2933. done
  2934. continue
  2935. fi
  2936. [ "$NO_CONSTRAINT_CHECK" ] && break
  2937. if [ "${#required[@]}" != 0 ]; then
  2938. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2939. err "Required relations not satisfied"
  2940. return 1
  2941. fi
  2942. if [ "${#recommended[@]}" != 0 ]; then
  2943. ## make recommendation
  2944. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2945. fi
  2946. if [ -z "$QUIET" ]; then
  2947. if [ "${#optional[@]}" != 0 ]; then
  2948. ## inform about options
  2949. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2950. fi
  2951. fi
  2952. # if [ "${#required[@]}" != 0 ]; then
  2953. # err "Required relations not satisfied"
  2954. # return 1
  2955. # fi
  2956. if [ "${#recommended[@]}" != 0 ]; then
  2957. warn "Recommended relations not satisfied"
  2958. fi
  2959. break
  2960. done
  2961. if [ "$?" != 0 ]; then
  2962. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2963. return 1
  2964. fi
  2965. ##
  2966. ## Sort relations thanks to uses =metadata.yml= relations.
  2967. ##
  2968. mv "${cache_file}.wip"{,.in} &&
  2969. rm -f "${cache_file}.wip.final" &&
  2970. touch "${cache_file}.wip.final" || {
  2971. err "Unexpected error when mangling cache files."
  2972. return 1
  2973. }
  2974. declare -A relation_done=()
  2975. while true; do
  2976. had_remaining_relation=
  2977. had_new_relation=
  2978. while read-0 p s rn ts rc td; do
  2979. if [ -z "$p" ] || [ "$p" == "," ]; then
  2980. relation_done["$s:$rn"]=1
  2981. # printf " .. %-30s %-30s %-30s\n" "$s" "$ts" "$rn" >&2
  2982. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  2983. had_new_relation=1
  2984. else
  2985. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2986. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2987. had_remaining_relation=1
  2988. fi
  2989. done < "${cache_file}.wip.in"
  2990. [ -z "$had_remaining_relation" ] && break
  2991. mv "${cache_file}.wip."{out,in}
  2992. while read-0 p s rn ts rc td; do
  2993. for rel in "${!relation_done[@]}"; do
  2994. p="${p//,$rel,/,}"
  2995. done
  2996. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2997. if [ -z "$had_new_relation" ]; then
  2998. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  2999. for rel in ${p//,/ }; do
  3000. rel_s=${rel%%:*}
  3001. rel_r=${rel##*:}
  3002. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  3003. done
  3004. else
  3005. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  3006. fi
  3007. done < "${cache_file}.wip.in"
  3008. if [ -z "$had_new_relation" ]; then
  3009. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  3010. return 1
  3011. fi
  3012. mv "${cache_file}.wip."{out,in}
  3013. done
  3014. mv "${cache_file}"{.wip.final,} || return 1
  3015. export GLOBAL_ALL_RELATIONS="$cache_file"
  3016. GLOBAL_ALL_RELATIONS_HASH=$(hash_get < "$cache_file") || return 1
  3017. export GLOBAL_ALL_RELATIONS_HASH
  3018. cat "$cache_file"
  3019. }
  3020. export -f get_all_relations
  3021. _display_solves() {
  3022. local array_name="$1" by_relation msg
  3023. ## inform about options
  3024. msg=""
  3025. declare -A by_relation
  3026. while read-0 service relation_name relation_def; do
  3027. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  3028. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  3029. if [ -z "$solves" ]; then
  3030. continue
  3031. fi
  3032. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  3033. if [ "$auto" == "pair" ]; then
  3034. requirement="add provider in cluster to auto-pair"
  3035. else
  3036. requirement="add explicit relation"
  3037. fi
  3038. while read-0 name def; do
  3039. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  3040. done < <(printf "%s" "$solves" | shyaml key-values-0)
  3041. done < <(array_values_to_stdin "$array_name")
  3042. while read-0 relation_name message; do
  3043. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  3044. "$relation_name" "$message" )"
  3045. done < <(array_kv_to_stdin by_relation)
  3046. if [ "$msg" ]; then
  3047. printf "%s\n" "${msg:1}"
  3048. fi
  3049. }
  3050. get_compose_relation_def() {
  3051. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  3052. while read-0 relation_name target_service relation_config tech_dep; do
  3053. [ "$relation_name" == "$relation" ] || continue
  3054. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  3055. done < <(get_compose_relations "$service") || return 1
  3056. }
  3057. export -f get_compose_relation_def
  3058. run_service_relations () {
  3059. local service services loaded subservices subservice
  3060. PROJECT_NAME=$(get_default_project_name) || return 1
  3061. export PROJECT_NAME
  3062. declare -A loaded
  3063. subservices=$(get_ordered_service_dependencies "$@") || return 1
  3064. for service in $subservices; do
  3065. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  3066. for subservice in $(get_service_deps "$service") "$service"; do
  3067. [ "${loaded[$subservice]}" ] && continue
  3068. export BASE_SERVICE_NAME=$service
  3069. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  3070. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  3071. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  3072. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  3073. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  3074. while read-0 relation_name target_service relation_config tech_dep; do
  3075. [ "${without_relations[$service:$relation_name]}" ] && {
  3076. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  3077. continue
  3078. }
  3079. export relation_config
  3080. export TARGET_SERVICE_NAME=$target_service
  3081. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  3082. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  3083. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  3084. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  3085. Wrap "${wrap_opts[@]}" -d "building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  3086. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  3087. EOF
  3088. done < <(get_service_relations "$subservice") || return 1
  3089. loaded[$subservice]=1
  3090. done
  3091. done
  3092. }
  3093. export -f run_service_relations
  3094. _run_service_action_direct() {
  3095. local service="$1" action="$2" charm _dummy project_name
  3096. shift; shift
  3097. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  3098. if read-0 _dummy || [ "$_dummy" ]; then
  3099. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3100. return 1
  3101. fi
  3102. project_name=$(get_default_project_name) || return 1
  3103. export PROJECT_NAME="$project_name"
  3104. export state_tmpdir
  3105. (
  3106. set +e ## Prevents unwanted leaks from parent shell
  3107. export COMPOSE_CONFIG=$(get_compose_yml_content)
  3108. export METADATA_CONFIG=$(charm.metadata "$charm")
  3109. export SERVICE_NAME=$service
  3110. export ACTION_NAME=$action
  3111. export ACTION_SCRIPT_PATH="$action_script_path"
  3112. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3113. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3114. export SERVICE_DATASTORE="$DATASTORE/$service"
  3115. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3116. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3117. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  3118. ) 0<&6 ## inject general stdin
  3119. }
  3120. export -f _run_service_action_direct
  3121. _run_service_action_relation() {
  3122. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  3123. shift; shift
  3124. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  3125. if read-0 _dummy || [ "$_dummy" ]; then
  3126. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  3127. return 1
  3128. fi
  3129. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  3130. export state_tmpdir
  3131. (
  3132. set +e ## Prevents unwanted leaks from parent shell
  3133. export METADATA_CONFIG=$(charm.metadata "$charm")
  3134. export SERVICE_NAME=$service
  3135. export RELATION_TARGET_SERVICE="$target_service"
  3136. export RELATION_TARGET_CHARM="$target_charm"
  3137. export RELATION_BASE_SERVICE="$service"
  3138. export RELATION_BASE_CHARM="$charm"
  3139. export ACTION_NAME=$action
  3140. export ACTION_SCRIPT_PATH="$action_script_path"
  3141. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  3142. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  3143. export SERVICE_DATASTORE="$DATASTORE/$service"
  3144. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  3145. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  3146. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  3147. ) 0<&6 ## inject general stdin
  3148. }
  3149. export -f _run_service_action_relation
  3150. get_relation_data_dir() {
  3151. local service="$1" target_service="$2" relation_name="$3" \
  3152. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  3153. if [ -e "$cache_file" ]; then
  3154. # debug "$FUNCNAME: cache hit ($*)"
  3155. cat "$cache_file"
  3156. return 0
  3157. fi
  3158. local project relation_dir
  3159. project=${PROJECT_NAME}
  3160. if [ -z "$project" ]; then
  3161. project=$(get_default_project_name) || return 1
  3162. fi
  3163. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  3164. if ! [ -d "$relation_dir" ]; then
  3165. mkdir -p "$relation_dir" || return 1
  3166. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  3167. fi
  3168. echo "$relation_dir" | tee "$cache_file"
  3169. }
  3170. export -f get_relation_data_dir
  3171. get_relation_data_file() {
  3172. local service="$1" target_service="$2" relation_name="$3" relation_config="$4" \
  3173. new new_md5 relation_dir relation_data_file
  3174. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  3175. relation_data_file="$relation_dir/data"
  3176. new=
  3177. if [ -e "$relation_data_file" ]; then
  3178. ## Has reference changed ?
  3179. new_md5=$(e "$relation_config" | md5_compat)
  3180. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  3181. new=true
  3182. fi
  3183. else
  3184. new=true
  3185. fi
  3186. if [ -n "$new" ]; then
  3187. OLDUMASK=$(umask)
  3188. umask 0077
  3189. e "$relation_config" > "$relation_data_file"
  3190. umask "$OLDUMASK"
  3191. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  3192. fi
  3193. echo "$relation_data_file"
  3194. }
  3195. export -f get_relation_data_file
  3196. has_service_action () {
  3197. if [ -z "$CHARM_STORE_HASH" ]; then
  3198. err-d "Can't access global \$CHARM_STORE_HASH"
  3199. return 1
  3200. fi
  3201. local service="$1" action="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$2.$CHARM_STORE_HASH" \
  3202. charm target_charm relation_name target_service relation_config _tech_dep \
  3203. path
  3204. if [ -e "$cache_file" ]; then
  3205. # debug "$FUNCNAME: cache hit ($*)"
  3206. if [ -s "$cache_file" ]; then
  3207. cat "$cache_file"
  3208. return 0
  3209. else
  3210. return 1
  3211. fi
  3212. fi
  3213. charm=$(get_service_charm "$service") || return 1
  3214. ## Action directly provided ?
  3215. if path=$(charm.has_direct_action "$charm" "$action"); then
  3216. p0 "direct" "$charm" "$path" | tee "$cache_file"
  3217. return 0
  3218. fi
  3219. ## Action provided by relation ?
  3220. while read-0 relation_name target_service relation_config _tech_dep; do
  3221. target_charm=$(get_service_charm "$target_service") || return 1
  3222. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  3223. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  3224. return 0
  3225. fi
  3226. done < <(get_service_relations "$service")
  3227. touch "$cache_file"
  3228. return 1
  3229. # master=$(get_top_master_service_for_service "$service")
  3230. # [ "$master" == "$charm" ] && return 1
  3231. # has_service_action "$master" "$action"
  3232. }
  3233. export -f has_service_action
  3234. run_service_action () {
  3235. local service="$1" action="$2" errlvl
  3236. shift ; shift
  3237. exec 6<&0 ## saving stdin
  3238. {
  3239. if ! read-0 action_type; then
  3240. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  3241. info " Add an executable script to 'actions/$action' to implement action."
  3242. return 1
  3243. fi
  3244. "_run_service_action_${action_type}" "$service" "$action" "$@"
  3245. errlvl="$?"
  3246. } < <(has_service_action "$service" "$action")
  3247. exec 0<&6 6<&- ## restoring stdin
  3248. return "$errlvl"
  3249. }
  3250. export -f run_service_action
  3251. get_compose_relation_config() {
  3252. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3253. if [ -e "$cache_file" ]; then
  3254. # debug "$FUNCNAME: cache hit ($*)"
  3255. cat "$cache_file"
  3256. return 0
  3257. fi
  3258. compose_service_def=$(get_compose_service_def "$service") || return 1
  3259. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  3260. }
  3261. export -f get_compose_relation_config
  3262. # ## Return key-values-0
  3263. # get_compose_relation_config_for_service() {
  3264. # local service=$1 relation_name=$2 relation_config
  3265. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  3266. # if ! relation_config=$(
  3267. # echo "$compose_service_relations" |
  3268. # shyaml get-value "${relation_name}" 2>/dev/null); then
  3269. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  3270. # "relation config in compose configuration."
  3271. # return 1
  3272. # fi
  3273. # if [ -z "$relation_config" ]; then
  3274. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  3275. # return 1
  3276. # fi
  3277. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  3278. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  3279. # return 1
  3280. # fi
  3281. # }
  3282. # export -f get_compose_relation_config_for_service
  3283. _get_container_relation() {
  3284. local metadata=$1 found relation_name relation_def
  3285. found=
  3286. while read-0 relation_name relation_def; do
  3287. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  3288. found="$relation_name"
  3289. break
  3290. }
  3291. done < <(_get_charm_metadata_uses "$metadata")
  3292. if [ -z "$found" ]; then
  3293. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  3294. "${WHITE}scope${NORMAL} set to 'container'."
  3295. return 1
  3296. fi
  3297. printf "%s" "$found"
  3298. }
  3299. _get_master_service_for_service_cached () {
  3300. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3301. charm requires master_charm target_charm target_service service_def found
  3302. if [ -e "$cache_file" ]; then
  3303. # debug "$FUNCNAME: STATIC cache hit ($1)"
  3304. cat "$cache_file" &&
  3305. touch "$cache_file" || return 1
  3306. return 0
  3307. fi
  3308. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3309. ## just return service name
  3310. echo "$service" | tee "$cache_file"
  3311. return 0
  3312. fi
  3313. ## Action provided by relation ?
  3314. container_relation=$(_get_container_relation "$metadata") || return 1
  3315. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  3316. if [ -z "$target_service" ]; then
  3317. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  3318. "${DARKYELLOW}$service$NORMAL compose definition."
  3319. err ${FUNCNAME[@]}
  3320. return 1
  3321. fi
  3322. echo "$target_service" | tee "$cache_file"
  3323. }
  3324. export -f _get_master_service_for_service_cached
  3325. get_master_service_for_service() {
  3326. if [ -z "$CHARM_STORE_HASH" ]; then
  3327. err-d "Expected \$CHARM_STORE_HASH to be set."
  3328. return 1
  3329. fi
  3330. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3331. charm metadata result
  3332. if [ -e "$cache_file" ]; then
  3333. # debug "$FUNCNAME: SESSION cache hit ($*)"
  3334. cat "$cache_file" || return 1
  3335. return 0
  3336. fi
  3337. charm=$(get_service_charm "$service") || return 1
  3338. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  3339. metadata=""
  3340. warn "No charm $DARKPINK$charm$NORMAL found."
  3341. }
  3342. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  3343. echo "$result" | tee "$cache_file" || return 1
  3344. }
  3345. export -f get_master_service_for_service
  3346. get_top_master_service_for_service() {
  3347. if [ -z "$CHARM_STORE_HASH" ]; then
  3348. err-d "Expected \$CHARM_STORE_HASH to be set."
  3349. return 1
  3350. fi
  3351. local service="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$1.$CHARM_STORE_HASH" \
  3352. current_service
  3353. if [ -e "$cache_file" ]; then
  3354. # debug "$FUNCNAME: cache hit ($*)"
  3355. touch "$cache_file" || return 1
  3356. cat "$cache_file"
  3357. return 0
  3358. fi
  3359. current_service="$service"
  3360. while true; do
  3361. master_service=$(get_master_service_for_service "$current_service") || return 1
  3362. [ "$master_service" == "$current_service" ] && break
  3363. current_service="$master_service"
  3364. done
  3365. echo "$current_service" | tee "$cache_file"
  3366. return 0
  3367. }
  3368. export -f get_top_master_service_for_service
  3369. ##
  3370. ## The result is a mixin that is not always a complete valid
  3371. ## docker-compose entry (thinking of subordinates). The result
  3372. ## will be merge with master charms.
  3373. _get_docker_compose_mixin_from_metadata_cached() {
  3374. local service="$1" charm="$2" metadata="$3" \
  3375. has_build_dir="$4" \
  3376. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3377. metadata_file metadata volumes docker_compose subordinate image \
  3378. mixin mixins tmemory memory limit docker_memory
  3379. if [ -e "$cache_file" ]; then
  3380. #debug "$FUNCNAME: STATIC cache hit $1"
  3381. cat "$cache_file" &&
  3382. touch "$cache_file" || return 1
  3383. return 0
  3384. fi
  3385. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  3386. if [ "$metadata" ]; then
  3387. ## resources to volumes
  3388. volumes=$(
  3389. for resource_type in data config; do
  3390. while read-0 resource; do
  3391. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  3392. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  3393. done
  3394. while read-0 resource; do
  3395. if [[ "$resource" == /*:/*:* ]]; then
  3396. echo " - $resource"
  3397. elif [[ "$resource" == /*:/* ]]; then
  3398. echo " - $resource:rw"
  3399. elif [[ "$resource" == /*:* ]]; then
  3400. echo " - ${resource%%:*}:$resource"
  3401. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  3402. echo " - $resource:$resource:rw"
  3403. else
  3404. die "Invalid host-resource specified in 'metadata.yml'."
  3405. fi
  3406. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  3407. while read-0 resource; do
  3408. dest="$(charm.get_dir "$charm")/resources$resource"
  3409. if ! [ -e "$dest" ]; then
  3410. die "charm-resource: '$resource' does not exist (file: '$dest')."
  3411. fi
  3412. echo " - $dest:$resource:ro"
  3413. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  3414. ) || return 1
  3415. if [ "$volumes" ]; then
  3416. mixins+=("volumes:"$'\n'"$volumes")
  3417. fi
  3418. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3419. if [ "$type" != "run-once" ]; then
  3420. mixins+=("restart: unless-stopped")
  3421. fi
  3422. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  3423. if [ "$docker_compose" ]; then
  3424. mixins+=("$docker_compose")
  3425. fi
  3426. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3427. subordinate=true
  3428. fi
  3429. fi
  3430. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  3431. [ "$image" == "None" ] && image=""
  3432. if [ -n "$image" ]; then
  3433. if [ -n "$subordinate" ]; then
  3434. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  3435. return 1
  3436. fi
  3437. mixins+=("image: $image")
  3438. elif [ "$has_build_dir" ]; then
  3439. if [ "$subordinate" ]; then
  3440. err "Subordinate charm can not have a 'build' sub directory."
  3441. return 1
  3442. fi
  3443. mixins+=("build: $(charm.get_dir "$charm")/build")
  3444. fi
  3445. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  3446. [ "$limit" == "null" ] && limit=""
  3447. if [ -n "$limit" ]; then
  3448. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  3449. [ "$E" != 0 ]; then
  3450. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  3451. return 1
  3452. fi
  3453. case "$tmemory" in
  3454. '!!str'|'!!int')
  3455. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  3456. err "Invalid format specified for .limit.memory: '$memory'."
  3457. return 1
  3458. }
  3459. ;;
  3460. '!!float')
  3461. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  3462. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  3463. return 1
  3464. ;;
  3465. '!!null')
  3466. :
  3467. ;;
  3468. *)
  3469. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  3470. "for ${WHITE}.limit.memory${NORMAL}."
  3471. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  3472. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  3473. echo " Example values: '1.5G', '252M', ..." >&2
  3474. return 1
  3475. ;;
  3476. esac
  3477. if [ -n "$docker_memory" ]; then
  3478. if [[ "$docker_memory" -lt 6291456 ]]; then
  3479. err "Can't limit service to lower than 6M."
  3480. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  3481. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  3482. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  3483. return 1
  3484. fi
  3485. mixins+=(
  3486. "mem_limit: $docker_memory"
  3487. "memswap_limit: $docker_memory"
  3488. )
  3489. fi
  3490. fi
  3491. ## Final merging
  3492. mixin=$(merge_yaml_str "${mixins[@]}") || {
  3493. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  3494. return 1
  3495. }
  3496. echo "$mixin" | tee "$cache_file"
  3497. }
  3498. export -f _get_docker_compose_mixin_from_metadata_cached
  3499. get_docker_compose_mixin_from_metadata() {
  3500. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3501. if [ -e "$cache_file" ]; then
  3502. #debug "$FUNCNAME: SESSION cache hit ($*)"
  3503. cat "$cache_file"
  3504. return 0
  3505. fi
  3506. charm=$(get_service_charm "$service") || return 1
  3507. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  3508. has_build_dir=
  3509. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  3510. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  3511. echo "$mixin" | tee "$cache_file"
  3512. }
  3513. export -f get_docker_compose_mixin_from_metadata
  3514. _save() {
  3515. local name="$1"
  3516. cat - | tee -a "$docker_compose_dir/.data/$name"
  3517. }
  3518. export -f _save
  3519. get_default_project_name() {
  3520. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  3521. echo "$DEFAULT_PROJECT_NAME"
  3522. return 0
  3523. fi
  3524. local normalized_path compose_yml_location name
  3525. compose_yml_location="$(get_compose_yml_location)" || return 1
  3526. if [ -n "$compose_yml_location" ]; then
  3527. if normalized_path=$(readlink -f "$compose_yml_location"); then
  3528. name="${normalized_path%/*}" ## dirname
  3529. name="${name##*/}" ## basename
  3530. name="${name%%-deploy}" ## remove any '-deploy'
  3531. name="${name,,}" ## lowercase
  3532. e "$name"
  3533. return 0
  3534. fi
  3535. fi
  3536. echo "orphan"
  3537. return 0
  3538. }
  3539. export -f get_default_project_name
  3540. get_running_compose_containers() {
  3541. ## XXXvlab: docker bug: there will be a final newline anyway
  3542. docker ps --filter label="compose.service" --format='{{.ID}}'
  3543. }
  3544. export -f get_running_compose_containers
  3545. get_healthy_container_ip_for_service () {
  3546. local service="$1" port="$2" timeout=${3:-60}
  3547. local containers container container_network container_ip
  3548. containers="$(get_running_containers_for_service "$service")"
  3549. if [ -z "$containers" ]; then
  3550. err "No containers running for service $DARKYELLOW$service$NORMAL."
  3551. return 1
  3552. fi
  3553. ## XXXvlab: taking first container is probably not a good idea
  3554. container="$(echo "$containers" | head -n 1)"
  3555. ## XXXvlab: taking first ip is probably not a good idea
  3556. read-0 container_network container_ip < <(get_container_network_ip "$container")
  3557. if [ -z "$container_ip" ]; then
  3558. err "Can't get container's IP. You should check health of" \
  3559. "${DARKYELLOW}$service${NORMAL}'s container."
  3560. return 1
  3561. fi
  3562. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  3563. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  3564. echo " Please check that container is healthy. Here are last logs:" >&2
  3565. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  3566. return 1
  3567. }
  3568. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  3569. echo "$container_network:$container_ip"
  3570. }
  3571. export -f get_healthy_container_ip_for_service
  3572. switch_to_relation_service() {
  3573. local relation="$1"
  3574. ## XXXvlab: can't get real config here
  3575. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  3576. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  3577. return 1
  3578. fi
  3579. export SERVICE_NAME="$ts"
  3580. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3581. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$SERVICE_NAME")
  3582. export DOCKER_BASE_IMAGE
  3583. target_charm=$(get_service_charm "$ts") || return 1
  3584. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3585. cd "$target_charm_path"
  3586. }
  3587. export -f switch_to_relation_service
  3588. get_volumes_for_container() {
  3589. local container="$1"
  3590. docker inspect \
  3591. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3592. "$container"
  3593. }
  3594. export -f get_volumes_for_container
  3595. is_volume_used() {
  3596. local volume="$1" container_id src dst
  3597. while read -r container_id; do
  3598. while read-0 src dst; do
  3599. [[ "$src/" == "$volume"/* ]] && return 0
  3600. done < <(get_volumes_for_container "$container_id")
  3601. done < <(get_running_compose_containers)
  3602. return 1
  3603. }
  3604. export -f is_volume_used
  3605. clean_unused_docker_compose() {
  3606. for f in /var/lib/compose/docker-compose/*; do
  3607. [ -e "$f" ] || continue
  3608. is_volume_used "$f" && continue
  3609. debug "Cleaning unused docker-compose ${f##*/}"
  3610. rm -rf "$f" || return 1
  3611. done
  3612. return 0
  3613. }
  3614. export -f clean_unused_docker_compose
  3615. docker_compose_store() {
  3616. local file="$1" sha
  3617. sha=$(hash_get 64 < "$file") || return 1
  3618. project=$(get_default_project_name) || return 1
  3619. dst="/var/lib/compose/docker-compose/$sha/$project"
  3620. mkdir -p "$dst" || return 1
  3621. cat <<EOF > "$dst/.env" || return 1
  3622. DOCKER_COMPOSE_PATH=$dst
  3623. COMPOSE_HTTP_TIMEOUT=7200
  3624. EOF
  3625. cp "$file" "$dst/docker-compose.yml" || return 1
  3626. mkdir -p "$dst/bin" || return 1
  3627. cat <<EOF > "$dst/bin/dc" || return 1
  3628. #!/bin/bash
  3629. $(declare -f read-0)
  3630. docker_run_opts=()
  3631. while read-0 opt; do
  3632. if [[ "\$opt" == "!env:"* ]]; then
  3633. opt="\${opt##!env:}"
  3634. var="\${opt%%=*}"
  3635. value="\${opt#*=}"
  3636. export "\$var"="\$value"
  3637. else
  3638. docker_run_opts+=("\$opt")
  3639. fi
  3640. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3641. docker_run_opts+=(
  3642. "-w" "$dst"
  3643. "--entrypoint" "/usr/local/bin/docker-compose"
  3644. )
  3645. [ -t 1 ] && {
  3646. docker_run_opts+=("-ti")
  3647. }
  3648. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3649. EOF
  3650. chmod +x "$dst/bin/dc" || return 1
  3651. printf "%s" "$sha"
  3652. }
  3653. export -f docker_compose_store
  3654. launch_docker_compose() {
  3655. local charm docker_compose_tmpdir docker_compose_dir
  3656. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3657. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3658. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3659. ## docker-compose will name network from the parent dir name
  3660. project=$(get_default_project_name)
  3661. mkdir -p "$docker_compose_tmpdir/$project"
  3662. docker_compose_dir="$docker_compose_tmpdir/$project"
  3663. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  3664. err "${FUNCNAME[0]} is meant to be called after"\
  3665. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  3666. echo " Called by:" >&2
  3667. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  3668. return 1
  3669. fi
  3670. cat "$_CURRENT_DOCKER_COMPOSE" > "$docker_compose_dir/docker-compose.yml" || return 1
  3671. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3672. # debug "Merging some config data in docker-compose.yml:"
  3673. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3674. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3675. fi
  3676. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3677. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3678. fi
  3679. ## XXXvlab: could be more specific and only link the needed charms
  3680. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3681. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3682. # if charm.exists "$charm"; then
  3683. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3684. # fi
  3685. # done
  3686. mkdir "$docker_compose_dir/.data"
  3687. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3688. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3689. fi
  3690. {
  3691. {
  3692. {
  3693. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3694. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3695. else
  3696. cd "$docker_compose_dir" || return 1
  3697. fi
  3698. if [ -f ".env" ]; then
  3699. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3700. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3701. fi
  3702. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3703. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3704. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3705. if [ "$DRY_COMPOSE_RUN" ]; then
  3706. echo docker-compose "$@"
  3707. else
  3708. docker-compose "$@"
  3709. fi
  3710. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3711. } | _save stdout
  3712. } 3>&1 1>&2 2>&3 | _save stderr
  3713. } 3>&1 1>&2 2>&3
  3714. 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
  3715. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3716. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3717. fi
  3718. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3719. if [ -z "$docker_compose_errlvl" ]; then
  3720. err "Something went wrong before you could gather docker-compose errorlevel."
  3721. return 1
  3722. fi
  3723. return "$docker_compose_errlvl"
  3724. }
  3725. export -f launch_docker_compose
  3726. get_compose_yml_location() {
  3727. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3728. echo "$COMPOSE_YML_FILE"
  3729. return 0
  3730. fi
  3731. parent=$(while ! [ -f "./compose.yml" ]; do
  3732. [ "$PWD" == "/" ] && exit 0
  3733. cd ..
  3734. done; echo "$PWD"
  3735. )
  3736. if [ "$parent" ]; then
  3737. echo "$parent/compose.yml"
  3738. return 0
  3739. fi
  3740. ## XXXvlab: do we need this additional environment variable,
  3741. ## COMPOSE_YML_FILE is not sufficient ?
  3742. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3743. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3744. warn "No 'compose.yml' was found in current or parent dirs," \
  3745. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3746. "(${DEFAULT_COMPOSE_FILE})"
  3747. return 0
  3748. fi
  3749. echo "$DEFAULT_COMPOSE_FILE"
  3750. return 0
  3751. fi
  3752. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3753. return 0
  3754. }
  3755. export -f get_compose_yml_location
  3756. get_compose_yml_content() {
  3757. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3758. if [ -e "$cache_file" ]; then
  3759. cat "$cache_file" &&
  3760. touch "$cache_file" || return 1
  3761. return 0
  3762. fi
  3763. if [ -z "$COMPOSE_YML_FILE" ]; then
  3764. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3765. fi
  3766. if [ -e "$COMPOSE_YML_FILE" ]; then
  3767. # debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3768. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3769. err "Could not read '$COMPOSE_YML_FILE'."
  3770. return 1
  3771. }
  3772. else
  3773. debug "No compose file found. Using an empty one."
  3774. COMPOSE_YML_CONTENT=""
  3775. fi
  3776. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3777. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3778. if [ "$?" != 0 ]; then
  3779. outputed_something=
  3780. while IFS='' read -r line1 && IFS='' read -r line2; do
  3781. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3782. outputed_something=true
  3783. echo "$line1 $GRAY($line2)$NORMAL"
  3784. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3785. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3786. prefix " $GRAY|$NORMAL "
  3787. [ "$outputed_something" ] || {
  3788. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3789. echo "$output" | prefix " $GRAY|$NORMAL "
  3790. }
  3791. return 1
  3792. fi
  3793. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3794. }
  3795. export -f get_compose_yml_content
  3796. compose:yml:hash() {
  3797. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3798. if [ -e "$cache_file" ]; then
  3799. cat "$cache_file" &&
  3800. touch "$cache_file" || return 1
  3801. return 0
  3802. fi
  3803. compose_yml_content=$(get_compose_yml_content) || return 1
  3804. compose_yml_hash=$(echo "$compose_yml_content" | hash_get) || return 1
  3805. e "$compose_yml_hash" | tee "$cache_file" || return 1
  3806. }
  3807. export -f compose:yml:hash
  3808. compose:yml:root:services() {
  3809. local cache_file="$state_tmpdir/$FUNCNAME.cache" services compose_yml_content
  3810. if [ -e "$cache_file" ]; then
  3811. cat "$cache_file" &&
  3812. touch "$cache_file" || return 1
  3813. return 0
  3814. fi
  3815. compose_yml_content=$(get_compose_yml_content) || return 1
  3816. services=($(e "$compose_yml_content" | shyaml keys)) || return 1
  3817. e "${services[*]}" | tee "$cache_file" || return 1
  3818. }
  3819. export -f compose:yml:root:services
  3820. get_default_target_services() {
  3821. local services=("$@")
  3822. if [ -z "${services[*]}" ]; then
  3823. if [ "$DEFAULT_SERVICES" ]; then
  3824. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3825. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3826. services="$DEFAULT_SERVICES"
  3827. else
  3828. err "No service provided."
  3829. return 1
  3830. fi
  3831. fi
  3832. echo "${services[*]}"
  3833. }
  3834. export -f get_default_target_services
  3835. get_master_services() {
  3836. local loaded master_service service
  3837. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(H "$@" )"
  3838. if [ -e "$cache_file" ]; then
  3839. cat "$cache_file" &&
  3840. touch "$cache_file" || return 1
  3841. return 0
  3842. fi
  3843. declare -A loaded
  3844. for service in "$@"; do
  3845. master_service=$(get_top_master_service_for_service "$service") || return 1
  3846. if [ "${loaded[$master_service]}" ]; then
  3847. continue
  3848. fi
  3849. echo "$master_service"
  3850. loaded["$master_service"]=1
  3851. done > "$cache_file".wip || return 1
  3852. mv "$cache_file"{.wip,} || return 1
  3853. cat "$cache_file" || return 1
  3854. }
  3855. export -f get_master_services
  3856. get_current_docker_container_id() {
  3857. local line
  3858. line=$(cat "/proc/self/cpuset") || return 1
  3859. [[ "$line" == *docker* ]] || return 1
  3860. echo "${line##*/}"
  3861. }
  3862. export -f get_current_docker_container_id
  3863. ## if we are in a docker compose, we might want to know what is the
  3864. ## real host path of some local paths.
  3865. get_host_path() {
  3866. local path="$1"
  3867. path=$(realpath "$path") || return 1
  3868. container_id=$(get_current_docker_container_id) || {
  3869. print "%s" "$path"
  3870. return 0
  3871. }
  3872. biggest_dst=
  3873. current_src=
  3874. while read-0 src dst; do
  3875. [[ "$path" == "$dst"* ]] || continue
  3876. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3877. biggest_dst="$dst"
  3878. current_src="$src"
  3879. fi
  3880. done < <(get_volumes_for_container "$container_id")
  3881. if [ "$current_src" ]; then
  3882. printf "%s" "$current_src"
  3883. else
  3884. return 1
  3885. fi
  3886. }
  3887. export -f get_host_path
  3888. _setup_state_dir() {
  3889. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3890. #debug "Creating temporary state directory in '$state_tmpdir'."
  3891. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3892. # rm -rf \"$state_tmpdir\""
  3893. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3894. }
  3895. get_docker_compose_help_msg() {
  3896. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3897. docker_compose_help_msg
  3898. if [ -e "$cache_file" ]; then
  3899. cat "$cache_file" &&
  3900. touch "$cache_file" || return 1
  3901. return 0
  3902. fi
  3903. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3904. echo "$docker_compose_help_msg" |
  3905. tee "$cache_file" || return 1
  3906. }
  3907. get_docker_compose_usage() {
  3908. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3909. docker_compose_help_msg
  3910. if [ -e "$cache_file" ]; then
  3911. cat "$cache_file" &&
  3912. touch "$cache_file" || return 1
  3913. return 0
  3914. fi
  3915. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3916. echo "$docker_compose_help_msg" |
  3917. grep -m 1 "^Usage:" -A 10000 |
  3918. egrep -m 1 "^\$" -B 10000 |
  3919. nspc |
  3920. sed -r 's/^Usage: //g' |
  3921. tee "$cache_file" || return 1
  3922. }
  3923. get_docker_compose_opts_help() {
  3924. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3925. docker_compose_help_msg
  3926. if [ -e "$cache_file" ]; then
  3927. cat "$cache_file" &&
  3928. touch "$cache_file" || return 1
  3929. return 0
  3930. fi
  3931. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3932. echo "$docker_compose_opts_help" |
  3933. grep '^Options:' -A 20000 |
  3934. tail -n +2 |
  3935. { cat ; echo; } |
  3936. egrep -m 1 "^\S*\$" -B 10000 |
  3937. head -n -1 |
  3938. tee "$cache_file" || return 1
  3939. }
  3940. get_docker_compose_commands_help() {
  3941. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3942. docker_compose_help_msg
  3943. if [ -e "$cache_file" ]; then
  3944. cat "$cache_file" &&
  3945. touch "$cache_file" || return 1
  3946. return 0
  3947. fi
  3948. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3949. echo "$docker_compose_opts_help" |
  3950. grep '^Commands:' -A 20000 |
  3951. tail -n +2 |
  3952. { cat ; echo; } |
  3953. egrep -m 1 "^\S*\$" -B 10000 |
  3954. head -n -1 |
  3955. tee "$cache_file" || return 1
  3956. }
  3957. get_docker_compose_opts_list() {
  3958. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3959. docker_compose_help_msg
  3960. if [ -e "$cache_file" ]; then
  3961. cat "$cache_file" &&
  3962. touch "$cache_file" || return 1
  3963. return 0
  3964. fi
  3965. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3966. echo "$docker_compose_opts_help" |
  3967. egrep "^\s+-" |
  3968. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3969. tee "$cache_file" || return 1
  3970. }
  3971. options_parser() {
  3972. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3973. printf "\0"
  3974. }
  3975. remove_options_in_option_help_msg() {
  3976. {
  3977. read-0 null
  3978. if [ "$null" ]; then
  3979. err "options parsing error, should start with an option line."
  3980. return 1
  3981. fi
  3982. while read-0 opt full_txt;do
  3983. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3984. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3985. for to_remove in "$@"; do
  3986. str_matches "$to_remove" $multi_opts $single_opts && {
  3987. continue 2
  3988. }
  3989. done
  3990. echo -n "$full_txt"
  3991. done
  3992. } < <(options_parser)
  3993. }
  3994. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3995. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3996. multi_opts_filter() {
  3997. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3998. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3999. tr ',' "\n" | nspc
  4000. }
  4001. single_opts_filter() {
  4002. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  4003. tr ',' "\n" | nspc
  4004. }
  4005. get_docker_compose_multi_opts_list() {
  4006. local action="$1" opts_list
  4007. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4008. echo "$opts_list" | multi_opts_filter
  4009. }
  4010. get_docker_compose_single_opts_list() {
  4011. local action="$1" opts_list
  4012. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  4013. echo "$opts_list" | single_opts_filter
  4014. }
  4015. display_commands_help() {
  4016. local charm_actions
  4017. echo
  4018. echo "${WHITE}Commands${NORMAL} (added by compose):"
  4019. echo " ${DARKCYAN}cache${NORMAL} Control compose's cache"
  4020. echo " ${DARKCYAN}status${NORMAL} Display statuses of services"
  4021. echo
  4022. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  4023. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  4024. charm_actions_help=$(get_docker_charm_action_help) || return 1
  4025. if [ "$charm_actions_help" ]; then
  4026. echo
  4027. echo "${WHITE}Charm actions${NORMAL}:"
  4028. printf "%s\n" "$charm_actions_help" | \
  4029. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  4030. fi
  4031. }
  4032. get_docker_charm_action() {
  4033. local services service charm relation_name target_service relation_config \
  4034. target_charm services
  4035. ## XXXvlab: this is for get_service_relations
  4036. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4037. err-d "Failed to set relations hash."
  4038. return 1
  4039. }
  4040. services=($(get_all_services)) || return 1
  4041. for service in "${services[@]}"; do
  4042. printf "%s:\n" "$service"
  4043. charm=$(get_service_charm "$service") || return 1
  4044. for action in $(charm.ls_direct_actions "$charm"); do
  4045. printf " %s:\n" "$action"
  4046. printf " type: %s\n" "direct"
  4047. done
  4048. while read-0 relation_name target_service _relation_config _tech_dep; do
  4049. target_charm=$(get_service_charm "$target_service") || return 1
  4050. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4051. printf " %s:\n" "$action"
  4052. printf " type: %s\n" "indirect"
  4053. printf " inherited: %s\n" "$target_charm"
  4054. done
  4055. done < <(get_service_relations "$service")
  4056. done
  4057. }
  4058. export -f get_docker_charm_action
  4059. get_docker_charm_action_help() {
  4060. local services service charm relation_name target_service relation_config \
  4061. target_charm
  4062. ## XXXvlab: this is for get_service_relations
  4063. NO_CONSTRAINT_CHECK=True service:all:set_relations_hash || {
  4064. err-d "Failed to set relations hash."
  4065. return 1
  4066. }
  4067. services=($(get_all_services)) || return 1
  4068. for service in "${services[@]}"; do
  4069. out=$(
  4070. charm=$(get_service_charm "$service") || return 1
  4071. for action in $(charm.ls_direct_actions "$charm"); do
  4072. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  4073. done
  4074. while read-0 relation_name target_service _relation_config _tech_dep; do
  4075. target_charm=$(get_service_charm "$target_service") || return 1
  4076. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  4077. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  4078. done
  4079. done < <(get_service_relations "$service")
  4080. )
  4081. if [ "$out" ]; then
  4082. echo " for ${DARKYELLOW}$service${NORMAL}:"
  4083. printf "%s\n" "$out"
  4084. fi
  4085. done
  4086. }
  4087. display_help() {
  4088. print_help
  4089. echo "${WHITE}Usage${NORMAL}:"
  4090. echo " $usage"
  4091. echo " $usage cache {clean|clear}"
  4092. echo "${WHITE}Options${NORMAL}:"
  4093. echo " -h, --help Print this message and quit"
  4094. echo " (ignoring any other options)"
  4095. echo " -V, --version Print current version and quit"
  4096. echo " (ignoring any other options)"
  4097. echo " --dirs Display data dirs and quit"
  4098. echo " (ignoring any other options)"
  4099. echo " --get-project-name Display project name and quit"
  4100. echo " (ignoring any other options)"
  4101. echo " --get-available-actions Display all available actions and quit"
  4102. echo " (ignoring any other options)"
  4103. echo " -v, --verbose Be more verbose"
  4104. echo " -q, --quiet Be quiet"
  4105. echo " -d, --debug Print full debugging information (sets also verbose)"
  4106. echo " --dry-compose-run If docker-compose will be run, only print out what"
  4107. echo " command line will be used."
  4108. echo " --no-relations Do not run any relation script"
  4109. echo " --no-hooks Do not run any hook script"
  4110. echo " --no-init Do not run any init script"
  4111. echo " --no-post-deploy Do not run any post-deploy script"
  4112. echo " --no-pre-deploy Do not run any pre-deploy script"
  4113. echo " --without-relation RELATION "
  4114. echo " Do not run given relation"
  4115. echo " -R, --rebuild-relations-to-service SERVICE"
  4116. echo " Will rebuild all relations to given service"
  4117. echo " --add-compose-content, -Y YAML"
  4118. echo " Will merge some direct YAML with the current compose"
  4119. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  4120. echo " --push-builds Will push cached docker images to docker cache registry"
  4121. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  4122. filter_docker_compose_help_message
  4123. display_commands_help
  4124. }
  4125. _graph_service() {
  4126. local service="$1" base="$1"
  4127. charm=$(get_service_charm "$service") || return 1
  4128. metadata=$(charm.metadata "$charm") || return 1
  4129. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  4130. if [[ "$subordinate" =~ ^True|true$ ]]; then
  4131. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  4132. master_charm=
  4133. while read-0 relation_name relation; do
  4134. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  4135. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  4136. if [ -z "$interface" ]; then
  4137. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  4138. return 1
  4139. fi
  4140. ## Action provided by relation ?
  4141. target_service=
  4142. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  4143. [ "$interface" == "$relation_name" ] && {
  4144. target_service="$candidate_target_service"
  4145. break
  4146. }
  4147. done < <(get_service_relations "$service")
  4148. if [ -z "$target_service" ]; then
  4149. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  4150. "${DARKYELLOW}$service$NORMAL compose definition."
  4151. return 1
  4152. fi
  4153. master_service="$target_service"
  4154. master_charm=$(get_service_charm "$target_service") || return 1
  4155. break
  4156. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  4157. fi
  4158. _graph_node_service "$service" "$base" "$charm"
  4159. _graph_edge_service "$service" "$subordinate" "$master_service"
  4160. }
  4161. _graph_node_service() {
  4162. local service="$1" base="$2" charm="$3"
  4163. cat <<EOF
  4164. "$(_graph_node_service_label ${service})" [
  4165. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  4166. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  4167. color = $([ "$base" ] && echo "blue" || echo "black")
  4168. fillcolor = "white"
  4169. fontname = "Courier New"
  4170. shape = "Mrecord"
  4171. label =<$(_graph_node_service_content "$service")>
  4172. ];
  4173. EOF
  4174. }
  4175. _graph_edge_service() {
  4176. local service="$1" subordinate="$2" master_service="$3"
  4177. while read-0 relation_name target_service relation_config tech_dep; do
  4178. cat <<EOF
  4179. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  4180. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  4181. fontsize = 16
  4182. fontcolor = "black"
  4183. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  4184. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  4185. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  4186. arrowtail = odot
  4187. # arrowhead = dotlicurve
  4188. taillabel = "$relation_name" ];
  4189. EOF
  4190. done < <(get_service_relations "$service") || return 1
  4191. }
  4192. _graph_node_service_label() {
  4193. local service="$1"
  4194. echo "service_$service"
  4195. }
  4196. _graph_node_service_content() {
  4197. local service="$1"
  4198. charm=$(get_service_charm "$service") || return 1
  4199. cat <<EOF
  4200. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  4201. <tr>
  4202. <td bgcolor="black" align="center" colspan="2">
  4203. <font color="white">$service</font>
  4204. </td>
  4205. </tr>
  4206. $(if [ "$charm" != "$service" ]; then
  4207. cat <<EOF2
  4208. <tr>
  4209. <td align="left" port="r0">charm: $charm</td>
  4210. </tr>
  4211. EOF2
  4212. fi)
  4213. </table>
  4214. EOF
  4215. }
  4216. cla_contains () {
  4217. local e
  4218. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  4219. return 1
  4220. }
  4221. filter_docker_compose_help_message() {
  4222. cat - |
  4223. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  4224. s/docker-compose.yml/compose.yml/g;
  4225. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  4226. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  4227. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  4228. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  4229. }
  4230. graph() {
  4231. local services=("$@")
  4232. declare -A entries
  4233. cat <<EOF
  4234. digraph g {
  4235. graph [
  4236. fontsize=30
  4237. labelloc="t"
  4238. label=""
  4239. splines=true
  4240. overlap=false
  4241. #rankdir = "LR"
  4242. ];
  4243. ratio = auto;
  4244. EOF
  4245. for target_service in "$@"; do
  4246. services=$(get_ordered_service_dependencies "$target_service") || return 1
  4247. for service in $services; do
  4248. [ "${entries[$service]}" ] && continue || entries[$service]=1
  4249. if cla_contains "$service" "${services[@]}"; then
  4250. base=true
  4251. else
  4252. base=
  4253. fi
  4254. _graph_service "$service" "$base"
  4255. done
  4256. done
  4257. echo "}"
  4258. }
  4259. cached_wget() {
  4260. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  4261. url="$1"
  4262. if [ -e "$cache_file" ]; then
  4263. cat "$cache_file"
  4264. touch "$cache_file"
  4265. return 0
  4266. fi
  4267. wget -O- "${url}" |
  4268. tee "$cache_file"
  4269. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4270. rm "$cache_file"
  4271. die "Unable to fetch '$url'."
  4272. return 1
  4273. fi
  4274. }
  4275. export -f cached_wget
  4276. [ "$SOURCED" ] && return 0
  4277. trap_add "EXIT" clean_cache
  4278. export COMPOSE_DOCKER_REGISTRY="${COMPOSE_DOCKER_REGISTRY:-docker.0k.io}"
  4279. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  4280. if [ -r /etc/default/charm ]; then
  4281. . "/etc/default/charm"
  4282. fi
  4283. if [ -r "/etc/default/$exname" ]; then
  4284. . "/etc/default/$exname"
  4285. fi
  4286. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  4287. ## userdir ? and global /etc/compose.yml ?
  4288. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  4289. /etc/default/compose /etc/compose/local.conf; do
  4290. [ -e "$cfgfile" ] || continue
  4291. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  4292. done
  4293. fi
  4294. _setup_state_dir
  4295. mkdir -p "$CACHEDIR" || exit 1
  4296. log () { cat; }
  4297. export -f log
  4298. ##
  4299. ## Argument parsing
  4300. ##
  4301. wrap_opts=()
  4302. services=()
  4303. remainder_args=()
  4304. compose_opts=()
  4305. compose_contents=()
  4306. action_opts=()
  4307. services_args=()
  4308. pos_arg_ct=0
  4309. no_hooks=
  4310. no_init=
  4311. action=
  4312. stage="main" ## switches from 'main', to 'action', 'remainder'
  4313. is_docker_compose_action=
  4314. is_docker_compose_action_multi_service=
  4315. rebuild_relations_to_service=()
  4316. color=
  4317. declare -A without_relations
  4318. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  4319. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  4320. while read-0 arg; do
  4321. case "$stage" in
  4322. "main")
  4323. case "$arg" in
  4324. --help|-h)
  4325. no_init=true ; no_hooks=true ; no_relations=true
  4326. display_help
  4327. exit 0
  4328. ;;
  4329. --verbose|-v)
  4330. export VERBOSE=true
  4331. compose_opts+=("--verbose")
  4332. ;;
  4333. --quiet|-q)
  4334. export QUIET=true
  4335. export wrap_opts+=("-q")
  4336. log () { cat >&2; }
  4337. export -f log
  4338. ;;
  4339. --version|-V)
  4340. print_version
  4341. docker-compose --version
  4342. docker --version
  4343. exit 0
  4344. ;;
  4345. -f|--file)
  4346. read-0 value
  4347. [ -e "$value" ] || die "File $value doesn't exists"
  4348. export COMPOSE_YML_FILE="$value"
  4349. shift
  4350. ;;
  4351. -p|--project-name)
  4352. read-0 value
  4353. export DEFAULT_PROJECT_NAME="$value"
  4354. compose_opts+=("--project-name $value")
  4355. shift
  4356. ;;
  4357. --color|-c)
  4358. if [ "$color" == "0" ]; then
  4359. err "Conflicting option --color with previous --no-ansi."
  4360. exit 1
  4361. fi
  4362. color=1
  4363. ansi_color yes
  4364. ;;
  4365. --no-ansi)
  4366. if [ "$color" == "1" ]; then
  4367. err "Conflicting option --no-ansi with previous --color."
  4368. exit 1
  4369. fi
  4370. color=0
  4371. ansi_color no
  4372. compose_opts+=("--no-ansi")
  4373. ;;
  4374. --no-relations)
  4375. export no_relations=true
  4376. ;;
  4377. --without-relation)
  4378. read-0 value
  4379. without_relations["$value"]=1
  4380. shift
  4381. ;;
  4382. --no-hooks)
  4383. export no_hooks=true
  4384. ;;
  4385. --no-init)
  4386. export no_init=true
  4387. ;;
  4388. --no-post-deploy)
  4389. export no_post_deploy=true
  4390. ;;
  4391. --no-pre-deploy)
  4392. export no_pre_deploy=true
  4393. ;;
  4394. --rebuild-relations-to-service|-R)
  4395. read-0 value
  4396. rebuild_relations_to_service+=("$value")
  4397. shift
  4398. ;;
  4399. --push-builds)
  4400. export COMPOSE_PUSH_TO_REGISTRY=1
  4401. ;;
  4402. --debug|-d)
  4403. export DEBUG=true
  4404. export VERBOSE=true
  4405. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  4406. ;;
  4407. --add-compose-content|-Y)
  4408. read-0 value
  4409. compose_contents+=("$value")
  4410. shift
  4411. ;;
  4412. --dirs)
  4413. echo "CACHEDIR: $CACHEDIR"
  4414. echo "VARDIR: $VARDIR"
  4415. exit 0
  4416. ;;
  4417. --get-project-name)
  4418. project=$(get_default_project_name) || exit 1
  4419. echo "$project"
  4420. exit 0
  4421. ;;
  4422. --get-available-actions)
  4423. get_docker_charm_action
  4424. exit $?
  4425. ;;
  4426. --dry-compose-run)
  4427. export DRY_COMPOSE_RUN=true
  4428. ;;
  4429. --*|-*)
  4430. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4431. read-0 value
  4432. compose_opts+=("$arg" "$value")
  4433. shift;
  4434. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4435. compose_opts+=("$arg")
  4436. else
  4437. err "Unknown option '$arg'. Please check help:"
  4438. display_help >&2
  4439. exit 1
  4440. fi
  4441. ;;
  4442. *)
  4443. action="$arg"
  4444. stage="action"
  4445. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  4446. is_docker_compose_action=true
  4447. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  4448. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  4449. if [ "$DC_MATCH_MULTI" ]; then
  4450. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  4451. fi
  4452. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  4453. pos_args=("${pos_args[@]:1}")
  4454. if [[ "${pos_args[0]}" == "[SERVICE...]" ]]; then
  4455. is_docker_compose_action_multi_service=1
  4456. elif [[ "${pos_args[0]}" == "SERVICE" ]]; then
  4457. is_docker_compose_action_multi_service=0
  4458. fi
  4459. # echo "USAGE: $DC_USAGE"
  4460. # echo "pos_args: ${pos_args[@]}"
  4461. # echo "MULTI: $DC_MATCH_MULTI"
  4462. # echo "SINGLE: $DC_MATCH_SINGLE"
  4463. # exit 1
  4464. else
  4465. stage="remainder"
  4466. fi
  4467. ;;
  4468. esac
  4469. ;;
  4470. "action") ## Only for docker-compose actions
  4471. case "$arg" in
  4472. --help|-h)
  4473. no_init=true ; no_hooks=true ; no_relations=true
  4474. action_opts+=("$arg")
  4475. ;;
  4476. --*|-*)
  4477. if [ "$is_docker_compose_action" ]; then
  4478. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4479. read-0 value
  4480. action_opts+=("$arg" "$value")
  4481. shift
  4482. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4483. action_opts+=("$arg")
  4484. else
  4485. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  4486. docker-compose "$action" --help |
  4487. filter_docker_compose_help_message >&2
  4488. exit 1
  4489. fi
  4490. fi
  4491. ;;
  4492. *)
  4493. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  4494. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  4495. services_args+=("$arg")
  4496. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  4497. services_args=("$arg") || exit 1
  4498. stage="remainder"
  4499. else
  4500. action_posargs+=("$arg")
  4501. ((pos_arg_ct++))
  4502. fi
  4503. ;;
  4504. esac
  4505. ;;
  4506. "remainder")
  4507. remainder_args+=("$arg")
  4508. while read-0 arg; do
  4509. remainder_args+=("$arg")
  4510. done
  4511. break 3
  4512. ;;
  4513. esac
  4514. shift
  4515. done < <(cla.normalize "$@")
  4516. ## These actions are additions to docker-compose actions and charm
  4517. ## actions
  4518. more_actions=(status)
  4519. if [[ "$action" == *" "* ]]; then
  4520. err "Invalid action name containing spaces: ${DARKCYAN}$action${NORMAL}"
  4521. exit 1
  4522. fi
  4523. is_more_action=
  4524. [[ " ${more_actions[*]} " == *" $action "* ]] && is_more_action=true
  4525. [ -n "$CACHEDIR" ] || die "No cache directory defined."
  4526. [ -d "$CACHEDIR" ] || die "Cache directory '$CACHEDIR' doesn't exists."
  4527. case "$action" in
  4528. cache)
  4529. case "${remainder_args[0]}" in
  4530. clean)
  4531. clean_cache
  4532. exit 0
  4533. ;;
  4534. clear)
  4535. Wrap "${wrap_opts[@]}" -v -d "clear cache directory" -- rm -rf "$CACHEDIR/"*
  4536. ## clear all docker caches
  4537. ## image name are like '[$COMPOSE_DOCKER_REGISTRY]cache/charm/CHARM_NAME:HASH'
  4538. Wrap "${wrap_opts[@]}" -v -d "clear docker cache" <<EOF
  4539. docker images --format "{{.Repository}}:{{.Tag}}" |
  4540. egrep "^($COMPOSE_DOCKER_REGISTRY/)?cache/charm/[a-zA-Z0-9._-]+:[0-9a-f]{32,32}$" |
  4541. while read -r image; do
  4542. docker rmi "\$image" || true
  4543. done
  4544. EOF
  4545. exit 0
  4546. ;;
  4547. *)
  4548. err "Unknown cache command: ${DARKCYAN}${remainder_args[0]}${NORMAL}"
  4549. exit 1
  4550. ;;
  4551. esac
  4552. ;;
  4553. status)
  4554. state_inner_cols=(name charm type state root)
  4555. state_all_services=
  4556. state_services=()
  4557. state_columns=()
  4558. state_columns_default=(name charm type state version)
  4559. state_filters=()
  4560. state_columns_default_msg=""
  4561. for col in "${state_columns_default[@]}"; do
  4562. if [ -n "$state_columns_default_msg" ]; then
  4563. state_columns_default_msg+=","
  4564. fi
  4565. state_columns_default_msg+="$col"
  4566. done
  4567. help="\
  4568. Display status information on services.
  4569. If no services are provided, all services in the root compose file
  4570. will be displayed. Use the --all option to display status of all
  4571. services (including dependencies).
  4572. $exname offers a few possible columns that can be complete on a charm
  4573. level by implementing an \`actions/get-COLNAME\` script.
  4574. These are the compose's columns: ${state_inner_cols[@]}.
  4575. Usage: status [options] [SERVICE...]
  4576. Options:
  4577. -h, --help Print this message and quit
  4578. -a, --all Display status of all services
  4579. (removes all filter, and will add a
  4580. 'root' first column by default)
  4581. -c, --column Column to display, can provide several
  4582. separated by commas, or option can be repeated.
  4583. (default: ${state_columns_default_msg})
  4584. -f, --filter Filter services by a key=value pair,
  4585. separated by commas or can be repeated.
  4586. (default: --filter root=yes)
  4587. "
  4588. while read-0 arg; do
  4589. case "$arg" in
  4590. --help|-h)
  4591. echo "$help"
  4592. exit 0
  4593. ;;
  4594. --all|-a)
  4595. if [ "${#state_services[@]}" -gt 0 ]; then
  4596. err "Cannot use --all and provide services at the same time."
  4597. exit 1
  4598. fi
  4599. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4600. err "Cannot use --all and provide filters at the same time."
  4601. exit 1
  4602. fi
  4603. state_all_services=1
  4604. ;;
  4605. --column|-c)
  4606. read-0 value
  4607. if [[ "$value" == *,* ]]; then
  4608. state_columns+=(${value//,/ })
  4609. else
  4610. state_columns+=("$value")
  4611. fi
  4612. ;;
  4613. --filter|-f)
  4614. if [ "${#state_services[@]}" -gt 0 ]; then
  4615. err "Cannot use --filter and provide services at the same time."
  4616. exit 1
  4617. fi
  4618. if [ -n "$state_all_services" ]; then
  4619. err "Cannot use --all and provide filters at the same time."
  4620. exit 1
  4621. fi
  4622. read-0 value
  4623. if [[ "$value" == *,* ]]; then
  4624. state_filters+=(${value//,/ })
  4625. else
  4626. state_filters+=("$value")
  4627. fi
  4628. ;;
  4629. --*|-*)
  4630. err "Unknown option '$arg'. Please check help:"
  4631. echo "$help" >&2
  4632. ;;
  4633. *)
  4634. if [ -n "$state_all_services" ]; then
  4635. err "Cannot use --all and provide services at the same time."
  4636. exit 1
  4637. fi
  4638. if [[ "${#state_filters[@]}" -gt 0 ]]; then
  4639. err "Cannot use --filter and provide filters at the same time."
  4640. exit 1
  4641. fi
  4642. state_services+=("$arg")
  4643. ;;
  4644. esac
  4645. done < <(cla.normalize "${remainder_args[@]}")
  4646. if [ "${#state_columns[@]}" == 0 ]; then
  4647. state_columns=("${state_columns_default[@]}")
  4648. fi
  4649. ;;
  4650. esac
  4651. export compose_contents
  4652. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  4653. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  4654. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  4655. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  4656. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  4657. aexport remainder_args
  4658. ##
  4659. ## Actual code
  4660. ##
  4661. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  4662. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  4663. COMPOSE_YML_CONTENT_HASH=$(compose:yml:hash) || exit 1
  4664. CHARM_STORE_HASH=$(charm.store_metadata_hash) || exit 1
  4665. COMBINED_HASH=$(H "$COMPOSE_YML_CONTENT_HASH" "$CHARM_STORE_HASH") || exit 1
  4666. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT COMPOSE_YML_CONTENT_HASH CHARM_STORE_HASH COMBINED_HASH
  4667. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  4668. ##
  4669. ## Get services in command line.
  4670. ##
  4671. if [ -z "$is_docker_compose_action" ] && [ -z "$is_more_action" ] && [ -n "$action" ]; then
  4672. action_service=${remainder_args[0]}
  4673. if [ -z "$action_service" ]; then
  4674. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  4675. display_commands_help
  4676. exit 1
  4677. fi
  4678. services_args=($(compose:yml:root:services)) || return 1
  4679. ## Required by has_service_action
  4680. service:all:set_relations_hash
  4681. remainder_args=("${remainder_args[@]:1}")
  4682. if has_service_action "$action_service" "$action" >/dev/null; then
  4683. is_service_action=true
  4684. services_args=("$action_service")
  4685. {
  4686. read-0 action_type
  4687. case "$action_type" in
  4688. "relation")
  4689. read-0 _ target_service _target_charm relation_name _ action_script_path
  4690. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  4691. services_args+=("$target_service")
  4692. ;;
  4693. "direct")
  4694. read-0 _ action_script_path
  4695. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  4696. ;;
  4697. esac
  4698. } < <(has_service_action "$action_service" "$action")
  4699. get_all_relations "${services_args[@]}" >/dev/null || {
  4700. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  4701. exit 1
  4702. }
  4703. ## Divert logging to stdout to stderr
  4704. log () { cat >&2; }
  4705. export -f log
  4706. else
  4707. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  4708. fi
  4709. else
  4710. case "$action" in
  4711. ps|up)
  4712. if [ "${#services_args[@]}" == 0 ]; then
  4713. services_args=($(compose:yml:root:services)) || return 1
  4714. fi
  4715. ;;
  4716. status)
  4717. services_args=("${state_services[@]}")
  4718. if [ "${#services_args[@]}" == 0 ] && [ -z "$state_all_services" ]; then
  4719. services_args=($(compose:yml:root:services)) || return 1
  4720. fi
  4721. ;;
  4722. config)
  4723. services_args=("${action_posargs[@]}")
  4724. ;;
  4725. esac
  4726. fi
  4727. export COMPOSE_ACTION="$action"
  4728. NO_CONSTRAINT_CHECK=True
  4729. case "$action" in
  4730. up|status)
  4731. NO_CONSTRAINT_CHECK=
  4732. if [ -n "$DEBUG" ]; then
  4733. Elt "solve all relations"
  4734. start=$(time_now)
  4735. fi
  4736. service:all:set_relations_hash || exit 1
  4737. if [ -n "$DEBUG" ]; then
  4738. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4739. print_info "$(printf "%.3fs" "$elapsed")"
  4740. Feedback
  4741. fi
  4742. all_services=($(get_all_services)) || exit 1
  4743. ## check that services_args is a subset of all_services
  4744. for service in "${services_args[@]}"; do
  4745. [[ " ${all_services[*]} " == *" $service "* ]] || {
  4746. err "Service ${DARKYELLOW}$service${NORMAL} is not defined in the current compose file."
  4747. echo " Neither is is a dependency of a service in the compose file." >&2
  4748. echo " These are the services directly or indirectly available from current compose file:" >&2
  4749. for service in "${all_services[@]}"; do
  4750. echo " - ${DARKYELLOW}$service${NORMAL}" >&2
  4751. done
  4752. exit 1
  4753. }
  4754. done
  4755. ;;
  4756. esac
  4757. case "$action" in
  4758. up)
  4759. PROJECT_NAME=$(get_default_project_name) || exit 1
  4760. ## Remove all intents (*ing states)
  4761. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*ing || true
  4762. ## Notify that we have the intent to bring up all these
  4763. ## This will be use in inner or concurrent 'run' to include the
  4764. ## services that are supposed to be up.
  4765. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME" || exit 1
  4766. services_args_deps=($(get_ordered_service_dependencies "${services_args[@]}")) || exit 1
  4767. for service in "${services_args_deps[@]}"; do
  4768. mkdir -p "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service" || exit 1
  4769. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/up ] || {
  4770. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"$service"/deploying || exit 1
  4771. }
  4772. done
  4773. ## remove services not included in compose.yml anymore
  4774. all_services_deps=($(get_ordered_service_dependencies "${all_services[@]}")) || exit 1
  4775. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/up; do
  4776. [ -e "$service" ] || continue
  4777. state=${service##*/}
  4778. service=${service%/$state}
  4779. service=${service##*/}
  4780. if [[ " ${all_services_deps[*]} " != *" ${service} "* ]]; then
  4781. touch "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  4782. fi
  4783. done
  4784. ;;
  4785. run)
  4786. PROJECT_NAME=$(get_default_project_name) || return 1
  4787. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  4788. ## Notify that we have the intent to bring up all these
  4789. ## This will be use in inner or concurrent 'run' to include the
  4790. ## services that are supposed to be up.
  4791. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/{up,deploying}; do
  4792. [ -e "$service" ] || continue
  4793. state=${service##*/}
  4794. service=${service%/$state}
  4795. service=${service##*/}
  4796. ## don't add if orphaning
  4797. [ -e "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning ] && continue
  4798. done
  4799. fi
  4800. ;;
  4801. status)
  4802. if [ -n "${state_all_services}" ] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  4803. services_args=("${all_services[@]}")
  4804. fi
  4805. ;;
  4806. esac
  4807. if [ -n "$is_docker_compose_action_multi_service" ]; then
  4808. if [ -n "$DEBUG" ]; then
  4809. Elt "get relation subset"
  4810. start=$(time_now)
  4811. fi
  4812. get_subset_relations "${services_args[@]}" >/dev/null || exit 1
  4813. if [ -n "$DEBUG" ]; then
  4814. elapsed="$(time_elapsed $start "$(time_now)")" || exit 1
  4815. print_info "$(printf "%.3fs" "$elapsed")"
  4816. Feedback
  4817. fi
  4818. fi
  4819. if [ -n "$is_docker_compose_action" ] && [ "${#services_args[@]}" -gt 0 ]; then
  4820. services=($(get_master_services "${services_args[@]}")) || exit 1
  4821. if [ "$action" == "up" ]; then
  4822. action_posargs+=($(services:get:upable "${services_args[@]}")) || exit 1
  4823. elif [ "$is_docker_compose_action_multi_service" == "1" ]; then
  4824. action_posargs+=("${services[@]}")
  4825. elif [ "$is_docker_compose_action_multi_service" == "0" ]; then
  4826. action_posargs+=("${services[0]}") ## only the first service is the legit one
  4827. fi
  4828. ## Get rid of subordinates
  4829. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  4830. fi
  4831. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  4832. err "Fails to compile base 'docker-compose.yml'"
  4833. exit 1
  4834. }
  4835. ##
  4836. ## Pre-action
  4837. ##
  4838. full_init=
  4839. case "$action" in
  4840. build)
  4841. full_init=true ## will actually stop after build
  4842. ;;
  4843. up|run)
  4844. full_init=true
  4845. post_hook=true
  4846. ;;
  4847. ""|down|restart|logs|config|ps|status)
  4848. full_init=
  4849. ;;
  4850. *)
  4851. if [ "$is_service_action" ]; then
  4852. full_init=true
  4853. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4854. for keyword in "${keywords[@]}"; do
  4855. case "$keyword" in
  4856. no-hooks)
  4857. no_hooks=true
  4858. ;;
  4859. hooks)
  4860. full_init=true
  4861. ;;
  4862. esac
  4863. done
  4864. fi
  4865. ;;
  4866. esac
  4867. if [ -n "$full_init" ]; then
  4868. if [[ "$action" == "build" ]] || [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4869. [[ "$action" == "build" ]] || Section "acquire charm's images"
  4870. run_service_acquire_images "${services_args[@]}" || exit 1
  4871. Feed
  4872. [ "$action" == "build" ] && {
  4873. exit 0
  4874. }
  4875. Section setup host resources
  4876. setup_host_resources "${services_args[@]}" || exit 1
  4877. ## init in order
  4878. Section initialisation
  4879. run_service_hook init "${services_args[@]}" || exit 1
  4880. fi
  4881. ## Get relations
  4882. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4883. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4884. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4885. rebuild_relations_to_service=($rebuild_relations_to_service)
  4886. project=$(get_default_project_name) || return 1
  4887. for service in "${rebuild_relations_to_service[@]}"; do
  4888. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  4889. [ -d "$dir" ] && {
  4890. debug rm -rf "$dir"
  4891. rm -rf "$dir"
  4892. }
  4893. done
  4894. done
  4895. fi
  4896. run_service_relations "${services_args[@]}" || exit 1
  4897. fi
  4898. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  4899. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  4900. fi
  4901. fi | log
  4902. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4903. exit 1
  4904. fi
  4905. [ "$action" == "build" ] && exit 0
  4906. if [ "$action" == "status" ]; then
  4907. if [[ -n "${state_all_services}" ]] || [[ "${#state_filters[@]}" -gt 0 ]]; then
  4908. compose_yml_services=($(compose:yml:root:services)) || exit 1
  4909. fi
  4910. if [[ -n "${state_all_services}" ]]; then
  4911. state_columns=("root" ${state_columns[@]})
  4912. fi
  4913. state_columns_raw=()
  4914. for col in "${state_columns[@]}"; do
  4915. if [[ "$col" == "-"* ]]; then
  4916. col=${col#-}
  4917. fi
  4918. state_columns_raw+=("$col")
  4919. done
  4920. state_columns_align=""
  4921. for col in "${state_columns[@]}"; do
  4922. if [[ "$col" == "-"* ]]; then
  4923. state_columns_align+="+"
  4924. else
  4925. state_columns_align+="-"
  4926. fi
  4927. done
  4928. while read-0-err E "${state_columns_raw[@]}"; do
  4929. values=()
  4930. for col in "${state_columns_raw[@]}"; do
  4931. color=
  4932. value="${!col}"
  4933. read -r -- value_trim <<<"${!col}"
  4934. case "$col" in
  4935. root)
  4936. case "$value_trim" in
  4937. 0) value=" ";;
  4938. 1) value="*";;
  4939. esac
  4940. ;;
  4941. name) color=darkyellow;;
  4942. charm) color=darkpink;;
  4943. state)
  4944. case "$value_trim" in
  4945. up) color=green;;
  4946. down) color=gray;;
  4947. deploying) color=yellow;;
  4948. *) color=red;;
  4949. esac
  4950. ;;
  4951. type)
  4952. case "$value_trim" in
  4953. run-once) color=gray;;
  4954. stub) color=gray;;
  4955. *) color=darkcyan;;
  4956. esac
  4957. ;;
  4958. *)
  4959. if [[ "${value_trim}" == "N/A" ]]; then
  4960. color=gray
  4961. fi
  4962. ;;
  4963. esac
  4964. color="${color^^}"
  4965. if [ -n "$color" ]; then
  4966. values+=("${!color}$value${NORMAL}")
  4967. else
  4968. values+=("$value")
  4969. fi
  4970. done
  4971. first=1
  4972. for value in "${values[@]}"; do
  4973. if [ -n "$first" ]; then
  4974. first=
  4975. else
  4976. printf " "
  4977. fi
  4978. printf "%s" "$value"
  4979. done
  4980. printf "\n"
  4981. done < <(
  4982. set -o pipefail
  4983. filter_cols=()
  4984. for filter in "${state_filters[@]}"; do
  4985. IFS="=" read -r key value <<<"$filter"
  4986. ## if not already in state_columns_raw
  4987. [[ " ${state_columns_raw[*]} " == *" $key "* ]] ||
  4988. filter_cols+=("$key")
  4989. done
  4990. for service in "${services_args[@]}"; do
  4991. declare -A values=()
  4992. for col in "${state_columns_raw[@]}" "${filter_cols[@]}"; do
  4993. case "$col" in
  4994. root)
  4995. if [[ " ${compose_yml_services[*]} " == *" ${service} "* ]]; then
  4996. value="1"
  4997. else
  4998. value="0"
  4999. fi
  5000. ;;
  5001. name) value="$service" ;;
  5002. charm)
  5003. value=$(get_service_charm "$service") || { echo 1; exit 1; }
  5004. ;;
  5005. state)
  5006. value=$(service:state "$service") || { echo 1; exit 1; }
  5007. ;;
  5008. type)
  5009. value=$(get_service_type "$service") || { echo 1; exit 1; }
  5010. ;;
  5011. *)
  5012. if has_service_action "$service" "get-$col" >/dev/null; then
  5013. state_msg=$(run_service_action "$service" "get-$col") || { echo 1; exit 1 ; }
  5014. if [[ "$state_msg" == *$'\n'* ]]; then
  5015. value="${state_msg%%$'\n'*}"
  5016. ## XXXvlab: For now, these are not used, but we could
  5017. ## display them in additional lines (in same "cell")
  5018. msgs="${state_msg#*$'\n'}"
  5019. else
  5020. value=${state_msg}
  5021. fi
  5022. else
  5023. value="N/A"
  5024. fi
  5025. ;;
  5026. esac
  5027. values["$col"]="$value"
  5028. done
  5029. for filter in "${state_filters[@]}"; do
  5030. IFS="=" read -r key value <<<"$filter"
  5031. [[ "${values[$key]}" != "$value" ]] &&
  5032. continue 2
  5033. done
  5034. for col in "${state_columns_raw[@]}"; do
  5035. p0 "${values[$col]}"
  5036. done
  5037. done | col-0:normalize:size "${state_columns_align}"
  5038. echo 0
  5039. )
  5040. if [ "$E" != 0 ]; then
  5041. echo "E: '$E'" >&2
  5042. exit 1
  5043. fi
  5044. exit 0
  5045. fi
  5046. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  5047. charm=$(get_service_charm "${services_args[0]}") || exit 1
  5048. metadata=$(charm.metadata "$charm") || exit 1
  5049. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  5050. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5051. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  5052. fi
  5053. fi
  5054. export SERVICE_PACK="${services_args[*]}"
  5055. ##
  5056. ## Docker-compose
  5057. ##
  5058. errlvl="0"
  5059. case "$action" in
  5060. up|start|stop|build|run)
  5061. ## force daemon mode for up
  5062. if [[ "$action" == "up" ]]; then
  5063. if ! array_member action_opts -d; then
  5064. action_opts+=("-d")
  5065. fi
  5066. if ! array_member action_opts --remove-orphans; then
  5067. action_opts+=("--remove-orphans")
  5068. fi
  5069. fi
  5070. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5071. ;;
  5072. logs)
  5073. if ! array_member action_opts --tail; then ## force daemon mode for up
  5074. action_opts+=("--tail" "10")
  5075. fi
  5076. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5077. ;;
  5078. "")
  5079. launch_docker_compose "${compose_opts[@]}"
  5080. ;;
  5081. graph)
  5082. graph $SERVICE_PACK
  5083. ;;
  5084. config)
  5085. ## removing the services
  5086. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  5087. ## forcing docker-compose config to output the config file to stdout and not stderr
  5088. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  5089. echo "$out"
  5090. exit 1
  5091. }
  5092. echo "$out"
  5093. warn "Runtime configuration modification (from relations) are not included here."
  5094. ;;
  5095. down)
  5096. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  5097. debug "Adding a default argument of '--remove-orphans'"
  5098. action_opts+=("--remove-orphans")
  5099. fi
  5100. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  5101. ;;
  5102. *)
  5103. if [ "$is_service_action" ]; then
  5104. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  5105. errlvl="$?"
  5106. errlvl "$errlvl"
  5107. else
  5108. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  5109. fi
  5110. ;;
  5111. esac || exit 1
  5112. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  5113. run_service_hook post_deploy "${services_args[@]}" || exit 1
  5114. fi
  5115. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  5116. if [ "$SERVICE_TYPE" == "run-once" ]; then
  5117. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  5118. fi
  5119. fi
  5120. case "$action" in
  5121. up)
  5122. ## Notify that services in 'deploying' states have been deployed
  5123. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/deploying; do
  5124. [ -e "$service" ] || continue
  5125. state=${service##*/}
  5126. service=${service%/$state}
  5127. service=${service##*/}
  5128. mv "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/{deploying,up} || exit 1
  5129. done
  5130. ## Notify that services in 'orphaning' states have been removed
  5131. for service in "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/orphaning; do
  5132. [ -e "$service" ] || continue
  5133. state=${service##*/}
  5134. service=${service%/$state}
  5135. service=${service##*/}
  5136. rm "$SERVICE_STATE_PATH/$PROJECT_NAME"/"${service}"/orphaning || exit 1
  5137. done
  5138. ;;
  5139. down)
  5140. PROJECT_NAME=$(get_default_project_name) || return 1
  5141. if [ -d "$SERVICE_STATE_PATH/$PROJECT_NAME" ]; then
  5142. if ! dir_is_empty "$SERVICE_STATE_PATH/$PROJECT_NAME"; then
  5143. rm -f "$SERVICE_STATE_PATH/$PROJECT_NAME"/*/*
  5144. fi
  5145. rmdir "$SERVICE_STATE_PATH/$PROJECT_NAME"/{*,}
  5146. fi
  5147. ;;
  5148. esac
  5149. clean_unused_docker_compose || exit 1
  5150. exit "$errlvl"