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.

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