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.

5064 lines
169 KiB

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