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.

4759 lines
158 KiB

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