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.

5050 lines
168 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="$(cat "$cache_file")"
  1075. echo "$_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. print_syntax_error "$FUNCNAME is meant to be called after"\
  1170. "\$_current_docker_compose has been calculated."
  1171. fi
  1172. def=$(echo "$_current_docker_compose" | shyaml get-value "services.${service//./\\.}" 2>/dev/null)
  1173. if [ -z "$def" ]; then
  1174. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  1175. return 1
  1176. fi
  1177. echo "$def"
  1178. }
  1179. export -f get_service_def
  1180. get_build_hash() {
  1181. local dir="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$1")" hash
  1182. if [ -e "$cache_file" ]; then
  1183. # debug "$FUNCNAME: cache hit ($*)"
  1184. cat "$cache_file"
  1185. return 0
  1186. fi
  1187. ## Check that there's a Dockerfile in this directory
  1188. if [ ! -e "$dir/Dockerfile" ]; then
  1189. err "No 'Dockerfile' found in '$dir'."
  1190. return 1
  1191. fi
  1192. ## use find to md5sum all files in the directory and make a final hash
  1193. hash=$(set -o pipefail; cd "$dir"; env -i find "." -type f -exec md5sum {} \; |
  1194. sort | md5sum | awk '{print $1}') || {
  1195. err "Failed to get hash for '$dir'."
  1196. return 1
  1197. }
  1198. printf "%s" "$hash" | tee "$cache_file"
  1199. return $?
  1200. }
  1201. export -f get_build_hash
  1202. ### Query/Get cached image from registry
  1203. ##
  1204. ## Returns on stdout the name of the image if found, or an empty string if not
  1205. cache:image:registry:get() {
  1206. if [ -n "$COMPOSE_DOCKER_REGISTRY" ]; then
  1207. local charm="$1" hash="$2" service="$3"
  1208. local charm_image_name="cache/charm/$charm"
  1209. local charm_image="$charm_image_name:$hash"
  1210. Elt "pulling ${DARKPINK}$charm${NORMAL} image from $COMPOSE_DOCKER_REGISTRY" >&2
  1211. if out=$(docker pull "$COMPOSE_DOCKER_REGISTRY/$charm_image" 2>&1); then
  1212. docker tag "$COMPOSE_DOCKER_REGISTRY/$charm_image" "$charm_image" || {
  1213. err "Failed set image '$COMPOSE_DOCKER_REGISTRY/$charm_image' as '$charm_image'" \
  1214. "for ${DARKYELLOW}$service${NORMAL}."
  1215. return 1
  1216. }
  1217. print_info "found" >&2
  1218. print_status success >&2
  1219. Feed >&2
  1220. printf "%s" "$charm_image" | tee "$cache_file"
  1221. return $?
  1222. fi
  1223. if [[ "$out" != *"manifest unknown"* ]]; then
  1224. print_status failure >&2
  1225. Feed >&2
  1226. err "Failed to pull image '$COMPOSE_DOCKER_REGISTRY/$charm_image'" \
  1227. "for ${DARKYELLOW}$service${NORMAL}:"
  1228. e "$out" | prefix " ${GRAY}|${NORMAL} " >&2
  1229. return 1
  1230. fi
  1231. print_info "not found" >&2
  1232. if test "$type_method" = "long"; then
  1233. __status="[${NOOP}ABSENT${NORMAL}]"
  1234. else
  1235. echo -n "${NOOP}"
  1236. shift; shift;
  1237. echo -n "$*${NORMAL}"
  1238. fi >&2
  1239. Feed >&2
  1240. fi
  1241. }
  1242. export -f cache:image:registry:get
  1243. ### Store cached image on registry
  1244. ##
  1245. ## Returns nothing
  1246. cache:image:registry:put() {
  1247. if [ -n "$COMPOSE_DOCKER_REGISTRY" ] && [ -n "$COMPOSE_PUSH_TO_REGISTRY" ]; then
  1248. local charm="$1" hash="$2" service="$3"
  1249. local charm_image_name="cache/charm/$charm"
  1250. local charm_image="$charm_image_name:$hash"
  1251. Wrap -d "pushing ${DARKPINK}$charm${NORMAL} image to $COMPOSE_DOCKER_REGISTRY" <<EOF || return 1
  1252. docker tag "$charm_image" "$COMPOSE_DOCKER_REGISTRY/$charm_image" &&
  1253. docker push "$COMPOSE_DOCKER_REGISTRY/$charm_image"
  1254. EOF
  1255. fi >&2
  1256. }
  1257. export -f cache:image:registry:put
  1258. ### Produce docker cached charm image 'cache/charm/$charm:$hash'
  1259. ##
  1260. ## Either by fetching it from a registry or by building it from a
  1261. ## Dockerfile.
  1262. cache:image:produce() {
  1263. local type="$1" src="$2" charm="$3" hash="$4" service="$5"
  1264. local charm_image_name="cache/charm/$charm"
  1265. local charm_image="$charm_image_name:$hash"
  1266. case "$type" in
  1267. fetch)
  1268. local specified_image="$src"
  1269. ## will not pull upstream image if already present locally
  1270. if ! docker_has_image "${specified_image}"; then
  1271. if ! out=$(docker pull "${specified_image}" 2>&1); then
  1272. err "Failed to pull image '$specified_image' for ${DARKYELLOW}$service${NORMAL}:"
  1273. echo "$out" | prefix " | " >&2
  1274. return 1
  1275. fi
  1276. fi
  1277. # specified_image_id=$(docker_image_id "$specified_image") || return 1
  1278. # charm_image_id=
  1279. # if docker_has_image "${image_dst}"; then
  1280. # charm_image_id=$(docker_image_id "${image_dst}") || return 1
  1281. # fi
  1282. # if [ "$specified_image_id" != "$charm_image_id" ]; then
  1283. docker tag "$specified_image" "${charm_image}" || return 1
  1284. # fi
  1285. ;;
  1286. build)
  1287. local service_build="$src"
  1288. Wrap -v -d "Building ${DARKPINK}$charm${NORMAL}:$hash image" -- \
  1289. docker build "$service_build" -t "${charm_image}" >&2 || {
  1290. err "Failed to build image '${charm_image}' for ${DARKYELLOW}$service${NORMAL}."
  1291. return 1
  1292. }
  1293. ;;
  1294. *)
  1295. err "Unknown type '$type'."
  1296. return 1
  1297. ;;
  1298. esac
  1299. }
  1300. export -f cache:image:produce
  1301. service_ensure_image_ready() {
  1302. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1303. master_service service_def service_image service_build service_dockerfile image \
  1304. specified_image specified_image_id charm_image_name hash \
  1305. service_quoted
  1306. if [ -e "$cache_file" ]; then
  1307. #debug "$FUNCNAME: cache hit ($*)"
  1308. cat "$cache_file"
  1309. return 0
  1310. fi
  1311. if [ -z "$_CURRENT_DOCKER_COMPOSE" ]; then
  1312. err "${FUNCNAME[0]} is meant to be called after"\
  1313. "\$_CURRENT_DOCKER_COMPOSE has been calculated."
  1314. echo " Called by:" >&2
  1315. printf " - %s\n" "${FUNCNAME[@]:1}" >&2
  1316. return 1
  1317. fi
  1318. master_service="$(get_top_master_service_for_service "$service")" || {
  1319. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  1320. return 1
  1321. }
  1322. if [ "$master_service" != "$service" ]; then
  1323. image=$(service_ensure_image_ready "$master_service") || return 1
  1324. printf "%s" "$image" | tee "$cache_file"
  1325. return $?
  1326. fi
  1327. ## check if \$_CURRENT_DOCKER_COMPOSE's service def is already correctly setup
  1328. local charm="$(get_service_charm "$service")" || return 1
  1329. local charm_image_name="cache/charm/$charm" || return 1
  1330. local service_def="$(get_service_def "$service")" || {
  1331. err "Could not get docker-compose service definition for $DARKYELLOW$service$NORMAL."
  1332. return 1
  1333. }
  1334. local service_quoted=${service//./\\.}
  1335. if specified_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null); then
  1336. if [ "$specified_image" == "$charm_image_name"* ]; then
  1337. ## Assume we already did the change
  1338. printf "%s" "$specified_image" | tee "$cache_file"
  1339. return 0
  1340. fi
  1341. if [[ "$specified_image" == "${COMPOSE_DOCKER_REGISTRY}/"* ]]; then
  1342. if ! docker_has_image "${specified_image}"; then
  1343. Wrap "${wrap_opts[@]}" \
  1344. -v -d "pulling ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" -- \
  1345. docker pull "${specified_image}" >&2 || return 1
  1346. else
  1347. if [ -n "$DEBUG" ]; then
  1348. Elt "using local ${DARKPINK}$charm${NORMAL}'s specified image from $COMPOSE_DOCKER_REGISTRY" >&2
  1349. print_status noop >&2
  1350. Feed >&2
  1351. fi
  1352. fi
  1353. ## Already on the cache server
  1354. printf "%s" "$specified_image" | tee "$cache_file"
  1355. return 0
  1356. fi
  1357. src="$specified_image"
  1358. hash=$(echo "$specified_image" | md5sum | cut -f 1 -d " ") || return 1
  1359. type=fetch
  1360. ## replace image by charm image
  1361. yq -i ".services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1362. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1363. else
  1364. if ! src=$(echo "$service_def" | shyaml get-value build 2>/dev/null); then
  1365. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  1366. echo "$service_def" >&2
  1367. return 1
  1368. fi
  1369. ## According to https://stackoverflow.com/questions/32230577 , if there's a build,
  1370. ## then the built image will get name ${project}_${service}
  1371. hash=$(get_build_hash "$src") || return 1
  1372. type=build
  1373. ## delete build key from service_def and add image to charm_image_name
  1374. yq -i "del(.services.[\"${service_quoted}\"].build) |
  1375. .services.[\"${service_quoted}\"].image = \"${charm_image_name}:${hash}\"" \
  1376. "$_CURRENT_DOCKER_COMPOSE" || return 1
  1377. if docker_has_image "${charm_image_name}:${hash}"; then
  1378. if [ -n "$DEBUG" ]; then
  1379. Elt "using ${DARKPINK}$charm${NORMAL}'s image from local cache" >&2
  1380. print_status noop >&2
  1381. Feed >&2
  1382. fi
  1383. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1384. printf "%s" "${charm_image_name}:${hash}" | tee "$cache_file"
  1385. return $?
  1386. fi
  1387. fi
  1388. ## Can we pull it ? Let's check on $COMPOSE_DOCKER_REGISTRY
  1389. img=$(cache:image:registry:get "$charm" "$hash" "$service") || {
  1390. err "Failed to get image '$charm_image_name:$hash' from registry for ${DARKYELLOW}$service${NORMAL}."
  1391. return 1
  1392. }
  1393. [ -n "$img" ] && {
  1394. printf "%s" "$img" | tee "$cache_file"
  1395. return $?
  1396. }
  1397. cache:image:produce "$type" "$src" "$charm" "$hash" "$service" || return 1
  1398. cache:image:registry:put "$charm" "$hash" "$service" || return 1
  1399. printf "%s" "${charm_image_name}:$hash" | tee "$cache_file"
  1400. return $?
  1401. }
  1402. export -f service_ensure_image_ready
  1403. get_charm_relation_def () {
  1404. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1405. relation_def metadata
  1406. if [ -e "$cache_file" ]; then
  1407. # debug "$FUNCNAME: cache hit ($*)"
  1408. cat "$cache_file"
  1409. return 0
  1410. fi
  1411. metadata="$(charm.metadata "$charm")" || return 1
  1412. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  1413. echo "$relation_def" | tee "$cache_file"
  1414. }
  1415. export -f get_charm_relation_def
  1416. get_charm_tech_dep_orientation_for_relation() {
  1417. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1418. relation_def value
  1419. if [ -e "$cache_file" ]; then
  1420. # debug "$FUNCNAME: cache hit ($*)"
  1421. cat "$cache_file"
  1422. return 0
  1423. fi
  1424. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  1425. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1426. value=${value:-True}
  1427. printf "%s" "$value" | tee "$cache_file"
  1428. }
  1429. export -f get_charm_tech_dep_orientation_for_relation
  1430. get_service_relation_tech_dep() {
  1431. local service="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1432. charm tech_dep
  1433. if [ -e "$cache_file" ]; then
  1434. # debug "$FUNCNAME: cache hit ($*)"
  1435. cat "$cache_file"
  1436. return 0
  1437. fi
  1438. charm=$(get_service_charm "$service") || return 1
  1439. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$charm" "$relation_name")" || return 1
  1440. printf "%s" "$tech_dep" | tee "$cache_file"
  1441. }
  1442. export -f get_service_relation_tech_dep
  1443. ##
  1444. ## Use compose file to get deps, and relation definition in metadata.yml
  1445. ## for tech-dep attribute.
  1446. get_service_deps() {
  1447. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")"
  1448. if [ -e "$cache_file" ]; then
  1449. # debug "$FUNCNAME: cache hit ($*)"
  1450. cat "$cache_file"
  1451. return 0
  1452. fi
  1453. (
  1454. set -o pipefail
  1455. get_service_relations "$service" | \
  1456. while read-0 relation_name target_service _relation_config tech_dep; do
  1457. echo "$target_service"
  1458. done | tee "$cache_file"
  1459. ) || return 1
  1460. }
  1461. export -f get_service_deps
  1462. ## XXXvlab: cache was disabled because improper. Indeed, this needs to cache
  1463. ## 'depths' full state. Second, it should be
  1464. _rec_get_depth() {
  1465. local elt=$1 dep deps max
  1466. [ "${depths[$elt]}" ] && return 0
  1467. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -pA depths)" "$ALL_RELATIONS")"
  1468. if [ -e "$cache_file.depths" ]; then
  1469. #debug "$FUNCNAME: cache hit ($*) - $cache_file.depths"
  1470. while read-0 k v; do
  1471. depths["$k"]="$v"
  1472. done < "$cache_file.depths"
  1473. while read-0 k v; do
  1474. visited["$k"]="$v"
  1475. done < "$cache_file.visited"
  1476. return 0
  1477. fi
  1478. visited[$elt]=1
  1479. #debug "Setting visited[$elt]"
  1480. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1481. deps=$(get_service_deps "$elt") || {
  1482. debug "Failed get_service_deps $elt"
  1483. return 1
  1484. }
  1485. # debug "$elt deps are:" $deps
  1486. max=0
  1487. for dep in $deps; do
  1488. [ "${visited[$dep]}" ] && {
  1489. #debug "Already computing $dep"
  1490. continue
  1491. }
  1492. _rec_get_depth "$dep" || return 1
  1493. #debug "Requesting depth[$dep]"
  1494. if (( ${depths[$dep]} > max )); then
  1495. max="${depths[$dep]}"
  1496. fi
  1497. done
  1498. # debug "Setting depth[$elt] to $((max + 1))"
  1499. depths[$elt]=$((max + 1))
  1500. array_kv_to_stdin depths > "$cache_file.depths"
  1501. array_kv_to_stdin visited > "$cache_file.visited"
  1502. # debug "DEPTHS: $(declare -pA depths)"
  1503. # debug "$FUNCNAME: caching hit ($*) - $cache_file"
  1504. }
  1505. export -f _rec_get_depth
  1506. get_ordered_service_dependencies() {
  1507. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")" \
  1508. i value key heads depths visited
  1509. if [ -e "$cache_file" ]; then
  1510. # debug "$FUNCNAME: cache hit ($*)"
  1511. cat "$cache_file"
  1512. return 0
  1513. fi
  1514. #debug "Figuring ordered deps of $DARKYELLOW${services[@]}$NORMAL"
  1515. if [ -z "${services[*]}" ]; then
  1516. return 0
  1517. # print_syntax_error "$FUNCNAME: no arguments"
  1518. # return 1
  1519. fi
  1520. declare -A depths
  1521. declare -A visited
  1522. heads=("${services[@]}")
  1523. while [ "${#heads[@]}" != 0 ]; do
  1524. array_pop heads head
  1525. _rec_get_depth "$head" || return 1
  1526. done
  1527. i=0
  1528. while [ "${#depths[@]}" != 0 ]; do
  1529. for key in "${!depths[@]}"; do
  1530. value="${depths[$key]}"
  1531. if [ "$value" == "$i" ]; then
  1532. echo "$key"
  1533. unset depths[$key]
  1534. fi
  1535. done
  1536. ((i++))
  1537. done | tee "$cache_file"
  1538. }
  1539. export -f get_ordered_service_dependencies
  1540. run_service_acquire_images () {
  1541. local service subservice subservices loaded
  1542. declare -A loaded
  1543. for service in "$@"; do
  1544. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1545. for subservice in $subservices; do
  1546. if [ "${loaded[$subservice]}" ]; then
  1547. ## Prevent double inclusion of same service if this
  1548. ## service is deps of two or more of your
  1549. ## requirements.
  1550. continue
  1551. fi
  1552. type=$(get_service_type "$subservice") || return 1
  1553. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1554. if [ "$type" != "stub" ]; then
  1555. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1556. fi
  1557. loaded[$subservice]=1
  1558. done
  1559. done
  1560. return 0
  1561. }
  1562. run_service_hook () {
  1563. local action="$1" service subservice subservices loaded
  1564. shift
  1565. declare -A loaded
  1566. for service in "$@"; do
  1567. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1568. for subservice in $subservices; do
  1569. if [ "${loaded[$subservice]}" ]; then
  1570. ## Prevent double inclusion of same service if this
  1571. ## service is deps of two or more of your
  1572. ## requirements.
  1573. continue
  1574. fi
  1575. charm=$(get_service_charm "$subservice") || return 1
  1576. charm.has_hook "$charm" "$action" >/dev/null || continue
  1577. type=$(get_service_type "$subservice") || return 1
  1578. PROJECT_NAME=$(get_default_project_name) || return 1
  1579. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1580. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1581. if [ "$type" != "stub" ]; then
  1582. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$MASTER_BASE_SERVICE_NAME") || return 1
  1583. fi
  1584. Wrap "${wrap_opts[@]}" -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1585. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1586. export SERVICE_NAME=$subservice
  1587. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1588. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1589. export CHARM_NAME="$charm"
  1590. export PROJECT_NAME="$PROJECT_NAME"
  1591. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1592. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1593. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1594. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1595. charm.run_hook "local" "$charm" "$action"
  1596. EOF
  1597. loaded[$subservice]=1
  1598. done
  1599. done
  1600. return 0
  1601. }
  1602. host_resource_get() {
  1603. local location="$1" cfg="$2"
  1604. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1605. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1606. return 1
  1607. }
  1608. if fn.exists host_resource_get_$type; then
  1609. host_resource_get_$type "$location" "$cfg"
  1610. else
  1611. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1612. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1613. "$DARKYELLOW$subservice$NORMAL config."
  1614. return 1
  1615. fi
  1616. }
  1617. export -f host_resource_get
  1618. host_resource_get_git() {
  1619. local location="$1" cfg="$2" branch parent url
  1620. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1621. branch=${branch:-master}
  1622. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1623. parent="$(dirname "$location")"
  1624. (
  1625. mkdir -p "$parent" && cd "$parent" &&
  1626. git clone -b "$branch" "$url" "$(basename "$location")"
  1627. ) || return 1
  1628. }
  1629. export -f host_resource_get_git
  1630. host_resource_get_git-sub() {
  1631. local location="$1" cfg="$2" branch parent url
  1632. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1633. branch=${branch:-master}
  1634. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1635. parent="$(dirname "$location")"
  1636. (
  1637. mkdir -p "$parent" && cd "$parent" &&
  1638. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1639. ) || return 1
  1640. }
  1641. export -f host_resource_get_git-sub
  1642. setup_host_resource () {
  1643. local subservice="$1" service_def location get cfg
  1644. service_def=$(get_compose_service_def "$subservice") || return 1
  1645. while read-0 location cfg; do
  1646. ## XXXvlab: will it be a git resources always ?
  1647. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1648. err "Hum, location '$location' does not seem to be a git directory."
  1649. return 1
  1650. fi
  1651. if [ -d "$location" ]; then
  1652. info "host resource '$location' already set up."
  1653. continue
  1654. fi
  1655. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1656. if [ -z "$get" ]; then
  1657. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1658. "specified for $DARKYELLOW$subservice$NORMAL."
  1659. return 1
  1660. fi
  1661. host_resource_get "$location" "$get" || return 1
  1662. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1663. }
  1664. export -f setup_host_resource
  1665. setup_host_resources () {
  1666. local service subservices subservice loaded
  1667. declare -A loaded
  1668. for service in "$@"; do
  1669. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1670. for subservice in $subservices; do
  1671. if [ "${loaded[$subservice]}" ]; then
  1672. ## Prevent double inclusion of same service if this
  1673. ## service is deps of two or more of your
  1674. ## requirements.
  1675. continue
  1676. fi
  1677. setup_host_resource "$subservice" || return 1
  1678. loaded[$subservice]=1
  1679. done
  1680. done
  1681. return 0
  1682. }
  1683. export -f setup_host_resources
  1684. ## Works on stdin
  1685. cfg-get-value () {
  1686. local key="$1" out
  1687. if [ -z "$key" ]; then
  1688. yaml_get_interpret || return 1
  1689. return 0
  1690. fi
  1691. if ! out=$(shyaml -y get-value "$key" 2>/dev/null); then
  1692. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1693. return 1
  1694. fi
  1695. printf "%s\n" "$out" | yaml_get_interpret
  1696. }
  1697. export -f cfg-get-value
  1698. relation-get () {
  1699. cfg-get-value "$1" < "$RELATION_DATA_FILE"
  1700. }
  1701. export -f relation-get
  1702. expand_vars() {
  1703. local unlikely_prefix="UNLIKELY_PREFIX"
  1704. content=$(cat -)
  1705. ## find first identifier not in content
  1706. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1707. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1708. size_prefix="${#unlikely_prefix}"
  1709. first_matching=$(echo "$remaining_lines" |
  1710. grep -v "^$unlikely_prefix$" |
  1711. uniq -w "$((size_prefix + 1))" -c |
  1712. sort -rn |
  1713. head -n 1)
  1714. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1715. first_matching="${first_matching#* }"
  1716. next_char=${first_matching:$size_prefix:1}
  1717. if [ "$next_char" != "0" ]; then
  1718. unlikely_prefix+="0"
  1719. else
  1720. unlikely_prefix+="1"
  1721. fi
  1722. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1723. done
  1724. eval "cat <<$unlikely_prefix
  1725. $content
  1726. $unlikely_prefix"
  1727. }
  1728. export -f expand_vars
  1729. yaml_get_interpret() {
  1730. local content tag
  1731. content=$(cat -)
  1732. tag=$(echo "$content" | shyaml get-type) || return 1
  1733. content=$(echo "$content" | shyaml get-value) || return 1
  1734. if ! [ "${tag:0:1}" == "!" ]; then
  1735. echo "$content" || return 1
  1736. return 0
  1737. fi
  1738. case "$tag" in
  1739. "!bash-stdout")
  1740. echo "$content" | bash || {
  1741. err "shell code didn't end with errorlevel 0"
  1742. return 1
  1743. }
  1744. ;;
  1745. "!var-expand")
  1746. echo "$content" | expand_vars || {
  1747. err "shell expansion failed"
  1748. return 1
  1749. }
  1750. ;;
  1751. "!file-content")
  1752. source=$(echo "$content" | expand_vars) || {
  1753. err "shell expansion failed"
  1754. return 1
  1755. }
  1756. cat "$source" || return 1
  1757. ;;
  1758. *)
  1759. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1760. return 1
  1761. ;;
  1762. esac
  1763. }
  1764. export -f yaml_get_interpret
  1765. options-get () {
  1766. local key="$1" out
  1767. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1768. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1769. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1770. return 1
  1771. fi
  1772. echo "$out" | yaml_get_interpret
  1773. }
  1774. export -f options-get
  1775. relation-base-compose-get () {
  1776. local key="$1" out
  1777. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1778. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1779. return 1
  1780. fi
  1781. echo "$out" | yaml_get_interpret
  1782. }
  1783. export -f relation-base-compose-get
  1784. relation-target-compose-get () {
  1785. local key="$1" out
  1786. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1787. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1788. return 1
  1789. fi
  1790. echo "$out" | yaml_get_interpret
  1791. }
  1792. export -f relation-target-compose-get
  1793. relation-set () {
  1794. local key="$1" value="$2"
  1795. if [ -z "$RELATION_DATA_FILE" ]; then
  1796. err "$FUNCNAME: relation does not seems to be correctly setup."
  1797. return 1
  1798. fi
  1799. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1800. err "$FUNCNAME: can't read relation's data." >&2
  1801. return 1
  1802. fi
  1803. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1804. }
  1805. export -f relation-set
  1806. _config_merge() {
  1807. local config_filename="$1" mixin="$2"
  1808. touch "$config_filename" &&
  1809. merge_yaml "$config_filename" "$mixin" > "$config_filename.tmp" || return 1
  1810. mv "$config_filename.tmp" "$config_filename"
  1811. }
  1812. export -f _config_merge
  1813. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1814. config-add() {
  1815. local metadata="$1"
  1816. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1817. }
  1818. export -f config-add
  1819. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1820. init-config-add() {
  1821. local metadata="$1"
  1822. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1823. <(yaml_key_val_str "services" "$metadata")
  1824. }
  1825. export -f init-config-add
  1826. docker_get_uid() {
  1827. local service="$1" user="$2" uid
  1828. uid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"") || {
  1829. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1830. return 1
  1831. }
  1832. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid'"
  1833. echo "$uid"
  1834. }
  1835. export -f docker_get_uid
  1836. docker_get_uid_gid() {
  1837. local service="$1" user="$2" group="$3" uid
  1838. uid_gid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"; id -g \"$group\"") || {
  1839. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1840. return 1
  1841. }
  1842. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid_gid'"
  1843. echo "$uid_gid"
  1844. }
  1845. export -f docker_get_uid_gid
  1846. logstdout() {
  1847. local name="$1"
  1848. sed -r 's%^%'"${name}"'> %g'
  1849. }
  1850. export -f logstdout
  1851. logstderr() {
  1852. local name="$1"
  1853. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1854. }
  1855. export -f logstderr
  1856. _run_service_relation () {
  1857. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1858. local errlvl
  1859. charm=$(get_service_charm "$service") || return 1
  1860. target_charm=$(get_service_charm "$target_service") || return 1
  1861. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1862. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1863. [ -n "$base_script_name" ] || [ -n "$target_script_name" ] || return 0
  1864. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1865. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1866. export BASE_SERVICE_NAME=$service
  1867. export BASE_CHARM_NAME=$charm
  1868. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1869. export TARGET_SERVICE_NAME=$target_service
  1870. export TARGET_CHARM_NAME=$target_charm
  1871. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1872. export RELATION_DATA_FILE
  1873. target_errlvl=0
  1874. if [ -z "$target_script_name" ]; then
  1875. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1876. else
  1877. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1878. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1879. RELATION_CONFIG="$relation_dir/config_provider"
  1880. type=$(get_service_type "$target_service") || return 1
  1881. if [ "$type" != "stub" ]; then
  1882. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$target_service") || return 1
  1883. fi
  1884. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1885. {
  1886. (
  1887. SERVICE_NAME=$target_service
  1888. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1889. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1890. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1891. charm.run_relation_hook local "$target_charm" "$relation_name" relation-joined
  1892. echo "$?" > "$relation_dir/target_errlvl"
  1893. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1894. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1895. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1896. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1897. "failed before outputing an errorlevel."
  1898. ((target_errlvl |= "1" ))
  1899. }
  1900. if [ -e "$RELATION_CONFIG" ]; then
  1901. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1902. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1903. rm "$RELATION_CONFIG"
  1904. ((target_errlvl |= "$?"))
  1905. fi
  1906. fi
  1907. if [ "$target_errlvl" == 0 ]; then
  1908. errlvl=0
  1909. if [ "$base_script_name" ]; then
  1910. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1911. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1912. RELATION_CONFIG="$relation_dir/config_providee"
  1913. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1914. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$service") || return 1
  1915. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1916. {
  1917. (
  1918. SERVICE_NAME=$service
  1919. SERVICE_DATASTORE="$DATASTORE/$service"
  1920. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1921. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1922. charm.run_relation_hook local "$charm" "$relation_name" relation-joined
  1923. echo "$?" > "$relation_dir/errlvl"
  1924. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1925. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1926. errlvl="$(cat "$relation_dir/errlvl")" || {
  1927. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1928. "failed before outputing an errorlevel."
  1929. ((errlvl |= "1" ))
  1930. }
  1931. if [ -e "$RELATION_CONFIG" ]; then
  1932. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1933. rm "$RELATION_CONFIG"
  1934. ((errlvl |= "$?" ))
  1935. fi
  1936. if [ "$errlvl" != 0 ]; then
  1937. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1938. fi
  1939. else
  1940. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1941. fi
  1942. else
  1943. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1944. fi
  1945. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1946. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1947. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1948. return 0
  1949. else
  1950. return 1
  1951. fi
  1952. }
  1953. export -f _run_service_relation
  1954. _get_compose_relations_cached () {
  1955. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1956. relation_name relation_def target_service
  1957. if [ -e "$cache_file" ]; then
  1958. #debug "$FUNCNAME: STATIC cache hit $1"
  1959. cat "$cache_file" &&
  1960. touch "$cache_file" || return 1
  1961. return 0
  1962. fi
  1963. (
  1964. set -o pipefail
  1965. if [ "$compose_service_def" ]; then
  1966. while read-0 relation_name relation_def; do
  1967. ## XXXvlab: could we use braces here instead of parenthesis ?
  1968. (
  1969. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1970. "str")
  1971. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  1972. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1973. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1974. ;;
  1975. "sequence")
  1976. while read-0 target_service; do
  1977. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1978. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1979. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1980. ;;
  1981. "struct")
  1982. while read-0 target_service relation_config; do
  1983. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1984. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  1985. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1986. ;;
  1987. esac
  1988. ) </dev/null >> "$cache_file" || return 1
  1989. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1990. fi
  1991. )
  1992. if [ "$?" != 0 ]; then
  1993. err "Error while looking for compose relations."
  1994. rm -f "$cache_file" ## no cache
  1995. return 1
  1996. fi
  1997. [ -e "$cache_file" ] && cat "$cache_file"
  1998. return 0
  1999. }
  2000. export -f _get_compose_relations_cached
  2001. get_compose_relations () {
  2002. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2003. compose_def
  2004. if [ -e "$cache_file" ]; then
  2005. #debug "$FUNCNAME: SESSION cache hit $1"
  2006. cat "$cache_file"
  2007. return 0
  2008. fi
  2009. compose_def="$(get_compose_service_def "$service")" || return 1
  2010. _get_compose_relations_cached "$compose_def" > "$cache_file"
  2011. if [ "$?" != 0 ]; then
  2012. rm -f "$cache_file" ## no cache
  2013. return 1
  2014. fi
  2015. cat "$cache_file"
  2016. }
  2017. export -f get_compose_relations
  2018. get_all_services() {
  2019. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$ALL_RELATIONS")" \
  2020. s rn ts rc td services
  2021. if [ -e "$cache_file" ]; then
  2022. #debug "$FUNCNAME: SESSION cache hit $1"
  2023. cat "$cache_file"
  2024. return 0
  2025. fi
  2026. if [ -z "$ALL_RELATIONS" ]; then
  2027. err "Can't access global \$ALL_RELATIONS"
  2028. return 1
  2029. fi
  2030. declare -A services
  2031. while read-0 s _ ts _ _; do
  2032. for service in "$s" "$ts"; do
  2033. [ "${services[$service]}" ] && continue
  2034. services["$service"]=1
  2035. echo "$service"
  2036. done
  2037. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  2038. cat "$cache_file"
  2039. }
  2040. export -f get_all_services
  2041. get_service_relations () {
  2042. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")" \
  2043. s rn ts rc td
  2044. if [ -e "$cache_file" ]; then
  2045. #debug "$FUNCNAME: SESSION cache hit $1"
  2046. cat "$cache_file"
  2047. return 0
  2048. fi
  2049. if [ -z "$ALL_RELATIONS" ]; then
  2050. err "Can't access global \$ALL_RELATIONS"
  2051. return 1
  2052. fi
  2053. while read-0 s rn ts rc td; do
  2054. [[ "$s" == "$service" ]] || continue
  2055. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  2056. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  2057. cat "$cache_file"
  2058. }
  2059. export -f get_service_relations
  2060. get_service_relation() {
  2061. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  2062. rn ts rc td
  2063. if [ -e "$cache_file" ]; then
  2064. #debug "$FUNCNAME: SESSION cache hit $1"
  2065. cat "$cache_file"
  2066. return 0
  2067. fi
  2068. while read-0 rn ts rc td; do
  2069. [ "$relation" == "$rn" ] && {
  2070. printf "%s\0" "$ts" "$rc" "$td"
  2071. break
  2072. }
  2073. done < <(get_service_relations "$service") > "$cache_file"
  2074. if [ "$?" != 0 ]; then
  2075. rm -f "$cache_file" ## no cache
  2076. return 1
  2077. fi
  2078. cat "$cache_file"
  2079. }
  2080. export -f get_service_relation
  2081. ## From a service and a relation, get all relations targeting given
  2082. ## service with given relation.
  2083. ##
  2084. ## Returns a NUL separated list of couple of:
  2085. ## (base_service, relation_config)
  2086. ##
  2087. get_service_incoming_relations() {
  2088. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")" \
  2089. s rn ts rc td
  2090. if [ -e "$cache_file" ]; then
  2091. #debug "$FUNCNAME: SESSION cache hit $1"
  2092. cat "$cache_file"
  2093. return 0
  2094. fi
  2095. if [ -z "$ALL_RELATIONS" ]; then
  2096. err "Can't access global \$ALL_RELATIONS"
  2097. return 1
  2098. fi
  2099. while read-0 s rn ts rc _td; do
  2100. [[ "$ts" == "$service" ]] || continue
  2101. [[ "$rn" == "$relation" ]] || continue
  2102. relation_data_file=$(get_relation_data_file "$s" "$ts" "$rn" "$rc") || return 1
  2103. printf "%s\0" "$s" "$(cat "$relation_data_file")"
  2104. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  2105. cat "$cache_file"
  2106. }
  2107. export -f get_service_incoming_relations
  2108. export TRAVERSE_SEPARATOR=:
  2109. ## Traverse on first service satisfying relation
  2110. service:traverse() {
  2111. local service_path="$1"
  2112. {
  2113. SEPARATOR=:
  2114. read -d "$TRAVERSE_SEPARATOR" service
  2115. while read -d "$TRAVERSE_SEPARATOR" relation; do
  2116. ## XXXvlab: Take only first service
  2117. if ! read-0 ts _ _ < <(get_service_relation "${service}" "${relation}"); then
  2118. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2119. "from ${DARKYELLOW}$service${NORMAL}."
  2120. return 1
  2121. fi
  2122. service="$ts"
  2123. done
  2124. echo "$service"
  2125. } < <(e "${service_path}${TRAVERSE_SEPARATOR}")
  2126. }
  2127. export -f service:traverse
  2128. service:relation-file() {
  2129. local service_path="$1" relation service relation_file
  2130. if ! [[ "$service_path" == *"$TRAVERSE_SEPARATOR"* ]]; then
  2131. err "Invalid argument '$service_path'." \
  2132. "Must provide a service path (no '${TRAVERSE_SEPARATOR}' found)."
  2133. return 1
  2134. fi
  2135. relation="${service_path##*${TRAVERSE_SEPARATOR}}"
  2136. service=$(service:traverse "${service_path%${TRAVERSE_SEPARATOR}*}") || return 1
  2137. if ! read-0 ts rc _ < <(get_service_relation "${service}" "${relation}"); then
  2138. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  2139. "from ${DARKYELLOW}$service${NORMAL}."
  2140. return 1
  2141. fi
  2142. relation_dir=$(get_relation_data_dir "$service" "$ts" "$relation") || {
  2143. err "Failed to find relation file"
  2144. return 1
  2145. }
  2146. relation_file="$relation_dir/data"
  2147. if ! [ -e "$relation_file" ]; then
  2148. e "$rc" > "$relation_file"
  2149. chmod go-rwx "$relation_file" ## protecting this file
  2150. fi
  2151. echo "$relation_file"
  2152. }
  2153. export -f service:relation-file
  2154. service:relation-options() {
  2155. local service_path="$1" relation_file
  2156. relation_file=$(service:relation-file "$service_path") || {
  2157. err "Failed to find relation file"
  2158. return 1
  2159. }
  2160. cat "$relation_file"
  2161. }
  2162. export -f service:relation-options
  2163. relation:get() {
  2164. local service_path="$1" query="$2" relation_file
  2165. relation_file=$(service:relation-file "$service_path") || {
  2166. err "Failed to find relation file"
  2167. return 1
  2168. }
  2169. cfg-get-value "$query" < "$relation_file"
  2170. }
  2171. export -f relation:get
  2172. _get_charm_metadata_uses() {
  2173. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2174. if [ -e "$cache_file" ]; then
  2175. #debug "$FUNCNAME: SESSION cache hit $1"
  2176. cat "$cache_file" || return 1
  2177. return 0
  2178. fi
  2179. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  2180. }
  2181. export -f _get_charm_metadata_uses
  2182. _get_service_metadata() {
  2183. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2184. charm
  2185. if [ -e "$cache_file" ]; then
  2186. #debug "$FUNCNAME: SESSION cache hit $1"
  2187. cat "$cache_file"
  2188. return 0
  2189. fi
  2190. charm="$(get_service_charm "$service")" || return 1
  2191. charm.metadata "$charm" > "$cache_file"
  2192. if [ "$?" != 0 ]; then
  2193. rm -f "$cache_file" ## no cache
  2194. return 1
  2195. fi
  2196. cat "$cache_file"
  2197. }
  2198. export -f _get_service_metadata
  2199. _get_service_uses() {
  2200. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2201. metadata
  2202. if [ -e "$cache_file" ]; then
  2203. #debug "$FUNCNAME: SESSION cache hit $1"
  2204. cat "$cache_file"
  2205. return 0
  2206. fi
  2207. metadata="$(_get_service_metadata "$service")" || return 1
  2208. _get_charm_metadata_uses "$metadata" > "$cache_file"
  2209. if [ "$?" != 0 ]; then
  2210. rm -f "$cache_file" ## no cache
  2211. return 1
  2212. fi
  2213. cat "$cache_file"
  2214. }
  2215. export -f _get_service_uses
  2216. _get_services_uses() {
  2217. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2218. service rn rd
  2219. if [ -e "$cache_file" ]; then
  2220. #debug "$FUNCNAME: SESSION cache hit $1"
  2221. cat "$cache_file"
  2222. return 0
  2223. fi
  2224. for service in "$@"; do
  2225. _get_service_uses "$service" | while read-0 rn rd; do
  2226. printf "%s\0" "$service" "$rn" "$rd"
  2227. done
  2228. [ "${PIPESTATUS[0]}" == 0 ] || {
  2229. return 1
  2230. }
  2231. done > "${cache_file}.wip"
  2232. mv "${cache_file}"{.wip,} &&
  2233. cat "$cache_file" || return 1
  2234. }
  2235. export -f _get_services_uses
  2236. _get_provides_provides() {
  2237. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2238. service rn rd
  2239. if [ -e "$cache_file" ]; then
  2240. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  2241. cat "$cache_file"
  2242. return 0
  2243. fi
  2244. type=$(printf "%s" "$provides" | shyaml get-type)
  2245. case "$type" in
  2246. sequence)
  2247. while read-0 prov; do
  2248. printf "%s\0" "$prov" ""
  2249. done < <(echo "$provides" | shyaml get-values-0)
  2250. ;;
  2251. struct)
  2252. printf "%s" "$provides" | shyaml key-values-0
  2253. ;;
  2254. str)
  2255. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  2256. ;;
  2257. *)
  2258. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  2259. return 1
  2260. esac | tee "$cache_file"
  2261. return "${PIPESTATUS[0]}"
  2262. }
  2263. _get_metadata_provides() {
  2264. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2265. service rn rd
  2266. if [ -e "$cache_file" ]; then
  2267. #debug "$FUNCNAME: CACHEDIR cache hit"
  2268. cat "$cache_file"
  2269. return 0
  2270. fi
  2271. provides=$(printf "%s" "$metadata" | shyaml -q get-value -y provides "")
  2272. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  2273. _get_provides_provides "$provides" | tee "$cache_file"
  2274. return "${PIPESTATUS[0]}"
  2275. }
  2276. _get_services_provides() {
  2277. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2278. service rn rd
  2279. if [ -e "$cache_file" ]; then
  2280. #debug "$FUNCNAME: SESSION cache hit $1"
  2281. cat "$cache_file"
  2282. return 0
  2283. fi
  2284. ## YYY: replace the inner loop by a cached function
  2285. for service in "$@"; do
  2286. metadata="$(_get_service_metadata "$service")" || return 1
  2287. while read-0 rn rd; do
  2288. printf "%s\0" "$service" "$rn" "$rd"
  2289. done < <(_get_metadata_provides "$metadata")
  2290. done > "$cache_file"
  2291. if [ "$?" != 0 ]; then
  2292. rm -f "$cache_file" ## no cache
  2293. return 1
  2294. fi
  2295. cat "$cache_file"
  2296. }
  2297. export -f _get_services_provides
  2298. _get_charm_provides() {
  2299. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(charm.store_metadata_hash)" errlvl
  2300. if [ -e "$cache_file" ]; then
  2301. #debug "$FUNCNAME: SESSION cache hit"
  2302. cat "$cache_file"
  2303. return 0
  2304. fi
  2305. start="$SECONDS"
  2306. debug "Getting charm provider list..."
  2307. while read-0 charm _ realpath metadata; do
  2308. metadata="$(charm.metadata "$charm")" || continue
  2309. # echo "reading $charm" >&2
  2310. while read-0 rn rd; do
  2311. printf "%s\0" "$charm" "$rn" "$rd"
  2312. done < <(_get_metadata_provides "$metadata")
  2313. done < <(charm.ls) | tee "$cache_file"
  2314. errlvl="${PIPESTATUS[0]}"
  2315. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  2316. return "$errlvl"
  2317. }
  2318. _get_charm_providing() {
  2319. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2320. relation="$1"
  2321. if [ -e "$cache_file" ]; then
  2322. #debug "$FUNCNAME: SESSION cache hit $1"
  2323. cat "$cache_file"
  2324. return 0
  2325. fi
  2326. while read-0 charm relation_name relation_def; do
  2327. [ "$relation_name" == "$relation" ] || continue
  2328. printf "%s\0" "$charm" "$relation_def"
  2329. done < <(_get_charm_provides) > "$cache_file"
  2330. if [ "$?" != 0 ]; then
  2331. rm -f "$cache_file" ## no cache
  2332. return 1
  2333. fi
  2334. cat "$cache_file"
  2335. }
  2336. _get_services_providing() {
  2337. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2338. relation="$1"
  2339. shift ## services is "$@"
  2340. if [ -e "$cache_file" ]; then
  2341. #debug "$FUNCNAME: SESSION cache hit $1"
  2342. cat "$cache_file"
  2343. return 0
  2344. fi
  2345. while read-0 service relation_name relation_def; do
  2346. [ "$relation_name" == "$relation" ] || continue
  2347. printf "%s\0" "$service" "$relation_def"
  2348. done < <(_get_services_provides "$@") > "$cache_file"
  2349. if [ "$?" != 0 ]; then
  2350. rm -f "$cache_file" ## no cache
  2351. return 1
  2352. fi
  2353. cat "$cache_file"
  2354. }
  2355. export -f _get_services_provides
  2356. _out_new_relation_from_defs() {
  2357. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  2358. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2359. ## YYYvlab: should be seen even in no debug mode no ?
  2360. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2361. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  2362. td=${td:-True}
  2363. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  2364. after=$(_out_after_value_from_def "$service" "$rn" "$rel_def") || return 1
  2365. printf "%s\0" "$after" "$service" "$relation_name" "$ts" "$rc" "$td"
  2366. }
  2367. _out_after_value_from_def() {
  2368. local service="$1" relation_name="$2" relation_def="$3" after_t after
  2369. if after_t=$(echo "$relation_def" | shyaml get-type after 2>/dev/null); then
  2370. case "$after_t" in
  2371. sequence)
  2372. after="$(echo "$relation_def" | shyaml get-values after 2>/dev/null)" || return 1
  2373. after=",$service:${after//$'\n'/,$service:},"
  2374. ;;
  2375. struct)
  2376. err "Invalid type for ${WHITE}after${NORMAL}'s value in ${DARKBLUE}$relation_name${NORMAL}'s definition."
  2377. return 1
  2378. ;;
  2379. str)
  2380. after=",$service:$(echo "$relation_def" | shyaml get-value after "" 2>/dev/null)," || return 1
  2381. ;;
  2382. esac
  2383. else
  2384. after=""
  2385. fi
  2386. e "$after"
  2387. }
  2388. get_all_relations () {
  2389. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -p without_relations)")" \
  2390. services
  2391. if [ -n "$ALL_RELATIONS" ]; then
  2392. cat "$ALL_RELATIONS" || return 1
  2393. return 0
  2394. fi
  2395. if [ -e "${cache_file}" ]; then
  2396. #debug "$FUNCNAME: SESSION cache hit $1"
  2397. export ALL_RELATIONS="$cache_file"
  2398. cat "${cache_file}"
  2399. return 0
  2400. fi
  2401. declare -A services
  2402. services_uses=()
  2403. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2404. _get_services_uses "$@" || return 1
  2405. array_read-0 services_uses < <(_get_services_uses "$@")
  2406. services_provides=()
  2407. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2408. _get_services_provides "$@" || return 1
  2409. array_read-0 services_provides < <(_get_services_provides "$@")
  2410. for service in "$@"; do
  2411. services[$service]=1
  2412. done
  2413. all_services=("$@")
  2414. while [ "${#all_services[@]}" != 0 ]; do
  2415. array_pop all_services service
  2416. while read-0 relation_name ts relation_config tech_dep; do
  2417. [ "${without_relations[$service:$relation_name]}" ] && {
  2418. debug "Ignoring compose $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> ${DARKYELLOW}$ts$NORMAL"
  2419. continue
  2420. }
  2421. ## First is priority, that can be adjusted in second step
  2422. printf "%s\0" "" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  2423. ## adding target services ?
  2424. [ "${services[$ts]}" ] && continue
  2425. array_read-0 services_uses < <(_get_services_uses "$ts")
  2426. all_services+=("$ts")
  2427. services[$ts]=1
  2428. done < <(get_compose_relations "$service")
  2429. done > "${cache_file}.wip"
  2430. while true; do
  2431. changed=
  2432. new_services_uses=()
  2433. summon=()
  2434. required=()
  2435. recommended=()
  2436. optional=()
  2437. while [ "${#services_uses[@]}" != 0 ]; do
  2438. service="${services_uses[0]}"
  2439. relation_name="${services_uses[1]}"
  2440. relation_def="${services_uses[2]}"
  2441. services_uses=("${services_uses[@]:3}")
  2442. [ "${without_relations[$service:$relation_name]}" ] && {
  2443. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2444. continue
  2445. }
  2446. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2447. after=$(_out_after_value_from_def "$service" "$relation_name" "$relation_def") || return 1
  2448. ## is this "use" declaration satisfied ?
  2449. found=
  2450. while read-0 p s rn ts rc td; do
  2451. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  2452. if [ "$default_options" ]; then
  2453. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2454. fi
  2455. found="$ts"
  2456. p="$after"
  2457. fi
  2458. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td"
  2459. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2460. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2461. if [ "$found" ]; then ## this "use" declaration was satisfied
  2462. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation" \
  2463. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2464. continue
  2465. fi
  2466. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2467. auto=${auto:-pair}
  2468. case "$auto" in
  2469. "pair"|"summon")
  2470. service_list=()
  2471. array_read-0 service_list < <(array_keys_to_stdin services)
  2472. providers=()
  2473. providers_def=()
  2474. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2475. if [ "${#providers[@]}" == 1 ]; then
  2476. ts="${providers[0]}"
  2477. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2478. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2479. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2480. "${providers_def[0]}" "$relation_def" \
  2481. >> "${cache_file}.wip" || return 1
  2482. ## Adding service
  2483. [ "${services[$ts]}" ] && continue
  2484. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2485. services[$ts]=1
  2486. changed=1
  2487. continue
  2488. fi
  2489. if [ "${#providers[@]}" -gt 1 ]; then
  2490. msg=""
  2491. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2492. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2493. "(> 1 provider)."
  2494. elif [ "$auto" == "summon" ]; then ## no provider
  2495. summon+=("$service" "$relation_name" "$relation_def")
  2496. fi
  2497. ;;
  2498. null|disable|disabled)
  2499. :
  2500. ;;
  2501. *)
  2502. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2503. return 1
  2504. ;;
  2505. esac
  2506. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2507. constraint=${constraint:-optional}
  2508. case "$constraint" in
  2509. "required")
  2510. required+=("$service" "$relation_name" "$relation_def")
  2511. ;;
  2512. "recommended")
  2513. recommended+=("$service" "$relation_name" "$relation_def")
  2514. ;;
  2515. "optional")
  2516. optional+=("$service" "$relation_name" "$relation_def")
  2517. ;;
  2518. *)
  2519. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2520. return 1
  2521. ;;
  2522. esac
  2523. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2524. done
  2525. services_uses=("${new_services_uses[@]}")
  2526. if [ "$changed" ]; then
  2527. continue
  2528. fi
  2529. ## situation is stable
  2530. if [ "${#summon[@]}" != 0 ]; then
  2531. declare -A summon_requeued=()
  2532. while [ "${#summon[@]}" != 0 ]; do
  2533. service="${summon[0]}"
  2534. relation_name="${summon[1]}"
  2535. relation_def="${summon[2]}"
  2536. summon=("${summon[@]:3}")
  2537. providers=()
  2538. providers_def=()
  2539. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2540. if [ "${#providers[@]}" == 0 ]; then
  2541. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2542. return 1
  2543. fi
  2544. if [ "${#providers[@]}" -gt 1 ]; then
  2545. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2546. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2547. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2548. "(> 1 provider). Requeing."
  2549. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2550. summon_requeued["$service/$relation_name"]=1
  2551. continue
  2552. else
  2553. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2554. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2555. "(> 1 provider). Choosing first."
  2556. fi
  2557. fi
  2558. ts="${providers[0]}"
  2559. ## YYYvlab: should be seen even in no debug mode no ?
  2560. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2561. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2562. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2563. "${providers_def[0]}" "$relation_def" \
  2564. >> "${cache_file}.wip" || return 1
  2565. ## Adding service
  2566. [ "${services[$ts]}" ] && continue
  2567. array_read-0 services_uses < <(_get_services_uses "$ts")
  2568. services[$ts]=1
  2569. changed=1
  2570. continue 2
  2571. done
  2572. continue
  2573. fi
  2574. [ "$NO_CONSTRAINT_CHECK" ] && break
  2575. if [ "${#required[@]}" != 0 ]; then
  2576. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2577. err "Required relations not satisfied"
  2578. return 1
  2579. fi
  2580. if [ "${#recommended[@]}" != 0 ]; then
  2581. ## make recommendation
  2582. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2583. fi
  2584. if [ -z "$QUIET" ]; then
  2585. if [ "${#optional[@]}" != 0 ]; then
  2586. ## inform about options
  2587. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2588. fi
  2589. fi
  2590. # if [ "${#required[@]}" != 0 ]; then
  2591. # err "Required relations not satisfied"
  2592. # return 1
  2593. # fi
  2594. if [ "${#recommended[@]}" != 0 ]; then
  2595. warn "Recommended relations not satisfied"
  2596. fi
  2597. break
  2598. done
  2599. if [ "$?" != 0 ]; then
  2600. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2601. return 1
  2602. fi
  2603. ##
  2604. ## Sort relations thanks to uses =metadata.yml= relations.
  2605. ##
  2606. mv "${cache_file}.wip"{,.in} &&
  2607. rm -f "${cache_file}.wip.final" &&
  2608. touch "${cache_file}.wip.final" || {
  2609. err "Unexpected error when mangling cache files."
  2610. return 1
  2611. }
  2612. declare -A relation_done=()
  2613. while true; do
  2614. had_remaining_relation=
  2615. had_new_relation=
  2616. while read-0 p s rn ts rc td; do
  2617. if [ -z "$p" ] || [ "$p" == "," ]; then
  2618. relation_done["$s:$rn"]=1
  2619. # printf " .. %-30s %-30s %-30s\n" "--" "$s" "$rn" >&2
  2620. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  2621. had_new_relation=1
  2622. else
  2623. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2624. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2625. had_remaining_relation=1
  2626. fi
  2627. done < "${cache_file}.wip.in"
  2628. [ -z "$had_remaining_relation" ] && break
  2629. mv "${cache_file}.wip."{out,in}
  2630. while read-0 p s rn ts rc td; do
  2631. for rel in "${!relation_done[@]}"; do
  2632. p="${p//,$rel,/,}"
  2633. done
  2634. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2635. if [ -z "$had_new_relation" ]; then
  2636. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  2637. for rel in ${p//,/ }; do
  2638. rel_s=${rel%%:*}
  2639. rel_r=${rel##*:}
  2640. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  2641. done
  2642. else
  2643. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2644. fi
  2645. done < "${cache_file}.wip.in"
  2646. if [ -z "$had_new_relation" ]; then
  2647. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  2648. return 1
  2649. fi
  2650. mv "${cache_file}.wip."{out,in}
  2651. done
  2652. export ALL_RELATIONS="$cache_file"
  2653. mv "${cache_file}"{.wip.final,} || return 1
  2654. cat "$cache_file"
  2655. }
  2656. export -f get_all_relations
  2657. _display_solves() {
  2658. local array_name="$1" by_relation msg
  2659. ## inform about options
  2660. msg=""
  2661. declare -A by_relation
  2662. while read-0 service relation_name relation_def; do
  2663. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2664. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2665. if [ -z "$solves" ]; then
  2666. continue
  2667. fi
  2668. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2669. if [ "$auto" == "pair" ]; then
  2670. requirement="add provider in cluster to auto-pair"
  2671. else
  2672. requirement="add explicit relation"
  2673. fi
  2674. while read-0 name def; do
  2675. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2676. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2677. done < <(array_values_to_stdin "$array_name")
  2678. while read-0 relation_name message; do
  2679. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2680. "$relation_name" "$message" )"
  2681. done < <(array_kv_to_stdin by_relation)
  2682. if [ "$msg" ]; then
  2683. printf "%s\n" "${msg:1}"
  2684. fi
  2685. }
  2686. get_compose_relation_def() {
  2687. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2688. while read-0 relation_name target_service relation_config tech_dep; do
  2689. [ "$relation_name" == "$relation" ] || continue
  2690. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2691. done < <(get_compose_relations "$service") || return 1
  2692. }
  2693. export -f get_compose_relation_def
  2694. run_service_relations () {
  2695. local service services loaded subservices subservice
  2696. PROJECT_NAME=$(get_default_project_name) || return 1
  2697. export PROJECT_NAME
  2698. declare -A loaded
  2699. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2700. for service in $subservices; do
  2701. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2702. for subservice in $(get_service_deps "$service") "$service"; do
  2703. [ "${loaded[$subservice]}" ] && continue
  2704. export BASE_SERVICE_NAME=$service
  2705. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2706. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2707. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2708. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2709. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2710. while read-0 relation_name target_service relation_config tech_dep; do
  2711. [ "${without_relations[$service:$relation_name]}" ] && {
  2712. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2713. continue
  2714. }
  2715. export relation_config
  2716. export TARGET_SERVICE_NAME=$target_service
  2717. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2718. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2719. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2720. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2721. Wrap "${wrap_opts[@]}" -d "building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2722. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2723. EOF
  2724. done < <(get_service_relations "$subservice") || return 1
  2725. loaded[$subservice]=1
  2726. done
  2727. done
  2728. }
  2729. export -f run_service_relations
  2730. _run_service_action_direct() {
  2731. local service="$1" action="$2" charm _dummy project_name
  2732. shift; shift
  2733. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  2734. if read-0 _dummy || [ "$_dummy" ]; then
  2735. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2736. return 1
  2737. fi
  2738. project_name=$(get_default_project_name) || return 1
  2739. export PROJECT_NAME="$project_name"
  2740. export state_tmpdir
  2741. (
  2742. set +e ## Prevents unwanted leaks from parent shell
  2743. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2744. export METADATA_CONFIG=$(charm.metadata "$charm")
  2745. export SERVICE_NAME=$service
  2746. export ACTION_NAME=$action
  2747. export ACTION_SCRIPT_PATH="$action_script_path"
  2748. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2749. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  2750. export SERVICE_DATASTORE="$DATASTORE/$service"
  2751. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2752. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2753. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2754. ) 0<&6 ## inject general stdin
  2755. }
  2756. export -f _run_service_action_direct
  2757. _run_service_action_relation() {
  2758. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2759. shift; shift
  2760. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  2761. if read-0 _dummy || [ "$_dummy" ]; then
  2762. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2763. return 1
  2764. fi
  2765. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2766. export state_tmpdir
  2767. (
  2768. set +e ## Prevents unwanted leaks from parent shell
  2769. export METADATA_CONFIG=$(charm.metadata "$charm")
  2770. export SERVICE_NAME=$service
  2771. export RELATION_TARGET_SERVICE="$target_service"
  2772. export RELATION_TARGET_CHARM="$target_charm"
  2773. export RELATION_BASE_SERVICE="$service"
  2774. export RELATION_BASE_CHARM="$charm"
  2775. export ACTION_NAME=$action
  2776. export ACTION_SCRIPT_PATH="$action_script_path"
  2777. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2778. export DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$CONTAINER_NAME")
  2779. export SERVICE_DATASTORE="$DATASTORE/$service"
  2780. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2781. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2782. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2783. ) 0<&6 ## inject general stdin
  2784. }
  2785. export -f _run_service_action_relation
  2786. get_relation_data_dir() {
  2787. local service="$1" target_service="$2" relation_name="$3" \
  2788. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2789. if [ -e "$cache_file" ]; then
  2790. # debug "$FUNCNAME: cache hit ($*)"
  2791. cat "$cache_file"
  2792. return 0
  2793. fi
  2794. local project relation_dir
  2795. project=${PROJECT_NAME}
  2796. if [ -z "$project" ]; then
  2797. project=$(get_default_project_name) || return 1
  2798. fi
  2799. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2800. if ! [ -d "$relation_dir" ]; then
  2801. mkdir -p "$relation_dir" || return 1
  2802. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2803. fi
  2804. echo "$relation_dir" | tee "$cache_file"
  2805. }
  2806. export -f get_relation_data_dir
  2807. get_relation_data_file() {
  2808. local service="$1" target_service="$2" relation_name="$3" relation_config="$4" \
  2809. new new_md5 relation_dir relation_data_file
  2810. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2811. relation_data_file="$relation_dir/data"
  2812. new=
  2813. if [ -e "$relation_data_file" ]; then
  2814. ## Has reference changed ?
  2815. new_md5=$(e "$relation_config" | md5_compat)
  2816. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2817. new=true
  2818. fi
  2819. else
  2820. new=true
  2821. fi
  2822. if [ -n "$new" ]; then
  2823. OLDUMASK=$(umask)
  2824. umask 0077
  2825. e "$relation_config" > "$relation_data_file"
  2826. umask "$OLDUMASK"
  2827. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2828. fi
  2829. echo "$relation_data_file"
  2830. }
  2831. export -f get_relation_data_file
  2832. has_service_action () {
  2833. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2834. charm target_charm relation_name target_service relation_config _tech_dep \
  2835. path
  2836. if [ -e "$cache_file" ]; then
  2837. # debug "$FUNCNAME: cache hit ($*)"
  2838. cat "$cache_file"
  2839. return 0
  2840. fi
  2841. charm=$(get_service_charm "$service") || return 1
  2842. ## Action directly provided ?
  2843. if path=$(charm.has_direct_action "$charm" "$action"); then
  2844. p0 "direct" "$charm" "$path" | tee "$cache_file"
  2845. return 0
  2846. fi
  2847. ## Action provided by relation ?
  2848. while read-0 relation_name target_service relation_config _tech_dep; do
  2849. target_charm=$(get_service_charm "$target_service") || return 1
  2850. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  2851. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  2852. return 0
  2853. fi
  2854. done < <(get_service_relations "$service")
  2855. return 1
  2856. # master=$(get_top_master_service_for_service "$service")
  2857. # [ "$master" == "$charm" ] && return 1
  2858. # has_service_action "$master" "$action"
  2859. }
  2860. export -f has_service_action
  2861. run_service_action () {
  2862. local service="$1" action="$2" errlvl
  2863. shift ; shift
  2864. exec 6<&0 ## saving stdin
  2865. {
  2866. if ! read-0 action_type; then
  2867. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2868. info " Add an executable script to 'actions/$action' to implement action."
  2869. return 1
  2870. fi
  2871. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2872. errlvl="$?"
  2873. } < <(has_service_action "$service" "$action")
  2874. exec 0<&6 6<&- ## restoring stdin
  2875. return "$errlvl"
  2876. }
  2877. export -f run_service_action
  2878. get_compose_relation_config() {
  2879. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2880. if [ -e "$cache_file" ]; then
  2881. # debug "$FUNCNAME: cache hit ($*)"
  2882. cat "$cache_file"
  2883. return 0
  2884. fi
  2885. compose_service_def=$(get_compose_service_def "$service") || return 1
  2886. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2887. }
  2888. export -f get_compose_relation_config
  2889. # ## Return key-values-0
  2890. # get_compose_relation_config_for_service() {
  2891. # local service=$1 relation_name=$2 relation_config
  2892. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2893. # if ! relation_config=$(
  2894. # echo "$compose_service_relations" |
  2895. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2896. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2897. # "relation config in compose configuration."
  2898. # return 1
  2899. # fi
  2900. # if [ -z "$relation_config" ]; then
  2901. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2902. # return 1
  2903. # fi
  2904. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2905. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2906. # return 1
  2907. # fi
  2908. # }
  2909. # export -f get_compose_relation_config_for_service
  2910. _get_container_relation() {
  2911. local metadata=$1 found relation_name relation_def
  2912. found=
  2913. while read-0 relation_name relation_def; do
  2914. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2915. found="$relation_name"
  2916. break
  2917. }
  2918. done < <(_get_charm_metadata_uses "$metadata")
  2919. if [ -z "$found" ]; then
  2920. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2921. "${WHITE}scope${NORMAL} set to 'container'."
  2922. return 1
  2923. fi
  2924. printf "%s" "$found"
  2925. }
  2926. _get_master_service_for_service_cached () {
  2927. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2928. charm requires master_charm target_charm target_service service_def found
  2929. if [ -e "$cache_file" ]; then
  2930. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2931. cat "$cache_file" &&
  2932. touch "$cache_file" || return 1
  2933. return 0
  2934. fi
  2935. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  2936. ## just return service name
  2937. echo "$service" | tee "$cache_file"
  2938. return 0
  2939. fi
  2940. ## Action provided by relation ?
  2941. container_relation=$(_get_container_relation "$metadata") || return 1
  2942. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2943. if [ -z "$target_service" ]; then
  2944. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2945. "${DARKYELLOW}$service$NORMAL compose definition."
  2946. err ${FUNCNAME[@]}
  2947. return 1
  2948. fi
  2949. echo "$target_service" | tee "$cache_file"
  2950. }
  2951. export -f _get_master_service_for_service_cached
  2952. get_master_service_for_service() {
  2953. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2954. charm metadata result
  2955. if [ -e "$cache_file" ]; then
  2956. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2957. cat "$cache_file" || return 1
  2958. return 0
  2959. fi
  2960. charm=$(get_service_charm "$service") || return 1
  2961. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2962. metadata=""
  2963. warn "No charm $DARKPINK$charm$NORMAL found."
  2964. }
  2965. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2966. echo "$result" | tee "$cache_file" || return 1
  2967. }
  2968. export -f get_master_service_for_service
  2969. get_top_master_service_for_service() {
  2970. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2971. current_service
  2972. if [ -e "$cache_file" ]; then
  2973. # debug "$FUNCNAME: cache hit ($*)"
  2974. cat "$cache_file"
  2975. return 0
  2976. fi
  2977. current_service="$service"
  2978. while true; do
  2979. master_service=$(get_master_service_for_service "$current_service") || return 1
  2980. [ "$master_service" == "$current_service" ] && break
  2981. current_service="$master_service"
  2982. done
  2983. echo "$current_service" | tee "$cache_file"
  2984. return 0
  2985. }
  2986. export -f get_top_master_service_for_service
  2987. ##
  2988. ## The result is a mixin that is not always a complete valid
  2989. ## docker-compose entry (thinking of subordinates). The result
  2990. ## will be merge with master charms.
  2991. _get_docker_compose_mixin_from_metadata_cached() {
  2992. local service="$1" charm="$2" metadata="$3" \
  2993. has_build_dir="$4" \
  2994. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2995. metadata_file metadata volumes docker_compose subordinate image \
  2996. mixin mixins tmemory memory limit docker_memory
  2997. if [ -e "$cache_file" ]; then
  2998. #debug "$FUNCNAME: STATIC cache hit $1"
  2999. cat "$cache_file" &&
  3000. touch "$cache_file" || return 1
  3001. return 0
  3002. fi
  3003. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  3004. if [ "$metadata" ]; then
  3005. ## resources to volumes
  3006. volumes=$(
  3007. for resource_type in data config; do
  3008. while read-0 resource; do
  3009. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  3010. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  3011. done
  3012. while read-0 resource; do
  3013. if [[ "$resource" == /*:/*:* ]]; then
  3014. echo " - $resource"
  3015. elif [[ "$resource" == /*:/* ]]; then
  3016. echo " - $resource:rw"
  3017. elif [[ "$resource" == /*:* ]]; then
  3018. echo " - ${resource%%:*}:$resource"
  3019. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  3020. echo " - $resource:$resource:rw"
  3021. else
  3022. die "Invalid host-resource specified in 'metadata.yml'."
  3023. fi
  3024. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  3025. while read-0 resource; do
  3026. dest="$(charm.get_dir "$charm")/resources$resource"
  3027. if ! [ -e "$dest" ]; then
  3028. die "charm-resource: '$resource' does not exist (file: '$dest')."
  3029. fi
  3030. echo " - $dest:$resource:ro"
  3031. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  3032. ) || return 1
  3033. if [ "$volumes" ]; then
  3034. mixins+=("volumes:"$'\n'"$volumes")
  3035. fi
  3036. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3037. if [ "$type" != "run-once" ]; then
  3038. mixins+=("restart: unless-stopped")
  3039. fi
  3040. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  3041. if [ "$docker_compose" ]; then
  3042. mixins+=("$docker_compose")
  3043. fi
  3044. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  3045. subordinate=true
  3046. fi
  3047. fi
  3048. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  3049. [ "$image" == "None" ] && image=""
  3050. if [ -n "$image" ]; then
  3051. if [ -n "$subordinate" ]; then
  3052. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  3053. return 1
  3054. fi
  3055. mixins+=("image: $image")
  3056. elif [ "$has_build_dir" ]; then
  3057. if [ "$subordinate" ]; then
  3058. err "Subordinate charm can not have a 'build' sub directory."
  3059. return 1
  3060. fi
  3061. mixins+=("build: $(charm.get_dir "$charm")/build")
  3062. fi
  3063. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  3064. [ "$limit" == "null" ] && limit=""
  3065. if [ -n "$limit" ]; then
  3066. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  3067. [ "$E" != 0 ]; then
  3068. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  3069. return 1
  3070. fi
  3071. case "$tmemory" in
  3072. '!!str'|'!!int')
  3073. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  3074. err "Invalid format specified for .limit.memory: '$memory'."
  3075. return 1
  3076. }
  3077. ;;
  3078. '!!float')
  3079. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  3080. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  3081. return 1
  3082. ;;
  3083. '!!null')
  3084. :
  3085. ;;
  3086. *)
  3087. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  3088. "for ${WHITE}.limit.memory${NORMAL}."
  3089. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  3090. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  3091. echo " Example values: '1.5G', '252M', ..." >&2
  3092. return 1
  3093. ;;
  3094. esac
  3095. if [ -n "$docker_memory" ]; then
  3096. if [[ "$docker_memory" -lt 6291456 ]]; then
  3097. err "Can't limit service to lower than 6M."
  3098. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  3099. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  3100. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  3101. return 1
  3102. fi
  3103. mixins+=(
  3104. "mem_limit: $docker_memory"
  3105. "memswap_limit: $docker_memory"
  3106. )
  3107. fi
  3108. fi
  3109. ## Final merging
  3110. mixin=$(merge_yaml_str "${mixins[@]}") || {
  3111. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  3112. return 1
  3113. }
  3114. echo "$mixin" | tee "$cache_file"
  3115. }
  3116. export -f _get_docker_compose_mixin_from_metadata_cached
  3117. get_docker_compose_mixin_from_metadata() {
  3118. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  3119. if [ -e "$cache_file" ]; then
  3120. #debug "$FUNCNAME: SESSION cache hit ($*)"
  3121. cat "$cache_file"
  3122. return 0
  3123. fi
  3124. charm=$(get_service_charm "$service") || return 1
  3125. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  3126. has_build_dir=
  3127. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  3128. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  3129. echo "$mixin" | tee "$cache_file"
  3130. }
  3131. export -f get_docker_compose_mixin_from_metadata
  3132. _save() {
  3133. local name="$1"
  3134. cat - | tee -a "$docker_compose_dir/.data/$name"
  3135. }
  3136. export -f _save
  3137. get_default_project_name() {
  3138. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  3139. echo "$DEFAULT_PROJECT_NAME"
  3140. return 0
  3141. fi
  3142. local normalized_path compose_yml_location name
  3143. compose_yml_location="$(get_compose_yml_location)" || return 1
  3144. if [ -n "$compose_yml_location" ]; then
  3145. if normalized_path=$(readlink -f "$compose_yml_location"); then
  3146. name="${normalized_path%/*}" ## dirname
  3147. name="${name##*/}" ## basename
  3148. name="${name%%-deploy}" ## remove any '-deploy'
  3149. name="${name,,}" ## lowercase
  3150. e "$name"
  3151. return 0
  3152. fi
  3153. fi
  3154. echo "orphan"
  3155. return 0
  3156. }
  3157. export -f get_default_project_name
  3158. get_running_compose_containers() {
  3159. ## XXXvlab: docker bug: there will be a final newline anyway
  3160. docker ps --filter label="compose.service" --format='{{.ID}}'
  3161. }
  3162. export -f get_running_compose_containers
  3163. get_healthy_container_ip_for_service () {
  3164. local service="$1" port="$2" timeout=${3:-60}
  3165. local containers container container_network container_ip
  3166. containers="$(get_running_containers_for_service "$service")"
  3167. if [ -z "$containers" ]; then
  3168. err "No containers running for service $DARKYELLOW$service$NORMAL."
  3169. return 1
  3170. fi
  3171. ## XXXvlab: taking first container is probably not a good idea
  3172. container="$(echo "$containers" | head -n 1)"
  3173. ## XXXvlab: taking first ip is probably not a good idea
  3174. read-0 container_network container_ip < <(get_container_network_ip "$container")
  3175. if [ -z "$container_ip" ]; then
  3176. err "Can't get container's IP. You should check health of" \
  3177. "${DARKYELLOW}$service${NORMAL}'s container."
  3178. return 1
  3179. fi
  3180. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  3181. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  3182. echo " Please check that container is healthy. Here are last logs:" >&2
  3183. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  3184. return 1
  3185. }
  3186. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  3187. echo "$container_network:$container_ip"
  3188. }
  3189. export -f get_healthy_container_ip_for_service
  3190. switch_to_relation_service() {
  3191. local relation="$1"
  3192. ## XXXvlab: can't get real config here
  3193. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  3194. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  3195. return 1
  3196. fi
  3197. export SERVICE_NAME="$ts"
  3198. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3199. DOCKER_BASE_IMAGE=$(service_ensure_image_ready "$SERVICE_NAME")
  3200. export DOCKER_BASE_IMAGE
  3201. target_charm=$(get_service_charm "$ts") || return 1
  3202. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3203. cd "$target_charm_path"
  3204. }
  3205. export -f switch_to_relation_service
  3206. get_volumes_for_container() {
  3207. local container="$1"
  3208. docker inspect \
  3209. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3210. "$container"
  3211. }
  3212. export -f get_volumes_for_container
  3213. is_volume_used() {
  3214. local volume="$1" container_id src dst
  3215. while read -r container_id; do
  3216. while read-0 src dst; do
  3217. [[ "$src/" == "$volume"/* ]] && return 0
  3218. done < <(get_volumes_for_container "$container_id")
  3219. done < <(get_running_compose_containers)
  3220. return 1
  3221. }
  3222. export -f is_volume_used
  3223. clean_unused_docker_compose() {
  3224. for f in /var/lib/compose/docker-compose/*; do
  3225. [ -e "$f" ] || continue
  3226. is_volume_used "$f" && continue
  3227. debug "Cleaning unused docker-compose ${f##*/}"
  3228. rm -rf "$f" || return 1
  3229. done
  3230. return 0
  3231. }
  3232. export -f clean_unused_docker_compose
  3233. stdin_get_hash() {
  3234. local sha
  3235. sha=$(sha256sum) || return 1
  3236. sha=${sha:0:64}
  3237. echo "$sha"
  3238. }
  3239. export -f stdin_get_hash
  3240. file_get_hash() {
  3241. stdin_get_hash < "$1" || return 1
  3242. }
  3243. export -f file_get_hash
  3244. docker_compose_store() {
  3245. local file="$1" sha
  3246. sha=$(file_get_hash "$file") || return 1
  3247. project=$(get_default_project_name) || return 1
  3248. dst="/var/lib/compose/docker-compose/$sha/$project"
  3249. mkdir -p "$dst" || return 1
  3250. cat <<EOF > "$dst/.env" || return 1
  3251. DOCKER_COMPOSE_PATH=$dst
  3252. COMPOSE_HTTP_TIMEOUT=7200
  3253. EOF
  3254. cp "$file" "$dst/docker-compose.yml" || return 1
  3255. mkdir -p "$dst/bin" || return 1
  3256. cat <<EOF > "$dst/bin/dc" || return 1
  3257. #!/bin/bash
  3258. $(declare -f read-0)
  3259. docker_run_opts=()
  3260. while read-0 opt; do
  3261. if [[ "\$opt" == "!env:"* ]]; then
  3262. opt="\${opt##!env:}"
  3263. var="\${opt%%=*}"
  3264. value="\${opt#*=}"
  3265. export "\$var"="\$value"
  3266. else
  3267. docker_run_opts+=("\$opt")
  3268. fi
  3269. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3270. docker_run_opts+=(
  3271. "-w" "$dst"
  3272. "--entrypoint" "/usr/local/bin/docker-compose"
  3273. )
  3274. [ -t 1 ] && {
  3275. docker_run_opts+=("-ti")
  3276. }
  3277. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3278. EOF
  3279. chmod +x "$dst/bin/dc" || return 1
  3280. printf "%s" "$sha"
  3281. }
  3282. export -f docker_compose_store
  3283. launch_docker_compose() {
  3284. local charm docker_compose_tmpdir docker_compose_dir
  3285. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3286. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3287. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3288. ## docker-compose will name network from the parent dir name
  3289. project=$(get_default_project_name)
  3290. mkdir -p "$docker_compose_tmpdir/$project"
  3291. docker_compose_dir="$docker_compose_tmpdir/$project"
  3292. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  3293. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3294. # debug "Merging some config data in docker-compose.yml:"
  3295. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3296. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3297. fi
  3298. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3299. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3300. fi
  3301. ## XXXvlab: could be more specific and only link the needed charms
  3302. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3303. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3304. # if charm.exists "$charm"; then
  3305. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3306. # fi
  3307. # done
  3308. mkdir "$docker_compose_dir/.data"
  3309. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3310. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3311. fi
  3312. {
  3313. {
  3314. {
  3315. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3316. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3317. else
  3318. cd "$docker_compose_dir" || return 1
  3319. fi
  3320. if [ -f ".env" ]; then
  3321. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3322. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3323. fi
  3324. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3325. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3326. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3327. if [ "$DRY_COMPOSE_RUN" ]; then
  3328. echo docker-compose "$@"
  3329. else
  3330. docker-compose "$@"
  3331. fi
  3332. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3333. } | _save stdout
  3334. } 3>&1 1>&2 2>&3 | _save stderr
  3335. } 3>&1 1>&2 2>&3
  3336. 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
  3337. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3338. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3339. fi
  3340. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3341. if [ -z "$docker_compose_errlvl" ]; then
  3342. err "Something went wrong before you could gather docker-compose errorlevel."
  3343. return 1
  3344. fi
  3345. return "$docker_compose_errlvl"
  3346. }
  3347. export -f launch_docker_compose
  3348. get_compose_yml_location() {
  3349. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3350. echo "$COMPOSE_YML_FILE"
  3351. return 0
  3352. fi
  3353. parent=$(while ! [ -f "./compose.yml" ]; do
  3354. [ "$PWD" == "/" ] && exit 0
  3355. cd ..
  3356. done; echo "$PWD"
  3357. )
  3358. if [ "$parent" ]; then
  3359. echo "$parent/compose.yml"
  3360. return 0
  3361. fi
  3362. ## XXXvlab: do we need this additional environment variable,
  3363. ## COMPOSE_YML_FILE is not sufficient ?
  3364. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3365. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3366. warn "No 'compose.yml' was found in current or parent dirs," \
  3367. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3368. "(${DEFAULT_COMPOSE_FILE})"
  3369. return 0
  3370. fi
  3371. echo "$DEFAULT_COMPOSE_FILE"
  3372. return 0
  3373. fi
  3374. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3375. return 0
  3376. }
  3377. export -f get_compose_yml_location
  3378. get_compose_yml_content() {
  3379. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3380. if [ -e "$cache_file" ]; then
  3381. cat "$cache_file" &&
  3382. touch "$cache_file" || return 1
  3383. return 0
  3384. fi
  3385. if [ -z "$COMPOSE_YML_FILE" ]; then
  3386. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3387. fi
  3388. if [ -e "$COMPOSE_YML_FILE" ]; then
  3389. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3390. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3391. err "Could not read '$COMPOSE_YML_FILE'."
  3392. return 1
  3393. }
  3394. else
  3395. debug "No compose file found. Using an empty one."
  3396. COMPOSE_YML_CONTENT=""
  3397. fi
  3398. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3399. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3400. if [ "$?" != 0 ]; then
  3401. outputed_something=
  3402. while IFS='' read -r line1 && IFS='' read -r line2; do
  3403. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3404. outputed_something=true
  3405. echo "$line1 $GRAY($line2)$NORMAL"
  3406. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3407. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3408. prefix " $GRAY|$NORMAL "
  3409. [ "$outputed_something" ] || {
  3410. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3411. echo "$output" | prefix " $GRAY|$NORMAL "
  3412. }
  3413. return 1
  3414. fi
  3415. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3416. }
  3417. export -f get_compose_yml_content
  3418. get_default_target_services() {
  3419. local services=("$@")
  3420. if [ -z "${services[*]}" ]; then
  3421. if [ "$DEFAULT_SERVICES" ]; then
  3422. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3423. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3424. services="$DEFAULT_SERVICES"
  3425. else
  3426. err "No service provided."
  3427. return 1
  3428. fi
  3429. fi
  3430. echo "${services[*]}"
  3431. }
  3432. export -f get_default_target_services
  3433. get_master_services() {
  3434. local loaded master_service service
  3435. declare -A loaded
  3436. for service in "$@"; do
  3437. master_service=$(get_top_master_service_for_service "$service") || return 1
  3438. if [ "${loaded[$master_service]}" ]; then
  3439. continue
  3440. fi
  3441. echo "$master_service"
  3442. loaded["$master_service"]=1
  3443. done | nspc
  3444. return "${PIPESTATUS[0]}"
  3445. }
  3446. export -f get_master_services
  3447. get_current_docker_container_id() {
  3448. local line
  3449. line=$(cat "/proc/self/cpuset") || return 1
  3450. [[ "$line" == *docker* ]] || return 1
  3451. echo "${line##*/}"
  3452. }
  3453. export -f get_current_docker_container_id
  3454. ## if we are in a docker compose, we might want to know what is the
  3455. ## real host path of some local paths.
  3456. get_host_path() {
  3457. local path="$1"
  3458. path=$(realpath "$path") || return 1
  3459. container_id=$(get_current_docker_container_id) || {
  3460. print "%s" "$path"
  3461. return 0
  3462. }
  3463. biggest_dst=
  3464. current_src=
  3465. while read-0 src dst; do
  3466. [[ "$path" == "$dst"* ]] || continue
  3467. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3468. biggest_dst="$dst"
  3469. current_src="$src"
  3470. fi
  3471. done < <(get_volumes_for_container "$container_id")
  3472. if [ "$current_src" ]; then
  3473. printf "%s" "$current_src"
  3474. else
  3475. return 1
  3476. fi
  3477. }
  3478. export -f get_host_path
  3479. _setup_state_dir() {
  3480. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3481. #debug "Creating temporary state directory in '$state_tmpdir'."
  3482. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3483. # rm -rf \"$state_tmpdir\""
  3484. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3485. }
  3486. get_docker_compose_help_msg() {
  3487. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3488. docker_compose_help_msg
  3489. if [ -e "$cache_file" ]; then
  3490. cat "$cache_file" &&
  3491. touch "$cache_file" || return 1
  3492. return 0
  3493. fi
  3494. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3495. echo "$docker_compose_help_msg" |
  3496. tee "$cache_file" || return 1
  3497. }
  3498. get_docker_compose_usage() {
  3499. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3500. docker_compose_help_msg
  3501. if [ -e "$cache_file" ]; then
  3502. cat "$cache_file" &&
  3503. touch "$cache_file" || return 1
  3504. return 0
  3505. fi
  3506. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3507. echo "$docker_compose_help_msg" |
  3508. grep -m 1 "^Usage:" -A 10000 |
  3509. egrep -m 1 "^\$" -B 10000 |
  3510. nspc |
  3511. sed -r 's/^Usage: //g' |
  3512. tee "$cache_file" || return 1
  3513. }
  3514. get_docker_compose_opts_help() {
  3515. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3516. docker_compose_help_msg
  3517. if [ -e "$cache_file" ]; then
  3518. cat "$cache_file" &&
  3519. touch "$cache_file" || return 1
  3520. return 0
  3521. fi
  3522. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3523. echo "$docker_compose_opts_help" |
  3524. grep '^Options:' -A 20000 |
  3525. tail -n +2 |
  3526. { cat ; echo; } |
  3527. egrep -m 1 "^\S*\$" -B 10000 |
  3528. head -n -1 |
  3529. tee "$cache_file" || return 1
  3530. }
  3531. get_docker_compose_commands_help() {
  3532. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3533. docker_compose_help_msg
  3534. if [ -e "$cache_file" ]; then
  3535. cat "$cache_file" &&
  3536. touch "$cache_file" || return 1
  3537. return 0
  3538. fi
  3539. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3540. echo "$docker_compose_opts_help" |
  3541. grep '^Commands:' -A 20000 |
  3542. tail -n +2 |
  3543. { cat ; echo; } |
  3544. egrep -m 1 "^\S*\$" -B 10000 |
  3545. head -n -1 |
  3546. tee "$cache_file" || return 1
  3547. }
  3548. get_docker_compose_opts_list() {
  3549. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3550. docker_compose_help_msg
  3551. if [ -e "$cache_file" ]; then
  3552. cat "$cache_file" &&
  3553. touch "$cache_file" || return 1
  3554. return 0
  3555. fi
  3556. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3557. echo "$docker_compose_opts_help" |
  3558. egrep "^\s+-" |
  3559. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3560. tee "$cache_file" || return 1
  3561. }
  3562. options_parser() {
  3563. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3564. printf "\0"
  3565. }
  3566. remove_options_in_option_help_msg() {
  3567. {
  3568. read-0 null
  3569. if [ "$null" ]; then
  3570. err "options parsing error, should start with an option line."
  3571. return 1
  3572. fi
  3573. while read-0 opt full_txt;do
  3574. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3575. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3576. for to_remove in "$@"; do
  3577. str_matches "$to_remove" $multi_opts $single_opts && {
  3578. continue 2
  3579. }
  3580. done
  3581. echo -n "$full_txt"
  3582. done
  3583. } < <(options_parser)
  3584. }
  3585. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3586. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3587. multi_opts_filter() {
  3588. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3589. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3590. tr ',' "\n" | nspc
  3591. }
  3592. single_opts_filter() {
  3593. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3594. tr ',' "\n" | nspc
  3595. }
  3596. get_docker_compose_multi_opts_list() {
  3597. local action="$1" opts_list
  3598. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3599. echo "$opts_list" | multi_opts_filter
  3600. }
  3601. get_docker_compose_single_opts_list() {
  3602. local action="$1" opts_list
  3603. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3604. echo "$opts_list" | single_opts_filter
  3605. }
  3606. display_commands_help() {
  3607. local charm_actions
  3608. echo
  3609. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3610. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3611. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3612. if [ "$charm_actions_help" ]; then
  3613. echo
  3614. echo "${WHITE}Charm actions${NORMAL}:"
  3615. printf "%s\n" "$charm_actions_help" | \
  3616. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3617. fi
  3618. }
  3619. get_docker_charm_action() {
  3620. local services service charm relation_name target_service relation_config \
  3621. target_charm
  3622. services=($(get_compose_yml_content | yq -r 'keys().[]' 2>/dev/null)) || return 1
  3623. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3624. services=($(get_all_services)) || return 1
  3625. for service in "${services[@]}"; do
  3626. printf "%s:\n" "$service"
  3627. charm=$(get_service_charm "$service") || return 1
  3628. for action in $(charm.ls_direct_actions "$charm"); do
  3629. printf " %s:\n" "$action"
  3630. printf " type: %s\n" "direct"
  3631. done
  3632. while read-0 relation_name target_service _relation_config _tech_dep; do
  3633. target_charm=$(get_service_charm "$target_service") || return 1
  3634. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3635. printf " %s:\n" "$action"
  3636. printf " type: %s\n" "indirect"
  3637. printf " inherited: %s\n" "$target_charm"
  3638. done
  3639. done < <(get_service_relations "$service")
  3640. done
  3641. }
  3642. export -f get_docker_charm_action
  3643. get_docker_charm_action_help() {
  3644. local services service charm relation_name target_service relation_config \
  3645. target_charm
  3646. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3647. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3648. for service in "${services[@]}"; do
  3649. out=$(
  3650. charm=$(get_service_charm "$service") || return 1
  3651. for action in $(charm.ls_direct_actions "$charm"); do
  3652. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3653. done
  3654. while read-0 relation_name target_service _relation_config _tech_dep; do
  3655. target_charm=$(get_service_charm "$target_service") || return 1
  3656. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3657. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3658. done
  3659. done < <(get_service_relations "$service")
  3660. )
  3661. if [ "$out" ]; then
  3662. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3663. printf "%s\n" "$out"
  3664. fi
  3665. done
  3666. }
  3667. display_help() {
  3668. print_help
  3669. echo "${WHITE}Usage${NORMAL}:"
  3670. echo " $usage"
  3671. echo " $usage cache {clean|clear}"
  3672. echo "${WHITE}Options${NORMAL}:"
  3673. echo " -h, --help Print this message and quit"
  3674. echo " (ignoring any other options)"
  3675. echo " -V, --version Print current version and quit"
  3676. echo " (ignoring any other options)"
  3677. echo " --dirs Display data dirs and quit"
  3678. echo " (ignoring any other options)"
  3679. echo " --get-project-name Display project name and quit"
  3680. echo " (ignoring any other options)"
  3681. echo " --get-available-actions Display all available actions and quit"
  3682. echo " (ignoring any other options)"
  3683. echo " -v, --verbose Be more verbose"
  3684. echo " -q, --quiet Be quiet"
  3685. echo " -d, --debug Print full debugging information (sets also verbose)"
  3686. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3687. echo " command line will be used."
  3688. echo " --no-relations Do not run any relation script"
  3689. echo " --no-hooks Do not run any hook script"
  3690. echo " --no-init Do not run any init script"
  3691. echo " --no-post-deploy Do not run any post-deploy script"
  3692. echo " --no-pre-deploy Do not run any pre-deploy script"
  3693. echo " --without-relation RELATION "
  3694. echo " Do not run given relation"
  3695. echo " -R, --rebuild-relations-to-service SERVICE"
  3696. echo " Will rebuild all relations to given service"
  3697. echo " --add-compose-content, -Y YAML"
  3698. echo " Will merge some direct YAML with the current compose"
  3699. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  3700. echo " --push-builds Will push cached docker images to docker cache registry"
  3701. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3702. filter_docker_compose_help_message
  3703. display_commands_help
  3704. }
  3705. _graph_service() {
  3706. local service="$1" base="$1"
  3707. charm=$(get_service_charm "$service") || return 1
  3708. metadata=$(charm.metadata "$charm") || return 1
  3709. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3710. if [[ "$subordinate" =~ ^True|true$ ]]; then
  3711. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3712. master_charm=
  3713. while read-0 relation_name relation; do
  3714. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3715. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3716. if [ -z "$interface" ]; then
  3717. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3718. return 1
  3719. fi
  3720. ## Action provided by relation ?
  3721. target_service=
  3722. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3723. [ "$interface" == "$relation_name" ] && {
  3724. target_service="$candidate_target_service"
  3725. break
  3726. }
  3727. done < <(get_service_relations "$service")
  3728. if [ -z "$target_service" ]; then
  3729. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3730. "${DARKYELLOW}$service$NORMAL compose definition."
  3731. return 1
  3732. fi
  3733. master_service="$target_service"
  3734. master_charm=$(get_service_charm "$target_service") || return 1
  3735. break
  3736. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3737. fi
  3738. _graph_node_service "$service" "$base" "$charm"
  3739. _graph_edge_service "$service" "$subordinate" "$master_service"
  3740. }
  3741. _graph_node_service() {
  3742. local service="$1" base="$2" charm="$3"
  3743. cat <<EOF
  3744. "$(_graph_node_service_label ${service})" [
  3745. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  3746. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  3747. color = $([ "$base" ] && echo "blue" || echo "black")
  3748. fillcolor = "white"
  3749. fontname = "Courier New"
  3750. shape = "Mrecord"
  3751. label =<$(_graph_node_service_content "$service")>
  3752. ];
  3753. EOF
  3754. }
  3755. _graph_edge_service() {
  3756. local service="$1" subordinate="$2" master_service="$3"
  3757. while read-0 relation_name target_service relation_config tech_dep; do
  3758. cat <<EOF
  3759. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3760. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3761. fontsize = 16
  3762. fontcolor = "black"
  3763. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3764. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3765. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3766. arrowtail = odot
  3767. # arrowhead = dotlicurve
  3768. taillabel = "$relation_name" ];
  3769. EOF
  3770. done < <(get_service_relations "$service") || return 1
  3771. }
  3772. _graph_node_service_label() {
  3773. local service="$1"
  3774. echo "service_$service"
  3775. }
  3776. _graph_node_service_content() {
  3777. local service="$1"
  3778. charm=$(get_service_charm "$service") || return 1
  3779. cat <<EOF
  3780. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3781. <tr>
  3782. <td bgcolor="black" align="center" colspan="2">
  3783. <font color="white">$service</font>
  3784. </td>
  3785. </tr>
  3786. $(if [ "$charm" != "$service" ]; then
  3787. cat <<EOF2
  3788. <tr>
  3789. <td align="left" port="r0">charm: $charm</td>
  3790. </tr>
  3791. EOF2
  3792. fi)
  3793. </table>
  3794. EOF
  3795. }
  3796. cla_contains () {
  3797. local e
  3798. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3799. return 1
  3800. }
  3801. filter_docker_compose_help_message() {
  3802. cat - |
  3803. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3804. s/docker-compose.yml/compose.yml/g;
  3805. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3806. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3807. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3808. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3809. }
  3810. graph() {
  3811. local services=("$@")
  3812. declare -A entries
  3813. cat <<EOF
  3814. digraph g {
  3815. graph [
  3816. fontsize=30
  3817. labelloc="t"
  3818. label=""
  3819. splines=true
  3820. overlap=false
  3821. #rankdir = "LR"
  3822. ];
  3823. ratio = auto;
  3824. EOF
  3825. for target_service in "$@"; do
  3826. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3827. for service in $services; do
  3828. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3829. if cla_contains "$service" "${services[@]}"; then
  3830. base=true
  3831. else
  3832. base=
  3833. fi
  3834. _graph_service "$service" "$base"
  3835. done
  3836. done
  3837. echo "}"
  3838. }
  3839. cached_wget() {
  3840. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  3841. url="$1"
  3842. if [ -e "$cache_file" ]; then
  3843. cat "$cache_file"
  3844. touch "$cache_file"
  3845. return 0
  3846. fi
  3847. wget -O- "${url}" |
  3848. tee "$cache_file"
  3849. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3850. rm "$cache_file"
  3851. die "Unable to fetch '$url'."
  3852. return 1
  3853. fi
  3854. }
  3855. export -f cached_wget
  3856. [ "$SOURCED" ] && return 0
  3857. trap_add "EXIT" clean_cache
  3858. export COMPOSE_DOCKER_REGISTRY="${COMPOSE_DOCKER_REGISTRY:-docker.0k.io}"
  3859. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3860. if [ -r /etc/default/charm ]; then
  3861. . "/etc/default/charm"
  3862. fi
  3863. if [ -r "/etc/default/$exname" ]; then
  3864. . "/etc/default/$exname"
  3865. fi
  3866. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3867. ## userdir ? and global /etc/compose.yml ?
  3868. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3869. /etc/default/compose /etc/compose/local.conf; do
  3870. [ -e "$cfgfile" ] || continue
  3871. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3872. done
  3873. fi
  3874. _setup_state_dir
  3875. mkdir -p "$CACHEDIR" || exit 1
  3876. log () { cat; }
  3877. export -f log
  3878. ##
  3879. ## Argument parsing
  3880. ##
  3881. wrap_opts=()
  3882. services=()
  3883. remainder_args=()
  3884. compose_opts=()
  3885. compose_contents=()
  3886. action_opts=()
  3887. services_args=()
  3888. pos_arg_ct=0
  3889. no_hooks=
  3890. no_init=
  3891. action=
  3892. stage="main" ## switches from 'main', to 'action', 'remainder'
  3893. is_docker_compose_action=
  3894. rebuild_relations_to_service=()
  3895. color=
  3896. declare -A without_relations
  3897. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3898. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  3899. while read-0 arg; do
  3900. case "$stage" in
  3901. "main")
  3902. case "$arg" in
  3903. --help|-h)
  3904. no_init=true ; no_hooks=true ; no_relations=true
  3905. display_help
  3906. exit 0
  3907. ;;
  3908. --verbose|-v)
  3909. export VERBOSE=true
  3910. compose_opts+=("--verbose")
  3911. ;;
  3912. --quiet|-q)
  3913. export QUIET=true
  3914. export wrap_opts+=("-q")
  3915. log () { cat >&2; }
  3916. export -f log
  3917. ;;
  3918. --version|-V)
  3919. print_version
  3920. docker-compose --version
  3921. docker --version
  3922. exit 0
  3923. ;;
  3924. -f|--file)
  3925. read-0 value
  3926. [ -e "$value" ] || die "File $value doesn't exists"
  3927. export COMPOSE_YML_FILE="$value"
  3928. shift
  3929. ;;
  3930. -p|--project-name)
  3931. read-0 value
  3932. export DEFAULT_PROJECT_NAME="$value"
  3933. compose_opts+=("--project-name $value")
  3934. shift
  3935. ;;
  3936. --color|-c)
  3937. if [ "$color" == "0" ]; then
  3938. err "Conflicting option --color with previous --no-ansi."
  3939. exit 1
  3940. fi
  3941. color=1
  3942. ansi_color yes
  3943. ;;
  3944. --no-ansi)
  3945. if [ "$color" == "1" ]; then
  3946. err "Conflicting option --no-ansi with previous --color."
  3947. exit 1
  3948. fi
  3949. color=0
  3950. ansi_color no
  3951. compose_opts+=("--no-ansi")
  3952. ;;
  3953. --no-relations)
  3954. export no_relations=true
  3955. ;;
  3956. --without-relation)
  3957. read-0 value
  3958. without_relations["$value"]=1
  3959. shift
  3960. ;;
  3961. --no-hooks)
  3962. export no_hooks=true
  3963. ;;
  3964. --no-init)
  3965. export no_init=true
  3966. ;;
  3967. --no-post-deploy)
  3968. export no_post_deploy=true
  3969. ;;
  3970. --no-pre-deploy)
  3971. export no_pre_deploy=true
  3972. ;;
  3973. --rebuild-relations-to-service|-R)
  3974. read-0 value
  3975. rebuild_relations_to_service+=("$value")
  3976. shift
  3977. ;;
  3978. --push-builds)
  3979. export COMPOSE_PUSH_TO_REGISTRY=1
  3980. ;;
  3981. --debug|-d)
  3982. export DEBUG=true
  3983. export VERBOSE=true
  3984. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3985. ;;
  3986. --add-compose-content|-Y)
  3987. read-0 value
  3988. compose_contents+=("$value")
  3989. shift
  3990. ;;
  3991. --dirs)
  3992. echo "CACHEDIR: $CACHEDIR"
  3993. echo "VARDIR: $VARDIR"
  3994. exit 0
  3995. ;;
  3996. --get-project-name)
  3997. project=$(get_default_project_name) || exit 1
  3998. echo "$project"
  3999. exit 0
  4000. ;;
  4001. --get-available-actions)
  4002. get_docker_charm_action
  4003. exit $?
  4004. ;;
  4005. --dry-compose-run)
  4006. export DRY_COMPOSE_RUN=true
  4007. ;;
  4008. --*|-*)
  4009. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4010. read-0 value
  4011. compose_opts+=("$arg" "$value")
  4012. shift;
  4013. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4014. compose_opts+=("$arg")
  4015. else
  4016. err "Unknown option '$arg'. Please check help:"
  4017. display_help >&2
  4018. exit 1
  4019. fi
  4020. ;;
  4021. *)
  4022. action="$arg"
  4023. stage="action"
  4024. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  4025. is_docker_compose_action=true
  4026. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  4027. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  4028. if [ "$DC_MATCH_MULTI" ]; then
  4029. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  4030. fi
  4031. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  4032. pos_args=("${pos_args[@]:1}")
  4033. # echo "USAGE: $DC_USAGE"
  4034. # echo "pos_args: ${pos_args[@]}"
  4035. # echo "MULTI: $DC_MATCH_MULTI"
  4036. # echo "SINGLE: $DC_MATCH_SINGLE"
  4037. # exit 1
  4038. else
  4039. stage="remainder"
  4040. fi
  4041. ;;
  4042. esac
  4043. ;;
  4044. "action") ## Only for docker-compose actions
  4045. case "$arg" in
  4046. --help|-h)
  4047. no_init=true ; no_hooks=true ; no_relations=true
  4048. action_opts+=("$arg")
  4049. ;;
  4050. --*|-*)
  4051. if [ "$is_docker_compose_action" ]; then
  4052. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  4053. read-0 value
  4054. action_opts+=("$arg" "$value")
  4055. shift
  4056. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  4057. action_opts+=("$arg")
  4058. else
  4059. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  4060. docker-compose "$action" --help |
  4061. filter_docker_compose_help_message >&2
  4062. exit 1
  4063. fi
  4064. fi
  4065. ;;
  4066. *)
  4067. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  4068. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  4069. services_args+=("$arg")
  4070. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  4071. services_args=("$arg") || exit 1
  4072. stage="remainder"
  4073. else
  4074. action_posargs+=("$arg")
  4075. ((pos_arg_ct++))
  4076. fi
  4077. ;;
  4078. esac
  4079. ;;
  4080. "remainder")
  4081. remainder_args+=("$arg")
  4082. while read-0 arg; do
  4083. remainder_args+=("$arg")
  4084. done
  4085. break 3
  4086. ;;
  4087. esac
  4088. shift
  4089. done < <(cla.normalize "$@")
  4090. case "$action" in
  4091. cache)
  4092. case "${remainder_args[0]}" in
  4093. clean)
  4094. clean_cache
  4095. exit 0
  4096. ;;
  4097. clear)
  4098. [ -n "$CACHEDIR" ] || die "No cache directory defined."
  4099. [ -d "$CACHEDIR" ] || die "Cache directory '$CACHEDIR' doesn't exists."
  4100. Wrap "${wrap_opts[@]}" -v -d "clear cache directory" -- rm -rf "$CACHEDIR/"*
  4101. ## clear all docker caches
  4102. ## image name are like '[$COMPOSE_DOCKER_REGISTRY]cache/charm/CHARM_NAME:HASH'
  4103. Wrap "${wrap_opts[@]}" -v -d "clear docker cache" <<EOF
  4104. docker images --format "{{.Repository}}:{{.Tag}}" |
  4105. egrep "^($COMPOSE_DOCKER_REGISTRY/)?cache/charm/[a-zA-Z0-9._-]+:[0-9a-f]{32,32}$" |
  4106. while read -r image; do
  4107. docker rmi "\$image" || true
  4108. done
  4109. EOF
  4110. exit 0
  4111. ;;
  4112. *)
  4113. err "Unknown cache command: ${DARKCYAN}${remainder_args[0]}${NORMAL}"
  4114. exit 1
  4115. ;;
  4116. esac
  4117. ;;
  4118. esac
  4119. export compose_contents
  4120. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  4121. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  4122. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  4123. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  4124. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  4125. aexport remainder_args
  4126. ##
  4127. ## Actual code
  4128. ##
  4129. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  4130. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  4131. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  4132. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  4133. ##
  4134. ## Get services in command line.
  4135. ##
  4136. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  4137. action_service=${remainder_args[0]}
  4138. if [ -z "$action_service" ]; then
  4139. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  4140. display_commands_help
  4141. exit 1
  4142. fi
  4143. ## Required by has_service_action
  4144. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  4145. NO_CONSTRAINT_CHECK=1 get_all_relations "${services_args[@]}" >/dev/null || exit 1
  4146. remainder_args=("${remainder_args[@]:1}")
  4147. if has_service_action "$action_service" "$action" >/dev/null; then
  4148. is_service_action=true
  4149. services_args=("$action_service")
  4150. {
  4151. read-0 action_type
  4152. case "$action_type" in
  4153. "relation")
  4154. read-0 _ target_service _target_charm relation_name _ action_script_path
  4155. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  4156. services_args+=("$target_service")
  4157. ;;
  4158. "direct")
  4159. read-0 _ action_script_path
  4160. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  4161. ;;
  4162. esac
  4163. } < <(has_service_action "$action_service" "$action")
  4164. get_all_relations "${services_args[@]}" >/dev/null || {
  4165. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  4166. exit 1
  4167. }
  4168. ## Divert logging to stdout to stderr
  4169. log () { cat >&2; }
  4170. export -f log
  4171. else
  4172. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  4173. fi
  4174. else
  4175. case "$action" in
  4176. ps|up)
  4177. if [ "${#services_args[@]}" == 0 ]; then
  4178. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  4179. fi
  4180. ;;
  4181. config)
  4182. services_args=("${action_posargs[@]}")
  4183. ;;
  4184. esac
  4185. fi
  4186. export COMPOSE_ACTION="$action"
  4187. NO_CONSTRAINT_CHECK=True
  4188. case "$action" in
  4189. up)
  4190. NO_CONSTRAINT_CHECK=
  4191. ;;
  4192. esac
  4193. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  4194. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  4195. services=($(get_master_services "${services_args[@]}")) || exit 1
  4196. if [ "$action" == "up" ]; then
  4197. declare -A seen
  4198. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  4199. mservice=$(get_master_service_for_service "$service") || exit 1
  4200. [ "${seen[$mservice]}" ] && continue
  4201. type="$(get_service_type "$mservice")" || exit 1
  4202. ## remove run-once
  4203. [ "$type" == "run-once" ] && continue
  4204. [ "$type" == "stub" ] && continue
  4205. seen[$mservice]=1
  4206. action_posargs+=("$mservice")
  4207. done
  4208. else
  4209. action_posargs+=("${services[@]}")
  4210. fi
  4211. ## Get rid of subordinates
  4212. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  4213. fi
  4214. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  4215. err "Fails to compile base 'docker-compose.yml'"
  4216. exit 1
  4217. }
  4218. ##
  4219. ## Pre-action
  4220. ##
  4221. full_init=
  4222. case "$action" in
  4223. up|run)
  4224. full_init=true
  4225. post_hook=true
  4226. ;;
  4227. ""|down|restart|logs|config|ps)
  4228. full_init=
  4229. ;;
  4230. *)
  4231. if [ "$is_service_action" ]; then
  4232. full_init=true
  4233. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4234. for keyword in "${keywords[@]}"; do
  4235. case "$keyword" in
  4236. no-hooks)
  4237. no_hooks=true
  4238. ;;
  4239. hooks)
  4240. full_init=true
  4241. ;;
  4242. esac
  4243. done
  4244. fi
  4245. ;;
  4246. esac
  4247. if [ -n "$full_init" ]; then
  4248. ## init in order
  4249. if [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4250. Section setup host resources
  4251. setup_host_resources "${services_args[@]}" || exit 1
  4252. Section "acquire charm's images"
  4253. run_service_acquire_images "${services_args[@]}" || exit 1
  4254. Feed
  4255. Section initialisation
  4256. run_service_hook init "${services_args[@]}" || exit 1
  4257. fi
  4258. ## Get relations
  4259. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4260. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4261. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4262. rebuild_relations_to_service=($rebuild_relations_to_service)
  4263. project=$(get_default_project_name) || return 1
  4264. for service in "${rebuild_relations_to_service[@]}"; do
  4265. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  4266. [ -d "$dir" ] && {
  4267. debug rm -rf "$dir"
  4268. rm -rf "$dir"
  4269. }
  4270. done
  4271. done
  4272. fi
  4273. run_service_relations "${services_args[@]}" || exit 1
  4274. fi
  4275. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  4276. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  4277. fi
  4278. fi | log
  4279. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4280. exit 1
  4281. fi
  4282. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  4283. charm=$(get_service_charm "${services_args[0]}") || exit 1
  4284. metadata=$(charm.metadata "$charm") || exit 1
  4285. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  4286. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4287. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  4288. fi
  4289. fi
  4290. export SERVICE_PACK="${services_args[*]}"
  4291. ##
  4292. ## Docker-compose
  4293. ##
  4294. errlvl="0"
  4295. case "$action" in
  4296. up|start|stop|build|run)
  4297. ## force daemon mode for up
  4298. if [[ "$action" == "up" ]]; then
  4299. if ! array_member action_opts -d; then
  4300. action_opts+=("-d")
  4301. fi
  4302. if ! array_member action_opts --remove-orphans; then
  4303. action_opts+=("--remove-orphans")
  4304. fi
  4305. fi
  4306. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4307. ;;
  4308. logs)
  4309. if ! array_member action_opts --tail; then ## force daemon mode for up
  4310. action_opts+=("--tail" "10")
  4311. fi
  4312. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4313. ;;
  4314. "")
  4315. launch_docker_compose "${compose_opts[@]}"
  4316. ;;
  4317. graph)
  4318. graph $SERVICE_PACK
  4319. ;;
  4320. config)
  4321. ## removing the services
  4322. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  4323. ## forcing docker-compose config to output the config file to stdout and not stderr
  4324. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  4325. echo "$out"
  4326. exit 1
  4327. }
  4328. echo "$out"
  4329. warn "Runtime configuration modification (from relations) are not included here."
  4330. ;;
  4331. down)
  4332. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  4333. debug "Adding a default argument of '--remove-orphans'"
  4334. action_opts+=("--remove-orphans")
  4335. fi
  4336. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  4337. ;;
  4338. *)
  4339. if [ "$is_service_action" ]; then
  4340. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  4341. errlvl="$?"
  4342. errlvl "$errlvl"
  4343. else
  4344. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4345. fi
  4346. ;;
  4347. esac || exit 1
  4348. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  4349. run_service_hook post_deploy "${services_args[@]}" || exit 1
  4350. fi
  4351. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  4352. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4353. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  4354. fi
  4355. fi
  4356. clean_unused_docker_compose || exit 1
  4357. exit "$errlvl"