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.

4790 lines
159 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}_${master_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 "${image_name}" >&2 || {
  1213. err "Failed to build image '${image_name}' for ${DARKYELLOW}$service${NORMAL}."
  1214. return 1
  1215. }
  1216. fi
  1217. printf "%s" "${image_name}"
  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. ## From a service and a relation, get all relations targeting given
  1884. ## service with given relation.
  1885. ##
  1886. ## Returns a NUL separated list of couple of:
  1887. ## (base_service, relation_config)
  1888. ##
  1889. get_service_incoming_relations() {
  1890. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")" \
  1891. s rn ts rc td
  1892. if [ -e "$cache_file" ]; then
  1893. #debug "$FUNCNAME: SESSION cache hit $1"
  1894. cat "$cache_file"
  1895. return 0
  1896. fi
  1897. if [ -z "$ALL_RELATIONS" ]; then
  1898. err "Can't access global \$ALL_RELATIONS"
  1899. return 1
  1900. fi
  1901. while read-0 s rn ts rc _td; do
  1902. [[ "$ts" == "$service" ]] || continue
  1903. [[ "$rn" == "$relation" ]] || continue
  1904. relation_data_file=$(get_relation_data_file "$s" "$ts" "$rn" "$rc") || return 1
  1905. printf "%s\0" "$s" "$(cat "$relation_data_file")"
  1906. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  1907. cat "$cache_file"
  1908. }
  1909. export -f get_service_incoming_relations
  1910. export TRAVERSE_SEPARATOR=:
  1911. ## Traverse on first service satisfying relation
  1912. service:traverse() {
  1913. local service_path="$1"
  1914. {
  1915. SEPARATOR=:
  1916. read -d "$TRAVERSE_SEPARATOR" service
  1917. while read -d "$TRAVERSE_SEPARATOR" relation; do
  1918. ## XXXvlab: Take only first service
  1919. if ! read-0 ts _ _ < <(get_service_relation "${service}" "${relation}"); then
  1920. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  1921. "from ${DARKYELLOW}$service${NORMAL}."
  1922. return 1
  1923. fi
  1924. service="$ts"
  1925. done
  1926. echo "$service"
  1927. } < <(e "${service_path}${TRAVERSE_SEPARATOR}")
  1928. }
  1929. export -f service:traverse
  1930. service:relation-file() {
  1931. local service_path="$1" relation service relation_file
  1932. if ! [[ "$service_path" == *"$TRAVERSE_SEPARATOR"* ]]; then
  1933. err "Invalid argument '$service_path'." \
  1934. "Must provide a service path (no '${TRAVERSE_SEPARATOR}' found)."
  1935. return 1
  1936. fi
  1937. relation="${service_path##*${TRAVERSE_SEPARATOR}}"
  1938. service=$(service:traverse "${service_path%${TRAVERSE_SEPARATOR}*}") || return 1
  1939. if ! read-0 ts rc _ < <(get_service_relation "${service}" "${relation}"); then
  1940. err "Couldn't find relation ${DARKCYAN}${relation}${NORMAL}" \
  1941. "from ${DARKYELLOW}$service${NORMAL}."
  1942. return 1
  1943. fi
  1944. relation_dir=$(get_relation_data_dir "$service" "$ts" "$relation") || {
  1945. err "Failed to find relation file"
  1946. return 1
  1947. }
  1948. relation_file="$relation_dir/data"
  1949. if ! [ -e "$relation_file" ]; then
  1950. e "$rc" > "$relation_file"
  1951. chmod go-rwx "$relation_file" ## protecting this file
  1952. fi
  1953. echo "$relation_file"
  1954. }
  1955. export -f service:relation-file
  1956. service:relation-options() {
  1957. local service_path="$1" relation_file
  1958. relation_file=$(service:relation-file "$service_path") || {
  1959. err "Failed to find relation file"
  1960. return 1
  1961. }
  1962. cat "$relation_file"
  1963. }
  1964. export -f service:relation-options
  1965. relation:get() {
  1966. local service_path="$1" query="$2" relation_file
  1967. relation_file=$(service:relation-file "$service_path") || {
  1968. err "Failed to find relation file"
  1969. return 1
  1970. }
  1971. cfg-get-value "$query" < "$relation_file"
  1972. }
  1973. export -f relation:get
  1974. _get_charm_metadata_uses() {
  1975. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  1976. if [ -e "$cache_file" ]; then
  1977. #debug "$FUNCNAME: SESSION cache hit $1"
  1978. cat "$cache_file" || return 1
  1979. return 0
  1980. fi
  1981. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  1982. }
  1983. export -f _get_charm_metadata_uses
  1984. _get_service_metadata() {
  1985. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1986. charm
  1987. if [ -e "$cache_file" ]; then
  1988. #debug "$FUNCNAME: SESSION cache hit $1"
  1989. cat "$cache_file"
  1990. return 0
  1991. fi
  1992. charm="$(get_service_charm "$service")" || return 1
  1993. charm.metadata "$charm" > "$cache_file"
  1994. if [ "$?" != 0 ]; then
  1995. rm -f "$cache_file" ## no cache
  1996. return 1
  1997. fi
  1998. cat "$cache_file"
  1999. }
  2000. export -f _get_service_metadata
  2001. _get_service_uses() {
  2002. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2003. metadata
  2004. if [ -e "$cache_file" ]; then
  2005. #debug "$FUNCNAME: SESSION cache hit $1"
  2006. cat "$cache_file"
  2007. return 0
  2008. fi
  2009. metadata="$(_get_service_metadata "$service")" || return 1
  2010. _get_charm_metadata_uses "$metadata" > "$cache_file"
  2011. if [ "$?" != 0 ]; then
  2012. rm -f "$cache_file" ## no cache
  2013. return 1
  2014. fi
  2015. cat "$cache_file"
  2016. }
  2017. export -f _get_service_uses
  2018. _get_services_uses() {
  2019. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2020. service rn rd
  2021. if [ -e "$cache_file" ]; then
  2022. #debug "$FUNCNAME: SESSION cache hit $1"
  2023. cat "$cache_file"
  2024. return 0
  2025. fi
  2026. for service in "$@"; do
  2027. _get_service_uses "$service" | while read-0 rn rd; do
  2028. printf "%s\0" "$service" "$rn" "$rd"
  2029. done
  2030. [ "${PIPESTATUS[0]}" == 0 ] || {
  2031. return 1
  2032. }
  2033. done > "${cache_file}.wip"
  2034. mv "${cache_file}"{.wip,} &&
  2035. cat "$cache_file" || return 1
  2036. }
  2037. export -f _get_services_uses
  2038. _get_provides_provides() {
  2039. local provides="$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 $1"
  2043. cat "$cache_file"
  2044. return 0
  2045. fi
  2046. type=$(printf "%s" "$provides" | shyaml get-type)
  2047. case "$type" in
  2048. sequence)
  2049. while read-0 prov; do
  2050. printf "%s\0" "$prov" ""
  2051. done < <(echo "$provides" | shyaml get-values-0)
  2052. ;;
  2053. struct)
  2054. printf "%s" "$provides" | shyaml key-values-0
  2055. ;;
  2056. str)
  2057. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  2058. ;;
  2059. *)
  2060. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  2061. return 1
  2062. esac | tee "$cache_file"
  2063. return "${PIPESTATUS[0]}"
  2064. }
  2065. _get_metadata_provides() {
  2066. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2067. service rn rd
  2068. if [ -e "$cache_file" ]; then
  2069. #debug "$FUNCNAME: CACHEDIR cache hit"
  2070. cat "$cache_file"
  2071. return 0
  2072. fi
  2073. provides=$(printf "%s" "$metadata" | shyaml -q get-value -y provides "")
  2074. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  2075. _get_provides_provides "$provides" | tee "$cache_file"
  2076. return "${PIPESTATUS[0]}"
  2077. }
  2078. _get_services_provides() {
  2079. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2080. service rn rd
  2081. if [ -e "$cache_file" ]; then
  2082. #debug "$FUNCNAME: SESSION cache hit $1"
  2083. cat "$cache_file"
  2084. return 0
  2085. fi
  2086. ## YYY: replace the inner loop by a cached function
  2087. for service in "$@"; do
  2088. metadata="$(_get_service_metadata "$service")" || return 1
  2089. while read-0 rn rd; do
  2090. printf "%s\0" "$service" "$rn" "$rd"
  2091. done < <(_get_metadata_provides "$metadata")
  2092. done > "$cache_file"
  2093. if [ "$?" != 0 ]; then
  2094. rm -f "$cache_file" ## no cache
  2095. return 1
  2096. fi
  2097. cat "$cache_file"
  2098. }
  2099. export -f _get_services_provides
  2100. _get_charm_provides() {
  2101. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(charm.store_metadata_hash)" errlvl
  2102. if [ -e "$cache_file" ]; then
  2103. #debug "$FUNCNAME: SESSION cache hit"
  2104. cat "$cache_file"
  2105. return 0
  2106. fi
  2107. start="$SECONDS"
  2108. debug "Getting charm provider list..."
  2109. while read-0 charm _ realpath metadata; do
  2110. metadata="$(charm.metadata "$charm")" || continue
  2111. # echo "reading $charm" >&2
  2112. while read-0 rn rd; do
  2113. printf "%s\0" "$charm" "$rn" "$rd"
  2114. done < <(_get_metadata_provides "$metadata")
  2115. done < <(charm.ls) | tee "$cache_file"
  2116. errlvl="${PIPESTATUS[0]}"
  2117. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  2118. return "$errlvl"
  2119. }
  2120. _get_charm_providing() {
  2121. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2122. relation="$1"
  2123. if [ -e "$cache_file" ]; then
  2124. #debug "$FUNCNAME: SESSION cache hit $1"
  2125. cat "$cache_file"
  2126. return 0
  2127. fi
  2128. while read-0 charm relation_name relation_def; do
  2129. [ "$relation_name" == "$relation" ] || continue
  2130. printf "%s\0" "$charm" "$relation_def"
  2131. done < <(_get_charm_provides) > "$cache_file"
  2132. if [ "$?" != 0 ]; then
  2133. rm -f "$cache_file" ## no cache
  2134. return 1
  2135. fi
  2136. cat "$cache_file"
  2137. }
  2138. _get_services_providing() {
  2139. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  2140. relation="$1"
  2141. shift ## services is "$@"
  2142. if [ -e "$cache_file" ]; then
  2143. #debug "$FUNCNAME: SESSION cache hit $1"
  2144. cat "$cache_file"
  2145. return 0
  2146. fi
  2147. while read-0 service relation_name relation_def; do
  2148. [ "$relation_name" == "$relation" ] || continue
  2149. printf "%s\0" "$service" "$relation_def"
  2150. done < <(_get_services_provides "$@") > "$cache_file"
  2151. if [ "$?" != 0 ]; then
  2152. rm -f "$cache_file" ## no cache
  2153. return 1
  2154. fi
  2155. cat "$cache_file"
  2156. }
  2157. export -f _get_services_provides
  2158. _out_new_relation_from_defs() {
  2159. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  2160. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2161. ## YYYvlab: should be seen even in no debug mode no ?
  2162. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2163. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  2164. td=${td:-True}
  2165. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  2166. after=$(_out_after_value_from_def "$service" "$rn" "$rel_def") || return 1
  2167. printf "%s\0" "$after" "$service" "$relation_name" "$ts" "$rc" "$td"
  2168. }
  2169. _out_after_value_from_def() {
  2170. local service="$1" relation_name="$2" relation_def="$3" after_t after
  2171. if after_t=$(echo "$relation_def" | shyaml get-type after 2>/dev/null); then
  2172. case "$after_t" in
  2173. sequence)
  2174. after="$(echo "$relation_def" | shyaml get-values after 2>/dev/null)" || return 1
  2175. after=",$service:${after//$'\n'/,$service:},"
  2176. ;;
  2177. struct)
  2178. err "Invalid type for ${WHITE}after${NORMAL}'s value in ${DARKBLUE}$relation_name${NORMAL}'s definition."
  2179. return 1
  2180. ;;
  2181. str)
  2182. after=",$service:$(echo "$relation_def" | shyaml get-value after "" 2>/dev/null)," || return 1
  2183. ;;
  2184. esac
  2185. else
  2186. after=""
  2187. fi
  2188. e "$after"
  2189. }
  2190. get_all_relations () {
  2191. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -p without_relations)")" \
  2192. services
  2193. if [ -n "$ALL_RELATIONS" ]; then
  2194. cat "$ALL_RELATIONS" || return 1
  2195. return 0
  2196. fi
  2197. if [ -e "${cache_file}" ]; then
  2198. #debug "$FUNCNAME: SESSION cache hit $1"
  2199. export ALL_RELATIONS="$cache_file"
  2200. cat "${cache_file}"
  2201. return 0
  2202. fi
  2203. declare -A services
  2204. services_uses=()
  2205. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2206. _get_services_uses "$@" || return 1
  2207. array_read-0 services_uses < <(_get_services_uses "$@")
  2208. services_provides=()
  2209. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  2210. _get_services_provides "$@" || return 1
  2211. array_read-0 services_provides < <(_get_services_provides "$@")
  2212. for service in "$@"; do
  2213. services[$service]=1
  2214. done
  2215. all_services=("$@")
  2216. while [ "${#all_services[@]}" != 0 ]; do
  2217. array_pop all_services service
  2218. while read-0 relation_name ts relation_config tech_dep; do
  2219. [ "${without_relations[$service:$relation_name]}" ] && {
  2220. debug "Ignoring compose $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> ${DARKYELLOW}$ts$NORMAL"
  2221. continue
  2222. }
  2223. ## First is priority, that can be adjusted in second step
  2224. printf "%s\0" "" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  2225. ## adding target services ?
  2226. [ "${services[$ts]}" ] && continue
  2227. array_read-0 services_uses < <(_get_services_uses "$ts")
  2228. all_services+=("$ts")
  2229. services[$ts]=1
  2230. done < <(get_compose_relations "$service")
  2231. done > "${cache_file}.wip"
  2232. while true; do
  2233. changed=
  2234. new_services_uses=()
  2235. summon=()
  2236. required=()
  2237. recommended=()
  2238. optional=()
  2239. while [ "${#services_uses[@]}" != 0 ]; do
  2240. service="${services_uses[0]}"
  2241. relation_name="${services_uses[1]}"
  2242. relation_def="${services_uses[2]}"
  2243. services_uses=("${services_uses[@]:3}")
  2244. [ "${without_relations[$service:$relation_name]}" ] && {
  2245. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2246. continue
  2247. }
  2248. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  2249. after=$(_out_after_value_from_def "$service" "$relation_name" "$relation_def") || return 1
  2250. ## is this "use" declaration satisfied ?
  2251. found=
  2252. while read-0 p s rn ts rc td; do
  2253. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  2254. if [ "$default_options" ]; then
  2255. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2256. fi
  2257. found="$ts"
  2258. p="$after"
  2259. fi
  2260. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td"
  2261. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2262. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2263. if [ "$found" ]; then ## this "use" declaration was satisfied
  2264. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation" \
  2265. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2266. continue
  2267. fi
  2268. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2269. auto=${auto:-pair}
  2270. case "$auto" in
  2271. "pair"|"summon")
  2272. service_list=()
  2273. array_read-0 service_list < <(array_keys_to_stdin services)
  2274. providers=()
  2275. providers_def=()
  2276. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2277. if [ "${#providers[@]}" == 1 ]; then
  2278. ts="${providers[0]}"
  2279. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2280. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2281. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2282. "${providers_def[0]}" "$relation_def" \
  2283. >> "${cache_file}.wip"
  2284. ## Adding service
  2285. [ "${services[$ts]}" ] && continue
  2286. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2287. services[$ts]=1
  2288. changed=1
  2289. continue
  2290. elif [ "${#providers[@]}" -gt 1 ]; then
  2291. msg=""
  2292. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2293. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2294. "(> 1 provider)."
  2295. continue
  2296. else
  2297. if [ "$auto" == "summon" ]; then
  2298. summon+=("$service" "$relation_name" "$relation_def")
  2299. fi
  2300. fi
  2301. ;;
  2302. null|disable|disabled)
  2303. :
  2304. ;;
  2305. *)
  2306. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2307. return 1
  2308. ;;
  2309. esac
  2310. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2311. constraint=${constraint:-optional}
  2312. case "$constraint" in
  2313. "required")
  2314. required+=("$service" "$relation_name" "$relation_def")
  2315. ;;
  2316. "recommended")
  2317. recommended+=("$service" "$relation_name" "$relation_def")
  2318. ;;
  2319. "optional")
  2320. optional+=("$service" "$relation_name" "$relation_def")
  2321. ;;
  2322. *)
  2323. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2324. return 1
  2325. ;;
  2326. esac
  2327. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2328. done
  2329. services_uses=("${new_services_uses[@]}")
  2330. if [ "$changed" ]; then
  2331. continue
  2332. fi
  2333. ## situation is stable
  2334. if [ "${#summon[@]}" != 0 ]; then
  2335. declare -A summon_requeued=()
  2336. while [ "${#summon[@]}" != 0 ]; do
  2337. service="${summon[0]}"
  2338. relation_name="${summon[1]}"
  2339. relation_def="${summon[2]}"
  2340. summon=("${summon[@]:3}")
  2341. providers=()
  2342. providers_def=()
  2343. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2344. if [ "${#providers[@]}" == 0 ]; then
  2345. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2346. return 1
  2347. fi
  2348. if [ "${#providers[@]}" -gt 1 ]; then
  2349. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2350. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2351. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2352. "(> 1 provider). Requeing."
  2353. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2354. summon_requeued["$service/$relation_name"]=1
  2355. continue
  2356. else
  2357. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2358. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2359. "(> 1 provider). Choosing first."
  2360. fi
  2361. fi
  2362. ts="${providers[0]}"
  2363. ## YYYvlab: should be seen even in no debug mode no ?
  2364. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2365. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2366. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2367. "${providers_def[0]}" "$relation_def" \
  2368. >> "${cache_file}.wip"
  2369. ## Adding service
  2370. [ "${services[$ts]}" ] && continue
  2371. array_read-0 services_uses < <(_get_services_uses "$ts")
  2372. services[$ts]=1
  2373. changed=1
  2374. continue 2
  2375. done
  2376. continue
  2377. fi
  2378. [ "$NO_CONSTRAINT_CHECK" ] && break
  2379. if [ "${#required[@]}" != 0 ]; then
  2380. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2381. err "Required relations not satisfied"
  2382. return 1
  2383. fi
  2384. if [ "${#recommended[@]}" != 0 ]; then
  2385. ## make recommendation
  2386. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2387. fi
  2388. if [ -z "$QUIET" ]; then
  2389. if [ "${#optional[@]}" != 0 ]; then
  2390. ## inform about options
  2391. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2392. fi
  2393. fi
  2394. # if [ "${#required[@]}" != 0 ]; then
  2395. # err "Required relations not satisfied"
  2396. # return 1
  2397. # fi
  2398. if [ "${#recommended[@]}" != 0 ]; then
  2399. warn "Recommended relations not satisfied"
  2400. fi
  2401. break
  2402. done
  2403. if [ "$?" != 0 ]; then
  2404. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2405. return 1
  2406. fi
  2407. ##
  2408. ## Sort relations thanks to uses =metadata.yml= relations.
  2409. ##
  2410. mv "${cache_file}.wip"{,.in} &&
  2411. rm -f "${cache_file}.wip.final" &&
  2412. touch "${cache_file}.wip.final" || {
  2413. err "Unexpected error when mangling cache files."
  2414. return 1
  2415. }
  2416. declare -A relation_done=()
  2417. while true; do
  2418. had_remaining_relation=
  2419. had_new_relation=
  2420. while read-0 p s rn ts rc td; do
  2421. if [ -z "$p" ] || [ "$p" == "," ]; then
  2422. relation_done["$s:$rn"]=1
  2423. # printf " .. %-30s %-30s %-30s\n" "--" "$s" "$rn" >&2
  2424. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  2425. had_new_relation=1
  2426. else
  2427. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2428. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2429. had_remaining_relation=1
  2430. fi
  2431. done < "${cache_file}.wip.in"
  2432. [ -z "$had_remaining_relation" ] && break
  2433. mv "${cache_file}.wip."{out,in}
  2434. while read-0 p s rn ts rc td; do
  2435. for rel in "${!relation_done[@]}"; do
  2436. p="${p//,$rel,/,}"
  2437. done
  2438. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2439. if [ -z "$had_new_relation" ]; then
  2440. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  2441. for rel in ${p//,/ }; do
  2442. rel_s=${rel%%:*}
  2443. rel_r=${rel##*:}
  2444. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  2445. done
  2446. else
  2447. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2448. fi
  2449. done < "${cache_file}.wip.in"
  2450. if [ -z "$had_new_relation" ]; then
  2451. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  2452. return 1
  2453. fi
  2454. mv "${cache_file}.wip."{out,in}
  2455. done
  2456. export ALL_RELATIONS="$cache_file"
  2457. mv "${cache_file}"{.wip.final,} || return 1
  2458. cat "$cache_file"
  2459. }
  2460. export -f get_all_relations
  2461. _display_solves() {
  2462. local array_name="$1" by_relation msg
  2463. ## inform about options
  2464. msg=""
  2465. declare -A by_relation
  2466. while read-0 service relation_name relation_def; do
  2467. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2468. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2469. if [ -z "$solves" ]; then
  2470. continue
  2471. fi
  2472. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2473. if [ "$auto" == "pair" ]; then
  2474. requirement="add provider in cluster to auto-pair"
  2475. else
  2476. requirement="add explicit relation"
  2477. fi
  2478. while read-0 name def; do
  2479. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2480. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2481. done < <(array_values_to_stdin "$array_name")
  2482. while read-0 relation_name message; do
  2483. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2484. "$relation_name" "$message" )"
  2485. done < <(array_kv_to_stdin by_relation)
  2486. if [ "$msg" ]; then
  2487. printf "%s\n" "${msg:1}"
  2488. fi
  2489. }
  2490. get_compose_relation_def() {
  2491. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2492. while read-0 relation_name target_service relation_config tech_dep; do
  2493. [ "$relation_name" == "$relation" ] || continue
  2494. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2495. done < <(get_compose_relations "$service") || return 1
  2496. }
  2497. export -f get_compose_relation_def
  2498. run_service_relations () {
  2499. local service services loaded subservices subservice
  2500. PROJECT_NAME=$(get_default_project_name) || return 1
  2501. export PROJECT_NAME
  2502. declare -A loaded
  2503. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2504. for service in $subservices; do
  2505. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2506. for subservice in $(get_service_deps "$service") "$service"; do
  2507. [ "${loaded[$subservice]}" ] && continue
  2508. export BASE_SERVICE_NAME=$service
  2509. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2510. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2511. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2512. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2513. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2514. while read-0 relation_name target_service relation_config tech_dep; do
  2515. [ "${without_relations[$service:$relation_name]}" ] && {
  2516. debug "Skipping $DARKYELLOW$service$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW*$NORMAL"
  2517. continue
  2518. }
  2519. export relation_config
  2520. export TARGET_SERVICE_NAME=$target_service
  2521. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2522. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2523. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2524. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2525. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2526. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2527. EOF
  2528. done < <(get_service_relations "$subservice") || return 1
  2529. loaded[$subservice]=1
  2530. done
  2531. done
  2532. }
  2533. export -f run_service_relations
  2534. _run_service_action_direct() {
  2535. local service="$1" action="$2" charm _dummy project_name
  2536. shift; shift
  2537. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  2538. if read-0 _dummy || [ "$_dummy" ]; then
  2539. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2540. return 1
  2541. fi
  2542. project_name=$(get_default_project_name) || return 1
  2543. export PROJECT_NAME="$project_name"
  2544. export state_tmpdir
  2545. (
  2546. set +e ## Prevents unwanted leaks from parent shell
  2547. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2548. export METADATA_CONFIG=$(charm.metadata "$charm")
  2549. export SERVICE_NAME=$service
  2550. export ACTION_NAME=$action
  2551. export ACTION_SCRIPT_PATH="$action_script_path"
  2552. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2553. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2554. export SERVICE_DATASTORE="$DATASTORE/$service"
  2555. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2556. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2557. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2558. ) 0<&6 ## inject general stdin
  2559. }
  2560. export -f _run_service_action_direct
  2561. _run_service_action_relation() {
  2562. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2563. shift; shift
  2564. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  2565. if read-0 _dummy || [ "$_dummy" ]; then
  2566. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2567. return 1
  2568. fi
  2569. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2570. export state_tmpdir
  2571. (
  2572. set +e ## Prevents unwanted leaks from parent shell
  2573. export METADATA_CONFIG=$(charm.metadata "$charm")
  2574. export SERVICE_NAME=$service
  2575. export RELATION_TARGET_SERVICE="$target_service"
  2576. export RELATION_TARGET_CHARM="$target_charm"
  2577. export RELATION_BASE_SERVICE="$service"
  2578. export RELATION_BASE_CHARM="$charm"
  2579. export ACTION_NAME=$action
  2580. export ACTION_SCRIPT_PATH="$action_script_path"
  2581. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2582. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2583. export SERVICE_DATASTORE="$DATASTORE/$service"
  2584. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2585. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2586. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2587. ) 0<&6 ## inject general stdin
  2588. }
  2589. export -f _run_service_action_relation
  2590. get_relation_data_dir() {
  2591. local service="$1" target_service="$2" relation_name="$3" \
  2592. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2593. if [ -e "$cache_file" ]; then
  2594. # debug "$FUNCNAME: cache hit ($*)"
  2595. cat "$cache_file"
  2596. return 0
  2597. fi
  2598. local project relation_dir
  2599. project=${PROJECT_NAME}
  2600. if [ -z "$project" ]; then
  2601. project=$(get_default_project_name) || return 1
  2602. fi
  2603. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2604. if ! [ -d "$relation_dir" ]; then
  2605. mkdir -p "$relation_dir" || return 1
  2606. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2607. fi
  2608. echo "$relation_dir" | tee "$cache_file"
  2609. }
  2610. export -f get_relation_data_dir
  2611. get_relation_data_file() {
  2612. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2613. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2614. relation_data_file="$relation_dir/data"
  2615. new=
  2616. if [ -e "$relation_data_file" ]; then
  2617. ## Has reference changed ?
  2618. new_md5=$(e "$relation_config" | md5_compat)
  2619. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2620. new=true
  2621. fi
  2622. else
  2623. new=true
  2624. fi
  2625. if [ "$new" ]; then
  2626. e "$relation_config" > "$relation_data_file"
  2627. chmod go-rwx "$relation_data_file" ## protecting this file
  2628. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2629. fi
  2630. echo "$relation_data_file"
  2631. }
  2632. export -f get_relation_data_file
  2633. has_service_action () {
  2634. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2635. charm target_charm relation_name target_service relation_config _tech_dep \
  2636. path
  2637. if [ -e "$cache_file" ]; then
  2638. # debug "$FUNCNAME: cache hit ($*)"
  2639. cat "$cache_file"
  2640. return 0
  2641. fi
  2642. charm=$(get_service_charm "$service") || return 1
  2643. ## Action directly provided ?
  2644. if path=$(charm.has_direct_action "$charm" "$action"); then
  2645. p0 "direct" "$charm" "$path" | tee "$cache_file"
  2646. return 0
  2647. fi
  2648. ## Action provided by relation ?
  2649. while read-0 relation_name target_service relation_config _tech_dep; do
  2650. target_charm=$(get_service_charm "$target_service") || return 1
  2651. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  2652. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  2653. return 0
  2654. fi
  2655. done < <(get_service_relations "$service")
  2656. return 1
  2657. # master=$(get_top_master_service_for_service "$service")
  2658. # [ "$master" == "$charm" ] && return 1
  2659. # has_service_action "$master" "$action"
  2660. }
  2661. export -f has_service_action
  2662. run_service_action () {
  2663. local service="$1" action="$2" errlvl
  2664. shift ; shift
  2665. exec 6<&0 ## saving stdin
  2666. {
  2667. if ! read-0 action_type; then
  2668. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2669. info " Add an executable script to 'actions/$action' to implement action."
  2670. return 1
  2671. fi
  2672. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2673. errlvl="$?"
  2674. } < <(has_service_action "$service" "$action")
  2675. exec 0<&6 6<&- ## restoring stdin
  2676. return "$errlvl"
  2677. }
  2678. export -f run_service_action
  2679. get_compose_relation_config() {
  2680. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2681. if [ -e "$cache_file" ]; then
  2682. # debug "$FUNCNAME: cache hit ($*)"
  2683. cat "$cache_file"
  2684. return 0
  2685. fi
  2686. compose_service_def=$(get_compose_service_def "$service") || return 1
  2687. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2688. }
  2689. export -f get_compose_relation_config
  2690. # ## Return key-values-0
  2691. # get_compose_relation_config_for_service() {
  2692. # local service=$1 relation_name=$2 relation_config
  2693. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2694. # if ! relation_config=$(
  2695. # echo "$compose_service_relations" |
  2696. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2697. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2698. # "relation config in compose configuration."
  2699. # return 1
  2700. # fi
  2701. # if [ -z "$relation_config" ]; then
  2702. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2703. # return 1
  2704. # fi
  2705. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2706. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2707. # return 1
  2708. # fi
  2709. # }
  2710. # export -f get_compose_relation_config_for_service
  2711. _get_container_relation() {
  2712. local metadata=$1 found relation_name relation_def
  2713. found=
  2714. while read-0 relation_name relation_def; do
  2715. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2716. found="$relation_name"
  2717. break
  2718. }
  2719. done < <(_get_charm_metadata_uses "$metadata")
  2720. if [ -z "$found" ]; then
  2721. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2722. "${WHITE}scope${NORMAL} set to 'container'."
  2723. return 1
  2724. fi
  2725. printf "%s" "$found"
  2726. }
  2727. _get_master_service_for_service_cached () {
  2728. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2729. charm requires master_charm target_charm target_service service_def found
  2730. if [ -e "$cache_file" ]; then
  2731. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2732. cat "$cache_file" &&
  2733. touch "$cache_file" || return 1
  2734. return 0
  2735. fi
  2736. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  2737. ## just return service name
  2738. echo "$service" | tee "$cache_file"
  2739. return 0
  2740. fi
  2741. ## Action provided by relation ?
  2742. container_relation=$(_get_container_relation "$metadata") || return 1
  2743. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2744. if [ -z "$target_service" ]; then
  2745. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2746. "${DARKYELLOW}$service$NORMAL compose definition."
  2747. err ${FUNCNAME[@]}
  2748. return 1
  2749. fi
  2750. echo "$target_service" | tee "$cache_file"
  2751. }
  2752. export -f _get_master_service_for_service_cached
  2753. get_master_service_for_service() {
  2754. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2755. charm metadata result
  2756. if [ -e "$cache_file" ]; then
  2757. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2758. cat "$cache_file" || return 1
  2759. return 0
  2760. fi
  2761. charm=$(get_service_charm "$service") || return 1
  2762. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2763. metadata=""
  2764. warn "No charm $DARKPINK$charm$NORMAL found."
  2765. }
  2766. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2767. echo "$result" | tee "$cache_file" || return 1
  2768. }
  2769. export -f get_master_service_for_service
  2770. get_top_master_service_for_service() {
  2771. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2772. current_service
  2773. if [ -e "$cache_file" ]; then
  2774. # debug "$FUNCNAME: cache hit ($*)"
  2775. cat "$cache_file"
  2776. return 0
  2777. fi
  2778. current_service="$service"
  2779. while true; do
  2780. master_service=$(get_master_service_for_service "$current_service") || return 1
  2781. [ "$master_service" == "$current_service" ] && break
  2782. current_service="$master_service"
  2783. done
  2784. echo "$current_service" | tee "$cache_file"
  2785. return 0
  2786. }
  2787. export -f get_top_master_service_for_service
  2788. ##
  2789. ## The result is a mixin that is not always a complete valid
  2790. ## docker-compose entry (thinking of subordinates). The result
  2791. ## will be merge with master charms.
  2792. _get_docker_compose_mixin_from_metadata_cached() {
  2793. local service="$1" charm="$2" metadata="$3" \
  2794. has_build_dir="$4" \
  2795. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2796. metadata_file metadata volumes docker_compose subordinate image \
  2797. mixin mixins tmemory memory limit docker_memory
  2798. if [ -e "$cache_file" ]; then
  2799. #debug "$FUNCNAME: STATIC cache hit $1"
  2800. cat "$cache_file" &&
  2801. touch "$cache_file" || return 1
  2802. return 0
  2803. fi
  2804. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2805. if [ "$metadata" ]; then
  2806. ## resources to volumes
  2807. volumes=$(
  2808. for resource_type in data config; do
  2809. while read-0 resource; do
  2810. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2811. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2812. done
  2813. while read-0 resource; do
  2814. if [[ "$resource" == /*:/*:* ]]; then
  2815. echo " - $resource"
  2816. elif [[ "$resource" == /*:/* ]]; then
  2817. echo " - $resource:rw"
  2818. elif [[ "$resource" == /*:* ]]; then
  2819. echo " - ${resource%%:*}:$resource"
  2820. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2821. echo " - $resource:$resource:rw"
  2822. else
  2823. die "Invalid host-resource specified in 'metadata.yml'."
  2824. fi
  2825. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2826. while read-0 resource; do
  2827. dest="$(charm.get_dir "$charm")/resources$resource"
  2828. if ! [ -e "$dest" ]; then
  2829. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2830. fi
  2831. echo " - $dest:$resource:ro"
  2832. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2833. ) || return 1
  2834. if [ "$volumes" ]; then
  2835. mixins+=("volumes:"$'\n'"$volumes")
  2836. fi
  2837. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2838. if [ "$type" != "run-once" ]; then
  2839. mixins+=("restart: unless-stopped")
  2840. fi
  2841. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2842. if [ "$docker_compose" ]; then
  2843. mixins+=("$docker_compose")
  2844. fi
  2845. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  2846. subordinate=true
  2847. fi
  2848. fi
  2849. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2850. [ "$image" == "None" ] && image=""
  2851. if [ -n "$image" ]; then
  2852. if [ -n "$subordinate" ]; then
  2853. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2854. return 1
  2855. fi
  2856. mixins+=("image: $image")
  2857. elif [ "$has_build_dir" ]; then
  2858. if [ "$subordinate" ]; then
  2859. err "Subordinate charm can not have a 'build' sub directory."
  2860. return 1
  2861. fi
  2862. mixins+=("build: $(charm.get_dir "$charm")/build")
  2863. fi
  2864. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  2865. [ "$limit" == "null" ] && limit=""
  2866. if [ -n "$limit" ]; then
  2867. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  2868. [ "$E" != 0 ]; then
  2869. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  2870. return 1
  2871. fi
  2872. case "$tmemory" in
  2873. '!!str'|'!!int')
  2874. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  2875. err "Invalid format specified for .limit.memory: '$memory'."
  2876. return 1
  2877. }
  2878. ;;
  2879. '!!float')
  2880. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  2881. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  2882. return 1
  2883. ;;
  2884. '!!null')
  2885. :
  2886. ;;
  2887. *)
  2888. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  2889. "for ${WHITE}.limit.memory${NORMAL}."
  2890. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  2891. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  2892. echo " Example values: '1.5G', '252M', ..." >&2
  2893. return 1
  2894. ;;
  2895. esac
  2896. if [ -n "$docker_memory" ]; then
  2897. if [[ "$docker_memory" -lt 6291456 ]]; then
  2898. err "Can't limit service to lower than 6M."
  2899. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  2900. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  2901. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  2902. return 1
  2903. fi
  2904. mixins+=(
  2905. "mem_limit: $docker_memory"
  2906. "memswap_limit: $docker_memory"
  2907. )
  2908. fi
  2909. fi
  2910. ## Final merging
  2911. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2912. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2913. return 1
  2914. }
  2915. echo "$mixin" | tee "$cache_file"
  2916. }
  2917. export -f _get_docker_compose_mixin_from_metadata_cached
  2918. get_docker_compose_mixin_from_metadata() {
  2919. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2920. if [ -e "$cache_file" ]; then
  2921. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2922. cat "$cache_file"
  2923. return 0
  2924. fi
  2925. charm=$(get_service_charm "$service") || return 1
  2926. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2927. has_build_dir=
  2928. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2929. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2930. echo "$mixin" | tee "$cache_file"
  2931. }
  2932. export -f get_docker_compose_mixin_from_metadata
  2933. _save() {
  2934. local name="$1"
  2935. cat - | tee -a "$docker_compose_dir/.data/$name"
  2936. }
  2937. export -f _save
  2938. get_default_project_name() {
  2939. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  2940. echo "$DEFAULT_PROJECT_NAME"
  2941. return 0
  2942. fi
  2943. local normalized_path compose_yml_location name
  2944. compose_yml_location="$(get_compose_yml_location)" || return 1
  2945. if [ -n "$compose_yml_location" ]; then
  2946. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2947. name="${normalized_path%/*}" ## dirname
  2948. name="${name##*/}" ## basename
  2949. name="${name%%-deploy}" ## remove any '-deploy'
  2950. name="${name,,}" ## lowercase
  2951. e "$name"
  2952. return 0
  2953. fi
  2954. fi
  2955. echo "orphan"
  2956. return 0
  2957. }
  2958. export -f get_default_project_name
  2959. get_running_compose_containers() {
  2960. ## XXXvlab: docker bug: there will be a final newline anyway
  2961. docker ps --filter label="compose.service" --format='{{.ID}}'
  2962. }
  2963. export -f get_running_compose_containers
  2964. get_healthy_container_ip_for_service () {
  2965. local service="$1" port="$2" timeout=${3:-60}
  2966. local containers container container_network container_ip
  2967. containers="$(get_running_containers_for_service "$service")"
  2968. if [ -z "$containers" ]; then
  2969. err "No containers running for service $DARKYELLOW$service$NORMAL."
  2970. return 1
  2971. fi
  2972. ## XXXvlab: taking first container is probably not a good idea
  2973. container="$(echo "$containers" | head -n 1)"
  2974. ## XXXvlab: taking first ip is probably not a good idea
  2975. read-0 container_network container_ip < <(get_container_network_ip "$container")
  2976. if [ -z "$container_ip" ]; then
  2977. err "Can't get container's IP. You should check health of" \
  2978. "${DARKYELLOW}$service${NORMAL}'s container."
  2979. return 1
  2980. fi
  2981. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  2982. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  2983. echo " Please check that container is healthy. Here are last logs:" >&2
  2984. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  2985. return 1
  2986. }
  2987. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  2988. echo "$container_network:$container_ip"
  2989. }
  2990. export -f get_healthy_container_ip_for_service
  2991. switch_to_relation_service() {
  2992. local relation="$1"
  2993. ## XXXvlab: can't get real config here
  2994. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  2995. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  2996. return 1
  2997. fi
  2998. export SERVICE_NAME="$ts"
  2999. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3000. DOCKER_BASE_IMAGE=$(service_base_docker_image "$SERVICE_NAME")
  3001. export DOCKER_BASE_IMAGE
  3002. target_charm=$(get_service_charm "$ts") || return 1
  3003. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3004. cd "$target_charm_path"
  3005. }
  3006. export -f switch_to_relation_service
  3007. get_volumes_for_container() {
  3008. local container="$1"
  3009. docker inspect \
  3010. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3011. "$container"
  3012. }
  3013. export -f get_volumes_for_container
  3014. is_volume_used() {
  3015. local volume="$1" container_id src dst
  3016. while read -r container_id; do
  3017. while read-0 src dst; do
  3018. [[ "$src/" == "$volume"/* ]] && return 0
  3019. done < <(get_volumes_for_container "$container_id")
  3020. done < <(get_running_compose_containers)
  3021. return 1
  3022. }
  3023. export -f is_volume_used
  3024. clean_unused_docker_compose() {
  3025. for f in /var/lib/compose/docker-compose/*; do
  3026. [ -e "$f" ] || continue
  3027. is_volume_used "$f" && continue
  3028. debug "Cleaning unused docker-compose ${f##*/}"
  3029. rm -rf "$f" || return 1
  3030. done
  3031. return 0
  3032. }
  3033. export -f clean_unused_docker_compose
  3034. stdin_get_hash() {
  3035. local sha
  3036. sha=$(sha256sum) || return 1
  3037. sha=${sha:0:64}
  3038. echo "$sha"
  3039. }
  3040. export -f stdin_get_hash
  3041. file_get_hash() {
  3042. stdin_get_hash < "$1" || return 1
  3043. }
  3044. export -f file_get_hash
  3045. docker_compose_store() {
  3046. local file="$1" sha
  3047. sha=$(file_get_hash "$file") || return 1
  3048. project=$(get_default_project_name) || return 1
  3049. dst="/var/lib/compose/docker-compose/$sha/$project"
  3050. mkdir -p "$dst" || return 1
  3051. cat <<EOF > "$dst/.env" || return 1
  3052. DOCKER_COMPOSE_PATH=$dst
  3053. COMPOSE_HTTP_TIMEOUT=7200
  3054. EOF
  3055. cp "$file" "$dst/docker-compose.yml" || return 1
  3056. mkdir -p "$dst/bin" || return 1
  3057. cat <<EOF > "$dst/bin/dc" || return 1
  3058. #!/bin/bash
  3059. $(declare -f read-0)
  3060. docker_run_opts=()
  3061. while read-0 opt; do
  3062. if [[ "\$opt" == "!env:"* ]]; then
  3063. opt="\${opt##!env:}"
  3064. var="\${opt%%=*}"
  3065. value="\${opt#*=}"
  3066. export "\$var"="\$value"
  3067. else
  3068. docker_run_opts+=("\$opt")
  3069. fi
  3070. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3071. docker_run_opts+=(
  3072. "-w" "$dst"
  3073. "--entrypoint" "/usr/local/bin/docker-compose"
  3074. )
  3075. [ -t 1 ] && {
  3076. docker_run_opts+=("-ti")
  3077. }
  3078. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3079. EOF
  3080. chmod +x "$dst/bin/dc" || return 1
  3081. printf "%s" "$sha"
  3082. }
  3083. export -f docker_compose_store
  3084. launch_docker_compose() {
  3085. local charm docker_compose_tmpdir docker_compose_dir
  3086. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3087. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3088. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3089. ## docker-compose will name network from the parent dir name
  3090. project=$(get_default_project_name)
  3091. mkdir -p "$docker_compose_tmpdir/$project"
  3092. docker_compose_dir="$docker_compose_tmpdir/$project"
  3093. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  3094. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3095. # debug "Merging some config data in docker-compose.yml:"
  3096. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3097. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3098. fi
  3099. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3100. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3101. fi
  3102. ## XXXvlab: could be more specific and only link the needed charms
  3103. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3104. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3105. # if charm.exists "$charm"; then
  3106. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3107. # fi
  3108. # done
  3109. mkdir "$docker_compose_dir/.data"
  3110. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3111. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3112. fi
  3113. {
  3114. {
  3115. {
  3116. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3117. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3118. else
  3119. cd "$docker_compose_dir" || return 1
  3120. fi
  3121. if [ -f ".env" ]; then
  3122. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3123. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3124. fi
  3125. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3126. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3127. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3128. if [ "$DRY_COMPOSE_RUN" ]; then
  3129. echo docker-compose "$@"
  3130. else
  3131. docker-compose "$@"
  3132. fi
  3133. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3134. } | _save stdout
  3135. } 3>&1 1>&2 2>&3 | _save stderr
  3136. } 3>&1 1>&2 2>&3
  3137. 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
  3138. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3139. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3140. fi
  3141. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3142. if [ -z "$docker_compose_errlvl" ]; then
  3143. err "Something went wrong before you could gather docker-compose errorlevel."
  3144. return 1
  3145. fi
  3146. return "$docker_compose_errlvl"
  3147. }
  3148. export -f launch_docker_compose
  3149. get_compose_yml_location() {
  3150. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3151. echo "$COMPOSE_YML_FILE"
  3152. return 0
  3153. fi
  3154. parent=$(while ! [ -f "./compose.yml" ]; do
  3155. [ "$PWD" == "/" ] && exit 0
  3156. cd ..
  3157. done; echo "$PWD"
  3158. )
  3159. if [ "$parent" ]; then
  3160. echo "$parent/compose.yml"
  3161. return 0
  3162. fi
  3163. ## XXXvlab: do we need this additional environment variable,
  3164. ## COMPOSE_YML_FILE is not sufficient ?
  3165. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3166. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3167. warn "No 'compose.yml' was found in current or parent dirs," \
  3168. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3169. "(${DEFAULT_COMPOSE_FILE})"
  3170. return 0
  3171. fi
  3172. echo "$DEFAULT_COMPOSE_FILE"
  3173. return 0
  3174. fi
  3175. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3176. return 0
  3177. }
  3178. export -f get_compose_yml_location
  3179. get_compose_yml_content() {
  3180. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3181. if [ -e "$cache_file" ]; then
  3182. cat "$cache_file" &&
  3183. touch "$cache_file" || return 1
  3184. return 0
  3185. fi
  3186. if [ -z "$COMPOSE_YML_FILE" ]; then
  3187. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3188. fi
  3189. if [ -e "$COMPOSE_YML_FILE" ]; then
  3190. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3191. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3192. err "Could not read '$COMPOSE_YML_FILE'."
  3193. return 1
  3194. }
  3195. else
  3196. debug "No compose file found. Using an empty one."
  3197. COMPOSE_YML_CONTENT=""
  3198. fi
  3199. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3200. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3201. if [ "$?" != 0 ]; then
  3202. outputed_something=
  3203. while IFS='' read -r line1 && IFS='' read -r line2; do
  3204. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3205. outputed_something=true
  3206. echo "$line1 $GRAY($line2)$NORMAL"
  3207. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3208. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3209. prefix " $GRAY|$NORMAL "
  3210. [ "$outputed_something" ] || {
  3211. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3212. echo "$output" | prefix " $GRAY|$NORMAL "
  3213. }
  3214. return 1
  3215. fi
  3216. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3217. }
  3218. export -f get_compose_yml_content
  3219. get_default_target_services() {
  3220. local services=("$@")
  3221. if [ -z "${services[*]}" ]; then
  3222. if [ "$DEFAULT_SERVICES" ]; then
  3223. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3224. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3225. services="$DEFAULT_SERVICES"
  3226. else
  3227. err "No service provided."
  3228. return 1
  3229. fi
  3230. fi
  3231. echo "${services[*]}"
  3232. }
  3233. export -f get_default_target_services
  3234. get_master_services() {
  3235. local loaded master_service service
  3236. declare -A loaded
  3237. for service in "$@"; do
  3238. master_service=$(get_top_master_service_for_service "$service") || return 1
  3239. if [ "${loaded[$master_service]}" ]; then
  3240. continue
  3241. fi
  3242. echo "$master_service"
  3243. loaded["$master_service"]=1
  3244. done | nspc
  3245. return "${PIPESTATUS[0]}"
  3246. }
  3247. export -f get_master_services
  3248. get_current_docker_container_id() {
  3249. local line
  3250. line=$(cat "/proc/self/cpuset") || return 1
  3251. [[ "$line" == *docker* ]] || return 1
  3252. echo "${line##*/}"
  3253. }
  3254. export -f get_current_docker_container_id
  3255. ## if we are in a docker compose, we might want to know what is the
  3256. ## real host path of some local paths.
  3257. get_host_path() {
  3258. local path="$1"
  3259. path=$(realpath "$path") || return 1
  3260. container_id=$(get_current_docker_container_id) || {
  3261. print "%s" "$path"
  3262. return 0
  3263. }
  3264. biggest_dst=
  3265. current_src=
  3266. while read-0 src dst; do
  3267. [[ "$path" == "$dst"* ]] || continue
  3268. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3269. biggest_dst="$dst"
  3270. current_src="$src"
  3271. fi
  3272. done < <(get_volumes_for_container "$container_id")
  3273. if [ "$current_src" ]; then
  3274. printf "%s" "$current_src"
  3275. else
  3276. return 1
  3277. fi
  3278. }
  3279. export -f get_host_path
  3280. _setup_state_dir() {
  3281. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3282. #debug "Creating temporary state directory in '$state_tmpdir'."
  3283. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3284. # rm -rf \"$state_tmpdir\""
  3285. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3286. }
  3287. get_docker_compose_help_msg() {
  3288. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3289. docker_compose_help_msg
  3290. if [ -e "$cache_file" ]; then
  3291. cat "$cache_file" &&
  3292. touch "$cache_file" || return 1
  3293. return 0
  3294. fi
  3295. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3296. echo "$docker_compose_help_msg" |
  3297. tee "$cache_file" || return 1
  3298. }
  3299. get_docker_compose_usage() {
  3300. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3301. docker_compose_help_msg
  3302. if [ -e "$cache_file" ]; then
  3303. cat "$cache_file" &&
  3304. touch "$cache_file" || return 1
  3305. return 0
  3306. fi
  3307. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3308. echo "$docker_compose_help_msg" |
  3309. grep -m 1 "^Usage:" -A 10000 |
  3310. egrep -m 1 "^\$" -B 10000 |
  3311. nspc |
  3312. sed -r 's/^Usage: //g' |
  3313. tee "$cache_file" || return 1
  3314. }
  3315. get_docker_compose_opts_help() {
  3316. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3317. docker_compose_help_msg
  3318. if [ -e "$cache_file" ]; then
  3319. cat "$cache_file" &&
  3320. touch "$cache_file" || return 1
  3321. return 0
  3322. fi
  3323. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3324. echo "$docker_compose_opts_help" |
  3325. grep '^Options:' -A 20000 |
  3326. tail -n +2 |
  3327. { cat ; echo; } |
  3328. egrep -m 1 "^\S*\$" -B 10000 |
  3329. head -n -1 |
  3330. tee "$cache_file" || return 1
  3331. }
  3332. get_docker_compose_commands_help() {
  3333. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3334. docker_compose_help_msg
  3335. if [ -e "$cache_file" ]; then
  3336. cat "$cache_file" &&
  3337. touch "$cache_file" || return 1
  3338. return 0
  3339. fi
  3340. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3341. echo "$docker_compose_opts_help" |
  3342. grep '^Commands:' -A 20000 |
  3343. tail -n +2 |
  3344. { cat ; echo; } |
  3345. egrep -m 1 "^\S*\$" -B 10000 |
  3346. head -n -1 |
  3347. tee "$cache_file" || return 1
  3348. }
  3349. get_docker_compose_opts_list() {
  3350. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3351. docker_compose_help_msg
  3352. if [ -e "$cache_file" ]; then
  3353. cat "$cache_file" &&
  3354. touch "$cache_file" || return 1
  3355. return 0
  3356. fi
  3357. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3358. echo "$docker_compose_opts_help" |
  3359. egrep "^\s+-" |
  3360. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3361. tee "$cache_file" || return 1
  3362. }
  3363. options_parser() {
  3364. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3365. printf "\0"
  3366. }
  3367. remove_options_in_option_help_msg() {
  3368. {
  3369. read-0 null
  3370. if [ "$null" ]; then
  3371. err "options parsing error, should start with an option line."
  3372. return 1
  3373. fi
  3374. while read-0 opt full_txt;do
  3375. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3376. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3377. for to_remove in "$@"; do
  3378. str_matches "$to_remove" $multi_opts $single_opts && {
  3379. continue 2
  3380. }
  3381. done
  3382. echo -n "$full_txt"
  3383. done
  3384. } < <(options_parser)
  3385. }
  3386. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3387. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3388. multi_opts_filter() {
  3389. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3390. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3391. tr ',' "\n" | nspc
  3392. }
  3393. single_opts_filter() {
  3394. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3395. tr ',' "\n" | nspc
  3396. }
  3397. get_docker_compose_multi_opts_list() {
  3398. local action="$1" opts_list
  3399. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3400. echo "$opts_list" | multi_opts_filter
  3401. }
  3402. get_docker_compose_single_opts_list() {
  3403. local action="$1" opts_list
  3404. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3405. echo "$opts_list" | single_opts_filter
  3406. }
  3407. display_commands_help() {
  3408. local charm_actions
  3409. echo
  3410. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3411. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3412. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3413. if [ "$charm_actions_help" ]; then
  3414. echo
  3415. echo "${WHITE}Charm actions${NORMAL}:"
  3416. printf "%s\n" "$charm_actions_help" | \
  3417. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3418. fi
  3419. }
  3420. get_docker_charm_action() {
  3421. local services service charm relation_name target_service relation_config \
  3422. target_charm
  3423. services=($(get_compose_yml_content | yq -r 'keys().[]' 2>/dev/null)) || return 1
  3424. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3425. services=($(get_all_services)) || return 1
  3426. for service in "${services[@]}"; do
  3427. printf "%s:\n" "$service"
  3428. charm=$(get_service_charm "$service") || return 1
  3429. for action in $(charm.ls_direct_actions "$charm"); do
  3430. printf " %s:\n" "$action"
  3431. printf " type: %s\n" "direct"
  3432. done
  3433. while read-0 relation_name target_service _relation_config _tech_dep; do
  3434. target_charm=$(get_service_charm "$target_service") || return 1
  3435. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3436. printf " %s:\n" "$action"
  3437. printf " type: %s\n" "indirect"
  3438. printf " inherited: %s\n" "$target_charm"
  3439. done
  3440. done < <(get_service_relations "$service")
  3441. done
  3442. }
  3443. export -f get_docker_charm_action
  3444. get_docker_charm_action_help() {
  3445. local services service charm relation_name target_service relation_config \
  3446. target_charm
  3447. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3448. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3449. for service in "${services[@]}"; do
  3450. out=$(
  3451. charm=$(get_service_charm "$service") || return 1
  3452. for action in $(charm.ls_direct_actions "$charm"); do
  3453. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3454. done
  3455. while read-0 relation_name target_service _relation_config _tech_dep; do
  3456. target_charm=$(get_service_charm "$target_service") || return 1
  3457. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3458. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3459. done
  3460. done < <(get_service_relations "$service")
  3461. )
  3462. if [ "$out" ]; then
  3463. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3464. printf "%s\n" "$out"
  3465. fi
  3466. done
  3467. }
  3468. display_help() {
  3469. print_help
  3470. echo "${WHITE}Usage${NORMAL}:"
  3471. echo " $usage"
  3472. echo "${WHITE}Options${NORMAL}:"
  3473. echo " -h, --help Print this message and quit"
  3474. echo " (ignoring any other options)"
  3475. echo " -V, --version Print current version and quit"
  3476. echo " (ignoring any other options)"
  3477. echo " --dirs Display data dirs and quit"
  3478. echo " (ignoring any other options)"
  3479. echo " --get-project-name Display project name and quit"
  3480. echo " (ignoring any other options)"
  3481. echo " --get-available-actions Display all available actions and quit"
  3482. echo " (ignoring any other options)"
  3483. echo " -v, --verbose Be more verbose"
  3484. echo " -q, --quiet Be quiet"
  3485. echo " -d, --debug Print full debugging information (sets also verbose)"
  3486. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3487. echo " command line will be used."
  3488. echo " --no-relations Do not run any relation script"
  3489. echo " --no-hooks Do not run any hook script"
  3490. echo " --no-init Do not run any init script"
  3491. echo " --no-post-deploy Do not run any post-deploy script"
  3492. echo " --no-pre-deploy Do not run any pre-deploy script"
  3493. echo " --without-relation RELATION "
  3494. echo " Do not run given relation"
  3495. echo " -R, --rebuild-relations-to-service SERVICE"
  3496. echo " Will rebuild all relations to given service"
  3497. echo " --add-compose-content, -Y YAML"
  3498. echo " Will merge some direct YAML with the current compose"
  3499. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  3500. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3501. filter_docker_compose_help_message
  3502. display_commands_help
  3503. }
  3504. _graph_service() {
  3505. local service="$1" base="$1"
  3506. charm=$(get_service_charm "$service") || return 1
  3507. metadata=$(charm.metadata "$charm") || return 1
  3508. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3509. if [[ "$subordinate" =~ ^True|true$ ]]; then
  3510. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3511. master_charm=
  3512. while read-0 relation_name relation; do
  3513. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3514. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3515. if [ -z "$interface" ]; then
  3516. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3517. return 1
  3518. fi
  3519. ## Action provided by relation ?
  3520. target_service=
  3521. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3522. [ "$interface" == "$relation_name" ] && {
  3523. target_service="$candidate_target_service"
  3524. break
  3525. }
  3526. done < <(get_service_relations "$service")
  3527. if [ -z "$target_service" ]; then
  3528. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3529. "${DARKYELLOW}$service$NORMAL compose definition."
  3530. return 1
  3531. fi
  3532. master_service="$target_service"
  3533. master_charm=$(get_service_charm "$target_service") || return 1
  3534. break
  3535. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3536. fi
  3537. _graph_node_service "$service" "$base" "$charm"
  3538. _graph_edge_service "$service" "$subordinate" "$master_service"
  3539. }
  3540. _graph_node_service() {
  3541. local service="$1" base="$2" charm="$3"
  3542. cat <<EOF
  3543. "$(_graph_node_service_label ${service})" [
  3544. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  3545. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  3546. color = $([ "$base" ] && echo "blue" || echo "black")
  3547. fillcolor = "white"
  3548. fontname = "Courier New"
  3549. shape = "Mrecord"
  3550. label =<$(_graph_node_service_content "$service")>
  3551. ];
  3552. EOF
  3553. }
  3554. _graph_edge_service() {
  3555. local service="$1" subordinate="$2" master_service="$3"
  3556. while read-0 relation_name target_service relation_config tech_dep; do
  3557. cat <<EOF
  3558. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3559. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3560. fontsize = 16
  3561. fontcolor = "black"
  3562. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3563. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3564. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3565. arrowtail = odot
  3566. # arrowhead = dotlicurve
  3567. taillabel = "$relation_name" ];
  3568. EOF
  3569. done < <(get_service_relations "$service") || return 1
  3570. }
  3571. _graph_node_service_label() {
  3572. local service="$1"
  3573. echo "service_$service"
  3574. }
  3575. _graph_node_service_content() {
  3576. local service="$1"
  3577. charm=$(get_service_charm "$service") || return 1
  3578. cat <<EOF
  3579. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3580. <tr>
  3581. <td bgcolor="black" align="center" colspan="2">
  3582. <font color="white">$service</font>
  3583. </td>
  3584. </tr>
  3585. $(if [ "$charm" != "$service" ]; then
  3586. cat <<EOF2
  3587. <tr>
  3588. <td align="left" port="r0">charm: $charm</td>
  3589. </tr>
  3590. EOF2
  3591. fi)
  3592. </table>
  3593. EOF
  3594. }
  3595. cla_contains () {
  3596. local e
  3597. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3598. return 1
  3599. }
  3600. filter_docker_compose_help_message() {
  3601. cat - |
  3602. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3603. s/docker-compose.yml/compose.yml/g;
  3604. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3605. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3606. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3607. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3608. }
  3609. graph() {
  3610. local services=("$@")
  3611. declare -A entries
  3612. cat <<EOF
  3613. digraph g {
  3614. graph [
  3615. fontsize=30
  3616. labelloc="t"
  3617. label=""
  3618. splines=true
  3619. overlap=false
  3620. #rankdir = "LR"
  3621. ];
  3622. ratio = auto;
  3623. EOF
  3624. for target_service in "$@"; do
  3625. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3626. for service in $services; do
  3627. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3628. if cla_contains "$service" "${services[@]}"; then
  3629. base=true
  3630. else
  3631. base=
  3632. fi
  3633. _graph_service "$service" "$base"
  3634. done
  3635. done
  3636. echo "}"
  3637. }
  3638. cached_wget() {
  3639. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  3640. url="$1"
  3641. if [ -e "$cache_file" ]; then
  3642. cat "$cache_file"
  3643. touch "$cache_file"
  3644. return 0
  3645. fi
  3646. wget -O- "${url}" |
  3647. tee "$cache_file"
  3648. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3649. rm "$cache_file"
  3650. die "Unable to fetch '$url'."
  3651. return 1
  3652. fi
  3653. }
  3654. export -f cached_wget
  3655. [ "$SOURCED" ] && return 0
  3656. trap_add "EXIT" clean_cache
  3657. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3658. if [ -r /etc/default/charm ]; then
  3659. . /etc/default/charm
  3660. fi
  3661. if [ -r "/etc/default/$exname" ]; then
  3662. . "/etc/default/$exname"
  3663. fi
  3664. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3665. ## userdir ? and global /etc/compose.yml ?
  3666. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3667. /etc/default/compose /etc/compose/local.conf; do
  3668. [ -e "$cfgfile" ] || continue
  3669. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3670. done
  3671. fi
  3672. _setup_state_dir
  3673. mkdir -p "$CACHEDIR" || exit 1
  3674. log () { cat; }
  3675. export -f log
  3676. ##
  3677. ## Argument parsing
  3678. ##
  3679. wrap_opts=()
  3680. services=()
  3681. remainder_args=()
  3682. compose_opts=()
  3683. compose_contents=()
  3684. action_opts=()
  3685. services_args=()
  3686. pos_arg_ct=0
  3687. no_hooks=
  3688. no_init=
  3689. action=
  3690. stage="main" ## switches from 'main', to 'action', 'remainder'
  3691. is_docker_compose_action=
  3692. rebuild_relations_to_service=()
  3693. color=
  3694. declare -A without_relations
  3695. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3696. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  3697. while read-0 arg; do
  3698. case "$stage" in
  3699. "main")
  3700. case "$arg" in
  3701. --help|-h)
  3702. no_init=true ; no_hooks=true ; no_relations=true
  3703. display_help
  3704. exit 0
  3705. ;;
  3706. --verbose|-v)
  3707. export VERBOSE=true
  3708. compose_opts+=("--verbose")
  3709. ;;
  3710. --quiet|-q)
  3711. export QUIET=true
  3712. export wrap_opts+=("-q")
  3713. log () { cat >&2; }
  3714. export -f log
  3715. ;;
  3716. --version|-V)
  3717. print_version
  3718. docker-compose --version
  3719. docker --version
  3720. exit 0
  3721. ;;
  3722. -f|--file)
  3723. read-0 value
  3724. [ -e "$value" ] || die "File $value doesn't exists"
  3725. export COMPOSE_YML_FILE="$value"
  3726. shift
  3727. ;;
  3728. -p|--project-name)
  3729. read-0 value
  3730. export DEFAULT_PROJECT_NAME="$value"
  3731. compose_opts+=("--project-name $value")
  3732. shift
  3733. ;;
  3734. --color|-c)
  3735. if [ "$color" == "0" ]; then
  3736. err "Conflicting option --color with previous --no-ansi."
  3737. exit 1
  3738. fi
  3739. color=1
  3740. ansi_color yes
  3741. ;;
  3742. --no-ansi)
  3743. if [ "$color" == "1" ]; then
  3744. err "Conflicting option --no-ansi with previous --color."
  3745. exit 1
  3746. fi
  3747. color=0
  3748. ansi_color no
  3749. compose_opts+=("--no-ansi")
  3750. ;;
  3751. --no-relations)
  3752. export no_relations=true
  3753. ;;
  3754. --without-relation)
  3755. read-0 value
  3756. without_relations["$value"]=1
  3757. shift
  3758. ;;
  3759. --no-hooks)
  3760. export no_hooks=true
  3761. ;;
  3762. --no-init)
  3763. export no_init=true
  3764. ;;
  3765. --no-post-deploy)
  3766. export no_post_deploy=true
  3767. ;;
  3768. --no-pre-deploy)
  3769. export no_pre_deploy=true
  3770. ;;
  3771. --rebuild-relations-to-service|-R)
  3772. read-0 value
  3773. rebuild_relations_to_service+=("$value")
  3774. shift
  3775. ;;
  3776. --debug|-d)
  3777. export DEBUG=true
  3778. export VERBOSE=true
  3779. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3780. ;;
  3781. --add-compose-content|-Y)
  3782. read-0 value
  3783. compose_contents+=("$value")
  3784. shift
  3785. ;;
  3786. --dirs)
  3787. echo "CACHEDIR: $CACHEDIR"
  3788. echo "VARDIR: $VARDIR"
  3789. exit 0
  3790. ;;
  3791. --get-project-name)
  3792. project=$(get_default_project_name) || exit 1
  3793. echo "$project"
  3794. exit 0
  3795. ;;
  3796. --get-available-actions)
  3797. get_docker_charm_action
  3798. exit $?
  3799. ;;
  3800. --dry-compose-run)
  3801. export DRY_COMPOSE_RUN=true
  3802. ;;
  3803. --*|-*)
  3804. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3805. read-0 value
  3806. compose_opts+=("$arg" "$value")
  3807. shift;
  3808. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3809. compose_opts+=("$arg")
  3810. else
  3811. err "Unknown option '$arg'. Please check help:"
  3812. display_help >&2
  3813. exit 1
  3814. fi
  3815. ;;
  3816. *)
  3817. action="$arg"
  3818. stage="action"
  3819. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3820. is_docker_compose_action=true
  3821. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3822. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3823. if [ "$DC_MATCH_MULTI" ]; then
  3824. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3825. fi
  3826. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3827. pos_args=("${pos_args[@]:1}")
  3828. # echo "USAGE: $DC_USAGE"
  3829. # echo "pos_args: ${pos_args[@]}"
  3830. # echo "MULTI: $DC_MATCH_MULTI"
  3831. # echo "SINGLE: $DC_MATCH_SINGLE"
  3832. # exit 1
  3833. else
  3834. stage="remainder"
  3835. fi
  3836. ;;
  3837. esac
  3838. ;;
  3839. "action") ## Only for docker-compose actions
  3840. case "$arg" in
  3841. --help|-h)
  3842. no_init=true ; no_hooks=true ; no_relations=true
  3843. action_opts+=("$arg")
  3844. ;;
  3845. --*|-*)
  3846. if [ "$is_docker_compose_action" ]; then
  3847. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3848. read-0 value
  3849. action_opts+=("$arg" "$value")
  3850. shift
  3851. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3852. action_opts+=("$arg")
  3853. else
  3854. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3855. docker-compose "$action" --help |
  3856. filter_docker_compose_help_message >&2
  3857. exit 1
  3858. fi
  3859. fi
  3860. ;;
  3861. *)
  3862. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3863. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3864. services_args+=("$arg")
  3865. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3866. services_args=("$arg") || exit 1
  3867. stage="remainder"
  3868. else
  3869. action_posargs+=("$arg")
  3870. ((pos_arg_ct++))
  3871. fi
  3872. ;;
  3873. esac
  3874. ;;
  3875. "remainder")
  3876. remainder_args+=("$arg")
  3877. while read-0 arg; do
  3878. remainder_args+=("$arg")
  3879. done
  3880. break 3
  3881. ;;
  3882. esac
  3883. shift
  3884. done < <(cla.normalize "$@")
  3885. export compose_contents
  3886. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3887. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3888. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3889. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3890. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3891. aexport remainder_args
  3892. ##
  3893. ## Actual code
  3894. ##
  3895. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3896. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3897. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3898. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3899. ##
  3900. ## Get services in command line.
  3901. ##
  3902. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3903. action_service=${remainder_args[0]}
  3904. if [ -z "$action_service" ]; then
  3905. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3906. display_commands_help
  3907. exit 1
  3908. fi
  3909. ## Required by has_service_action
  3910. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3911. NO_CONSTRAINT_CHECK=1 get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3912. remainder_args=("${remainder_args[@]:1}")
  3913. if has_service_action "$action_service" "$action" >/dev/null; then
  3914. is_service_action=true
  3915. services_args=("$action_service")
  3916. {
  3917. read-0 action_type
  3918. case "$action_type" in
  3919. "relation")
  3920. read-0 _ target_service _target_charm relation_name _ action_script_path
  3921. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3922. services_args+=("$target_service")
  3923. ;;
  3924. "direct")
  3925. read-0 _ action_script_path
  3926. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3927. ;;
  3928. esac
  3929. } < <(has_service_action "$action_service" "$action")
  3930. get_all_relations "${services_args[@]}" >/dev/null || {
  3931. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  3932. exit 1
  3933. }
  3934. ## Divert logging to stdout to stderr
  3935. log () { cat >&2; }
  3936. export -f log
  3937. else
  3938. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3939. fi
  3940. else
  3941. case "$action" in
  3942. ps|up)
  3943. if [ "${#services_args[@]}" == 0 ]; then
  3944. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3945. fi
  3946. ;;
  3947. config)
  3948. services_args=("${action_posargs[@]}")
  3949. ;;
  3950. esac
  3951. fi
  3952. export COMPOSE_ACTION="$action"
  3953. NO_CONSTRAINT_CHECK=True
  3954. case "$action" in
  3955. up)
  3956. NO_CONSTRAINT_CHECK=
  3957. ;;
  3958. esac
  3959. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3960. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3961. services=($(get_master_services "${services_args[@]}")) || exit 1
  3962. if [ "$action" == "up" ]; then
  3963. declare -A seen
  3964. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3965. mservice=$(get_master_service_for_service "$service") || exit 1
  3966. [ "${seen[$mservice]}" ] && continue
  3967. type="$(get_service_type "$mservice")" || exit 1
  3968. ## remove run-once
  3969. [ "$type" == "run-once" ] && continue
  3970. [ "$type" == "stub" ] && continue
  3971. seen[$mservice]=1
  3972. action_posargs+=("$mservice")
  3973. done
  3974. else
  3975. action_posargs+=("${services[@]}")
  3976. fi
  3977. ## Get rid of subordinates
  3978. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  3979. fi
  3980. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3981. err "Fails to compile base 'docker-compose.yml'"
  3982. exit 1
  3983. }
  3984. ##
  3985. ## Pre-action
  3986. ##
  3987. full_init=
  3988. case "$action" in
  3989. up|run)
  3990. full_init=true
  3991. post_hook=true
  3992. ;;
  3993. ""|down|restart|logs|config|ps)
  3994. full_init=
  3995. ;;
  3996. *)
  3997. if [ "$is_service_action" ]; then
  3998. full_init=true
  3999. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4000. for keyword in "${keywords[@]}"; do
  4001. case "$keyword" in
  4002. no-hooks)
  4003. no_hooks=true
  4004. ;;
  4005. hooks)
  4006. full_init=true
  4007. ;;
  4008. esac
  4009. done
  4010. fi
  4011. ;;
  4012. esac
  4013. if [ -n "$full_init" ]; then
  4014. ## init in order
  4015. if [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4016. Section setup host resources
  4017. setup_host_resources "${services_args[@]}" || exit 1
  4018. Section initialisation
  4019. run_service_hook init "${services_args[@]}" || exit 1
  4020. fi
  4021. ## Get relations
  4022. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4023. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4024. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4025. rebuild_relations_to_service=($rebuild_relations_to_service)
  4026. project=$(get_default_project_name) || return 1
  4027. for service in "${rebuild_relations_to_service[@]}"; do
  4028. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  4029. [ -d "$dir" ] && {
  4030. debug rm -rf "$dir"
  4031. rm -rf "$dir"
  4032. }
  4033. done
  4034. done
  4035. fi
  4036. run_service_relations "${services_args[@]}" || exit 1
  4037. fi
  4038. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  4039. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  4040. fi
  4041. fi | log
  4042. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4043. exit 1
  4044. fi
  4045. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  4046. charm=$(get_service_charm "${services_args[0]}") || exit 1
  4047. metadata=$(charm.metadata "$charm") || exit 1
  4048. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  4049. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4050. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  4051. fi
  4052. fi
  4053. export SERVICE_PACK="${services_args[*]}"
  4054. ##
  4055. ## Docker-compose
  4056. ##
  4057. errlvl="0"
  4058. case "$action" in
  4059. up|start|stop|build|run)
  4060. ## force daemon mode for up
  4061. if [[ "$action" == "up" ]]; then
  4062. if ! array_member action_opts -d; then
  4063. action_opts+=("-d")
  4064. fi
  4065. if ! array_member action_opts --remove-orphans; then
  4066. action_opts+=("--remove-orphans")
  4067. fi
  4068. fi
  4069. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4070. ;;
  4071. logs)
  4072. if ! array_member action_opts --tail; then ## force daemon mode for up
  4073. action_opts+=("--tail" "10")
  4074. fi
  4075. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4076. ;;
  4077. "")
  4078. launch_docker_compose "${compose_opts[@]}"
  4079. ;;
  4080. graph)
  4081. graph $SERVICE_PACK
  4082. ;;
  4083. config)
  4084. ## removing the services
  4085. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  4086. ## forcing docker-compose config to output the config file to stdout and not stderr
  4087. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  4088. echo "$out"
  4089. exit 1
  4090. }
  4091. echo "$out"
  4092. warn "Runtime configuration modification (from relations) are not included here."
  4093. ;;
  4094. down)
  4095. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  4096. debug "Adding a default argument of '--remove-orphans'"
  4097. action_opts+=("--remove-orphans")
  4098. fi
  4099. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  4100. ;;
  4101. *)
  4102. if [ "$is_service_action" ]; then
  4103. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  4104. errlvl="$?"
  4105. errlvl "$errlvl"
  4106. else
  4107. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4108. fi
  4109. ;;
  4110. esac || exit 1
  4111. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  4112. run_service_hook post_deploy "${services_args[@]}" || exit 1
  4113. fi
  4114. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  4115. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4116. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  4117. fi
  4118. fi
  4119. clean_unused_docker_compose || exit 1
  4120. exit "$errlvl"