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.

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