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.

5595 lines
188 KiB

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