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.

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