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.

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