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.

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