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.

6413 lines
218 KiB

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