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.

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