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.

4798 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. new new_md5 relation_dir relation_data_file
  2618. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2619. relation_data_file="$relation_dir/data"
  2620. new=
  2621. if [ -e "$relation_data_file" ]; then
  2622. ## Has reference changed ?
  2623. new_md5=$(e "$relation_config" | md5_compat)
  2624. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2625. new=true
  2626. fi
  2627. else
  2628. new=true
  2629. fi
  2630. if [ -n "$new" ]; then
  2631. OLDUMASK=$(umask)
  2632. umask 0077
  2633. e "$relation_config" > "$relation_data_file"
  2634. umask "$OLDUMASK"
  2635. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2636. fi
  2637. echo "$relation_data_file"
  2638. }
  2639. export -f get_relation_data_file
  2640. has_service_action () {
  2641. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2642. charm target_charm relation_name target_service relation_config _tech_dep \
  2643. path
  2644. if [ -e "$cache_file" ]; then
  2645. # debug "$FUNCNAME: cache hit ($*)"
  2646. cat "$cache_file"
  2647. return 0
  2648. fi
  2649. charm=$(get_service_charm "$service") || return 1
  2650. ## Action directly provided ?
  2651. if path=$(charm.has_direct_action "$charm" "$action"); then
  2652. p0 "direct" "$charm" "$path" | tee "$cache_file"
  2653. return 0
  2654. fi
  2655. ## Action provided by relation ?
  2656. while read-0 relation_name target_service relation_config _tech_dep; do
  2657. target_charm=$(get_service_charm "$target_service") || return 1
  2658. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  2659. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  2660. return 0
  2661. fi
  2662. done < <(get_service_relations "$service")
  2663. return 1
  2664. # master=$(get_top_master_service_for_service "$service")
  2665. # [ "$master" == "$charm" ] && return 1
  2666. # has_service_action "$master" "$action"
  2667. }
  2668. export -f has_service_action
  2669. run_service_action () {
  2670. local service="$1" action="$2" errlvl
  2671. shift ; shift
  2672. exec 6<&0 ## saving stdin
  2673. {
  2674. if ! read-0 action_type; then
  2675. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2676. info " Add an executable script to 'actions/$action' to implement action."
  2677. return 1
  2678. fi
  2679. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2680. errlvl="$?"
  2681. } < <(has_service_action "$service" "$action")
  2682. exec 0<&6 6<&- ## restoring stdin
  2683. return "$errlvl"
  2684. }
  2685. export -f run_service_action
  2686. get_compose_relation_config() {
  2687. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2688. if [ -e "$cache_file" ]; then
  2689. # debug "$FUNCNAME: cache hit ($*)"
  2690. cat "$cache_file"
  2691. return 0
  2692. fi
  2693. compose_service_def=$(get_compose_service_def "$service") || return 1
  2694. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2695. }
  2696. export -f get_compose_relation_config
  2697. # ## Return key-values-0
  2698. # get_compose_relation_config_for_service() {
  2699. # local service=$1 relation_name=$2 relation_config
  2700. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2701. # if ! relation_config=$(
  2702. # echo "$compose_service_relations" |
  2703. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2704. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2705. # "relation config in compose configuration."
  2706. # return 1
  2707. # fi
  2708. # if [ -z "$relation_config" ]; then
  2709. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2710. # return 1
  2711. # fi
  2712. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2713. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2714. # return 1
  2715. # fi
  2716. # }
  2717. # export -f get_compose_relation_config_for_service
  2718. _get_container_relation() {
  2719. local metadata=$1 found relation_name relation_def
  2720. found=
  2721. while read-0 relation_name relation_def; do
  2722. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2723. found="$relation_name"
  2724. break
  2725. }
  2726. done < <(_get_charm_metadata_uses "$metadata")
  2727. if [ -z "$found" ]; then
  2728. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2729. "${WHITE}scope${NORMAL} set to 'container'."
  2730. return 1
  2731. fi
  2732. printf "%s" "$found"
  2733. }
  2734. _get_master_service_for_service_cached () {
  2735. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2736. charm requires master_charm target_charm target_service service_def found
  2737. if [ -e "$cache_file" ]; then
  2738. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2739. cat "$cache_file" &&
  2740. touch "$cache_file" || return 1
  2741. return 0
  2742. fi
  2743. if ! [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  2744. ## just return service name
  2745. echo "$service" | tee "$cache_file"
  2746. return 0
  2747. fi
  2748. ## Action provided by relation ?
  2749. container_relation=$(_get_container_relation "$metadata") || return 1
  2750. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2751. if [ -z "$target_service" ]; then
  2752. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2753. "${DARKYELLOW}$service$NORMAL compose definition."
  2754. err ${FUNCNAME[@]}
  2755. return 1
  2756. fi
  2757. echo "$target_service" | tee "$cache_file"
  2758. }
  2759. export -f _get_master_service_for_service_cached
  2760. get_master_service_for_service() {
  2761. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2762. charm metadata result
  2763. if [ -e "$cache_file" ]; then
  2764. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2765. cat "$cache_file" || return 1
  2766. return 0
  2767. fi
  2768. charm=$(get_service_charm "$service") || return 1
  2769. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2770. metadata=""
  2771. warn "No charm $DARKPINK$charm$NORMAL found."
  2772. }
  2773. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2774. echo "$result" | tee "$cache_file" || return 1
  2775. }
  2776. export -f get_master_service_for_service
  2777. get_top_master_service_for_service() {
  2778. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2779. current_service
  2780. if [ -e "$cache_file" ]; then
  2781. # debug "$FUNCNAME: cache hit ($*)"
  2782. cat "$cache_file"
  2783. return 0
  2784. fi
  2785. current_service="$service"
  2786. while true; do
  2787. master_service=$(get_master_service_for_service "$current_service") || return 1
  2788. [ "$master_service" == "$current_service" ] && break
  2789. current_service="$master_service"
  2790. done
  2791. echo "$current_service" | tee "$cache_file"
  2792. return 0
  2793. }
  2794. export -f get_top_master_service_for_service
  2795. ##
  2796. ## The result is a mixin that is not always a complete valid
  2797. ## docker-compose entry (thinking of subordinates). The result
  2798. ## will be merge with master charms.
  2799. _get_docker_compose_mixin_from_metadata_cached() {
  2800. local service="$1" charm="$2" metadata="$3" \
  2801. has_build_dir="$4" \
  2802. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2803. metadata_file metadata volumes docker_compose subordinate image \
  2804. mixin mixins tmemory memory limit docker_memory
  2805. if [ -e "$cache_file" ]; then
  2806. #debug "$FUNCNAME: STATIC cache hit $1"
  2807. cat "$cache_file" &&
  2808. touch "$cache_file" || return 1
  2809. return 0
  2810. fi
  2811. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2812. if [ "$metadata" ]; then
  2813. ## resources to volumes
  2814. volumes=$(
  2815. for resource_type in data config; do
  2816. while read-0 resource; do
  2817. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2818. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2819. done
  2820. while read-0 resource; do
  2821. if [[ "$resource" == /*:/*:* ]]; then
  2822. echo " - $resource"
  2823. elif [[ "$resource" == /*:/* ]]; then
  2824. echo " - $resource:rw"
  2825. elif [[ "$resource" == /*:* ]]; then
  2826. echo " - ${resource%%:*}:$resource"
  2827. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2828. echo " - $resource:$resource:rw"
  2829. else
  2830. die "Invalid host-resource specified in 'metadata.yml'."
  2831. fi
  2832. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2833. while read-0 resource; do
  2834. dest="$(charm.get_dir "$charm")/resources$resource"
  2835. if ! [ -e "$dest" ]; then
  2836. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2837. fi
  2838. echo " - $dest:$resource:ro"
  2839. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2840. ) || return 1
  2841. if [ "$volumes" ]; then
  2842. mixins+=("volumes:"$'\n'"$volumes")
  2843. fi
  2844. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2845. if [ "$type" != "run-once" ]; then
  2846. mixins+=("restart: unless-stopped")
  2847. fi
  2848. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2849. if [ "$docker_compose" ]; then
  2850. mixins+=("$docker_compose")
  2851. fi
  2852. if [[ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" =~ ^True|true$ ]]; then
  2853. subordinate=true
  2854. fi
  2855. fi
  2856. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2857. [ "$image" == "None" ] && image=""
  2858. if [ -n "$image" ]; then
  2859. if [ -n "$subordinate" ]; then
  2860. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2861. return 1
  2862. fi
  2863. mixins+=("image: $image")
  2864. elif [ "$has_build_dir" ]; then
  2865. if [ "$subordinate" ]; then
  2866. err "Subordinate charm can not have a 'build' sub directory."
  2867. return 1
  2868. fi
  2869. mixins+=("build: $(charm.get_dir "$charm")/build")
  2870. fi
  2871. limit=$(e "$metadata" | yq '.limit' 2>/dev/null) || return 1
  2872. [ "$limit" == "null" ] && limit=""
  2873. if [ -n "$limit" ]; then
  2874. if ! read-0-err E tmemory memory < <(e "$limit" | wyq ".memory | type, .memory") ||
  2875. [ "$E" != 0 ]; then
  2876. err "Unexpected error in ${DARKPINK}$charm${NORMAL}'s metadata when parsing ${WHITE}.limit${NORMAL}"
  2877. return 1
  2878. fi
  2879. case "$tmemory" in
  2880. '!!str'|'!!int')
  2881. docker_memory="$(e "$memory" | numfmt --from iec)" || {
  2882. err "Invalid format specified for .limit.memory: '$memory'."
  2883. return 1
  2884. }
  2885. ;;
  2886. '!!float')
  2887. err "Unexpected value in ${DARKPINK}$charm${NORMAL}'s metadata for ${WHITE}.limit.memory${NORMAL}."
  2888. echo " You need to specify a unit (like 'K', 'M', 'G' ...)." >&2
  2889. return 1
  2890. ;;
  2891. '!!null')
  2892. :
  2893. ;;
  2894. *)
  2895. err "Unexpected type '${tmemory#!!}' in ${DARKPINK}$charm${NORMAL}'s metadata" \
  2896. "for ${WHITE}.limit.memory${NORMAL}."
  2897. echo " You need to check ${DARKPINK}$charm${NORMAL}'s metadata " \
  2898. "for ${WHITE}.limit.memory${NORMAL} and provide a valid value" >&2
  2899. echo " Example values: '1.5G', '252M', ..." >&2
  2900. return 1
  2901. ;;
  2902. esac
  2903. if [ -n "$docker_memory" ]; then
  2904. if [[ "$docker_memory" -lt 6291456 ]]; then
  2905. err "Can't limit service to lower than 6M."
  2906. echo " Specified limit of $memory (=$docker_memory) is lower than docker's min limit of 6M (=6291456)." >&2
  2907. echo " The provided limit to memory is lower than minimum memory for a container." >&2
  2908. echo " Please remove memory limit in ${DARKPINK}$charm${NORMAL}'s metadata or raise it." >&2
  2909. return 1
  2910. fi
  2911. mixins+=(
  2912. "mem_limit: $docker_memory"
  2913. "memswap_limit: $docker_memory"
  2914. )
  2915. fi
  2916. fi
  2917. ## Final merging
  2918. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2919. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2920. return 1
  2921. }
  2922. echo "$mixin" | tee "$cache_file"
  2923. }
  2924. export -f _get_docker_compose_mixin_from_metadata_cached
  2925. get_docker_compose_mixin_from_metadata() {
  2926. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2927. if [ -e "$cache_file" ]; then
  2928. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2929. cat "$cache_file"
  2930. return 0
  2931. fi
  2932. charm=$(get_service_charm "$service") || return 1
  2933. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2934. has_build_dir=
  2935. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2936. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2937. echo "$mixin" | tee "$cache_file"
  2938. }
  2939. export -f get_docker_compose_mixin_from_metadata
  2940. _save() {
  2941. local name="$1"
  2942. cat - | tee -a "$docker_compose_dir/.data/$name"
  2943. }
  2944. export -f _save
  2945. get_default_project_name() {
  2946. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  2947. echo "$DEFAULT_PROJECT_NAME"
  2948. return 0
  2949. fi
  2950. local normalized_path compose_yml_location name
  2951. compose_yml_location="$(get_compose_yml_location)" || return 1
  2952. if [ -n "$compose_yml_location" ]; then
  2953. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2954. name="${normalized_path%/*}" ## dirname
  2955. name="${name##*/}" ## basename
  2956. name="${name%%-deploy}" ## remove any '-deploy'
  2957. name="${name,,}" ## lowercase
  2958. e "$name"
  2959. return 0
  2960. fi
  2961. fi
  2962. echo "orphan"
  2963. return 0
  2964. }
  2965. export -f get_default_project_name
  2966. get_running_compose_containers() {
  2967. ## XXXvlab: docker bug: there will be a final newline anyway
  2968. docker ps --filter label="compose.service" --format='{{.ID}}'
  2969. }
  2970. export -f get_running_compose_containers
  2971. get_healthy_container_ip_for_service () {
  2972. local service="$1" port="$2" timeout=${3:-60}
  2973. local containers container container_network container_ip
  2974. containers="$(get_running_containers_for_service "$service")"
  2975. if [ -z "$containers" ]; then
  2976. err "No containers running for service $DARKYELLOW$service$NORMAL."
  2977. return 1
  2978. fi
  2979. ## XXXvlab: taking first container is probably not a good idea
  2980. container="$(echo "$containers" | head -n 1)"
  2981. ## XXXvlab: taking first ip is probably not a good idea
  2982. read-0 container_network container_ip < <(get_container_network_ip "$container")
  2983. if [ -z "$container_ip" ]; then
  2984. err "Can't get container's IP. You should check health of" \
  2985. "${DARKYELLOW}$service${NORMAL}'s container."
  2986. return 1
  2987. fi
  2988. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  2989. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  2990. echo " Please check that container is healthy. Here are last logs:" >&2
  2991. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  2992. return 1
  2993. }
  2994. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  2995. echo "$container_network:$container_ip"
  2996. }
  2997. export -f get_healthy_container_ip_for_service
  2998. switch_to_relation_service() {
  2999. local relation="$1"
  3000. ## XXXvlab: can't get real config here
  3001. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  3002. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  3003. return 1
  3004. fi
  3005. export SERVICE_NAME="$ts"
  3006. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  3007. DOCKER_BASE_IMAGE=$(service_base_docker_image "$SERVICE_NAME")
  3008. export DOCKER_BASE_IMAGE
  3009. target_charm=$(get_service_charm "$ts") || return 1
  3010. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  3011. cd "$target_charm_path"
  3012. }
  3013. export -f switch_to_relation_service
  3014. get_volumes_for_container() {
  3015. local container="$1"
  3016. docker inspect \
  3017. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  3018. "$container"
  3019. }
  3020. export -f get_volumes_for_container
  3021. is_volume_used() {
  3022. local volume="$1" container_id src dst
  3023. while read -r container_id; do
  3024. while read-0 src dst; do
  3025. [[ "$src/" == "$volume"/* ]] && return 0
  3026. done < <(get_volumes_for_container "$container_id")
  3027. done < <(get_running_compose_containers)
  3028. return 1
  3029. }
  3030. export -f is_volume_used
  3031. clean_unused_docker_compose() {
  3032. for f in /var/lib/compose/docker-compose/*; do
  3033. [ -e "$f" ] || continue
  3034. is_volume_used "$f" && continue
  3035. debug "Cleaning unused docker-compose ${f##*/}"
  3036. rm -rf "$f" || return 1
  3037. done
  3038. return 0
  3039. }
  3040. export -f clean_unused_docker_compose
  3041. stdin_get_hash() {
  3042. local sha
  3043. sha=$(sha256sum) || return 1
  3044. sha=${sha:0:64}
  3045. echo "$sha"
  3046. }
  3047. export -f stdin_get_hash
  3048. file_get_hash() {
  3049. stdin_get_hash < "$1" || return 1
  3050. }
  3051. export -f file_get_hash
  3052. docker_compose_store() {
  3053. local file="$1" sha
  3054. sha=$(file_get_hash "$file") || return 1
  3055. project=$(get_default_project_name) || return 1
  3056. dst="/var/lib/compose/docker-compose/$sha/$project"
  3057. mkdir -p "$dst" || return 1
  3058. cat <<EOF > "$dst/.env" || return 1
  3059. DOCKER_COMPOSE_PATH=$dst
  3060. COMPOSE_HTTP_TIMEOUT=7200
  3061. EOF
  3062. cp "$file" "$dst/docker-compose.yml" || return 1
  3063. mkdir -p "$dst/bin" || return 1
  3064. cat <<EOF > "$dst/bin/dc" || return 1
  3065. #!/bin/bash
  3066. $(declare -f read-0)
  3067. docker_run_opts=()
  3068. while read-0 opt; do
  3069. if [[ "\$opt" == "!env:"* ]]; then
  3070. opt="\${opt##!env:}"
  3071. var="\${opt%%=*}"
  3072. value="\${opt#*=}"
  3073. export "\$var"="\$value"
  3074. else
  3075. docker_run_opts+=("\$opt")
  3076. fi
  3077. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  3078. docker_run_opts+=(
  3079. "-w" "$dst"
  3080. "--entrypoint" "/usr/local/bin/docker-compose"
  3081. )
  3082. [ -t 1 ] && {
  3083. docker_run_opts+=("-ti")
  3084. }
  3085. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  3086. EOF
  3087. chmod +x "$dst/bin/dc" || return 1
  3088. printf "%s" "$sha"
  3089. }
  3090. export -f docker_compose_store
  3091. launch_docker_compose() {
  3092. local charm docker_compose_tmpdir docker_compose_dir
  3093. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3094. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  3095. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  3096. ## docker-compose will name network from the parent dir name
  3097. project=$(get_default_project_name)
  3098. mkdir -p "$docker_compose_tmpdir/$project"
  3099. docker_compose_dir="$docker_compose_tmpdir/$project"
  3100. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  3101. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  3102. # debug "Merging some config data in docker-compose.yml:"
  3103. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  3104. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  3105. fi
  3106. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  3107. die "Generated 'docker-compose.yml' is unexpectedly empty."
  3108. fi
  3109. ## XXXvlab: could be more specific and only link the needed charms
  3110. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  3111. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  3112. # if charm.exists "$charm"; then
  3113. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  3114. # fi
  3115. # done
  3116. mkdir "$docker_compose_dir/.data"
  3117. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3118. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  3119. fi
  3120. {
  3121. {
  3122. {
  3123. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  3124. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  3125. else
  3126. cd "$docker_compose_dir" || return 1
  3127. fi
  3128. if [ -f ".env" ]; then
  3129. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3130. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  3131. fi
  3132. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  3133. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  3134. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  3135. if [ "$DRY_COMPOSE_RUN" ]; then
  3136. echo docker-compose "$@"
  3137. else
  3138. docker-compose "$@"
  3139. fi
  3140. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3141. } | _save stdout
  3142. } 3>&1 1>&2 2>&3 | _save stderr
  3143. } 3>&1 1>&2 2>&3
  3144. 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
  3145. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3146. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3147. fi
  3148. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3149. if [ -z "$docker_compose_errlvl" ]; then
  3150. err "Something went wrong before you could gather docker-compose errorlevel."
  3151. return 1
  3152. fi
  3153. return "$docker_compose_errlvl"
  3154. }
  3155. export -f launch_docker_compose
  3156. get_compose_yml_location() {
  3157. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3158. echo "$COMPOSE_YML_FILE"
  3159. return 0
  3160. fi
  3161. parent=$(while ! [ -f "./compose.yml" ]; do
  3162. [ "$PWD" == "/" ] && exit 0
  3163. cd ..
  3164. done; echo "$PWD"
  3165. )
  3166. if [ "$parent" ]; then
  3167. echo "$parent/compose.yml"
  3168. return 0
  3169. fi
  3170. ## XXXvlab: do we need this additional environment variable,
  3171. ## COMPOSE_YML_FILE is not sufficient ?
  3172. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3173. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3174. warn "No 'compose.yml' was found in current or parent dirs," \
  3175. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3176. "(${DEFAULT_COMPOSE_FILE})"
  3177. return 0
  3178. fi
  3179. echo "$DEFAULT_COMPOSE_FILE"
  3180. return 0
  3181. fi
  3182. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3183. return 0
  3184. }
  3185. export -f get_compose_yml_location
  3186. get_compose_yml_content() {
  3187. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3188. if [ -e "$cache_file" ]; then
  3189. cat "$cache_file" &&
  3190. touch "$cache_file" || return 1
  3191. return 0
  3192. fi
  3193. if [ -z "$COMPOSE_YML_FILE" ]; then
  3194. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3195. fi
  3196. if [ -e "$COMPOSE_YML_FILE" ]; then
  3197. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3198. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3199. err "Could not read '$COMPOSE_YML_FILE'."
  3200. return 1
  3201. }
  3202. else
  3203. debug "No compose file found. Using an empty one."
  3204. COMPOSE_YML_CONTENT=""
  3205. fi
  3206. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3207. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3208. if [ "$?" != 0 ]; then
  3209. outputed_something=
  3210. while IFS='' read -r line1 && IFS='' read -r line2; do
  3211. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3212. outputed_something=true
  3213. echo "$line1 $GRAY($line2)$NORMAL"
  3214. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3215. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3216. prefix " $GRAY|$NORMAL "
  3217. [ "$outputed_something" ] || {
  3218. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3219. echo "$output" | prefix " $GRAY|$NORMAL "
  3220. }
  3221. return 1
  3222. fi
  3223. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3224. }
  3225. export -f get_compose_yml_content
  3226. get_default_target_services() {
  3227. local services=("$@")
  3228. if [ -z "${services[*]}" ]; then
  3229. if [ "$DEFAULT_SERVICES" ]; then
  3230. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3231. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3232. services="$DEFAULT_SERVICES"
  3233. else
  3234. err "No service provided."
  3235. return 1
  3236. fi
  3237. fi
  3238. echo "${services[*]}"
  3239. }
  3240. export -f get_default_target_services
  3241. get_master_services() {
  3242. local loaded master_service service
  3243. declare -A loaded
  3244. for service in "$@"; do
  3245. master_service=$(get_top_master_service_for_service "$service") || return 1
  3246. if [ "${loaded[$master_service]}" ]; then
  3247. continue
  3248. fi
  3249. echo "$master_service"
  3250. loaded["$master_service"]=1
  3251. done | nspc
  3252. return "${PIPESTATUS[0]}"
  3253. }
  3254. export -f get_master_services
  3255. get_current_docker_container_id() {
  3256. local line
  3257. line=$(cat "/proc/self/cpuset") || return 1
  3258. [[ "$line" == *docker* ]] || return 1
  3259. echo "${line##*/}"
  3260. }
  3261. export -f get_current_docker_container_id
  3262. ## if we are in a docker compose, we might want to know what is the
  3263. ## real host path of some local paths.
  3264. get_host_path() {
  3265. local path="$1"
  3266. path=$(realpath "$path") || return 1
  3267. container_id=$(get_current_docker_container_id) || {
  3268. print "%s" "$path"
  3269. return 0
  3270. }
  3271. biggest_dst=
  3272. current_src=
  3273. while read-0 src dst; do
  3274. [[ "$path" == "$dst"* ]] || continue
  3275. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3276. biggest_dst="$dst"
  3277. current_src="$src"
  3278. fi
  3279. done < <(get_volumes_for_container "$container_id")
  3280. if [ "$current_src" ]; then
  3281. printf "%s" "$current_src"
  3282. else
  3283. return 1
  3284. fi
  3285. }
  3286. export -f get_host_path
  3287. _setup_state_dir() {
  3288. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3289. #debug "Creating temporary state directory in '$state_tmpdir'."
  3290. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3291. # rm -rf \"$state_tmpdir\""
  3292. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3293. }
  3294. get_docker_compose_help_msg() {
  3295. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3296. docker_compose_help_msg
  3297. if [ -e "$cache_file" ]; then
  3298. cat "$cache_file" &&
  3299. touch "$cache_file" || return 1
  3300. return 0
  3301. fi
  3302. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3303. echo "$docker_compose_help_msg" |
  3304. tee "$cache_file" || return 1
  3305. }
  3306. get_docker_compose_usage() {
  3307. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3308. docker_compose_help_msg
  3309. if [ -e "$cache_file" ]; then
  3310. cat "$cache_file" &&
  3311. touch "$cache_file" || return 1
  3312. return 0
  3313. fi
  3314. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3315. echo "$docker_compose_help_msg" |
  3316. grep -m 1 "^Usage:" -A 10000 |
  3317. egrep -m 1 "^\$" -B 10000 |
  3318. nspc |
  3319. sed -r 's/^Usage: //g' |
  3320. tee "$cache_file" || return 1
  3321. }
  3322. get_docker_compose_opts_help() {
  3323. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3324. docker_compose_help_msg
  3325. if [ -e "$cache_file" ]; then
  3326. cat "$cache_file" &&
  3327. touch "$cache_file" || return 1
  3328. return 0
  3329. fi
  3330. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3331. echo "$docker_compose_opts_help" |
  3332. grep '^Options:' -A 20000 |
  3333. tail -n +2 |
  3334. { cat ; echo; } |
  3335. egrep -m 1 "^\S*\$" -B 10000 |
  3336. head -n -1 |
  3337. tee "$cache_file" || return 1
  3338. }
  3339. get_docker_compose_commands_help() {
  3340. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3341. docker_compose_help_msg
  3342. if [ -e "$cache_file" ]; then
  3343. cat "$cache_file" &&
  3344. touch "$cache_file" || return 1
  3345. return 0
  3346. fi
  3347. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3348. echo "$docker_compose_opts_help" |
  3349. grep '^Commands:' -A 20000 |
  3350. tail -n +2 |
  3351. { cat ; echo; } |
  3352. egrep -m 1 "^\S*\$" -B 10000 |
  3353. head -n -1 |
  3354. tee "$cache_file" || return 1
  3355. }
  3356. get_docker_compose_opts_list() {
  3357. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3358. docker_compose_help_msg
  3359. if [ -e "$cache_file" ]; then
  3360. cat "$cache_file" &&
  3361. touch "$cache_file" || return 1
  3362. return 0
  3363. fi
  3364. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3365. echo "$docker_compose_opts_help" |
  3366. egrep "^\s+-" |
  3367. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3368. tee "$cache_file" || return 1
  3369. }
  3370. options_parser() {
  3371. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3372. printf "\0"
  3373. }
  3374. remove_options_in_option_help_msg() {
  3375. {
  3376. read-0 null
  3377. if [ "$null" ]; then
  3378. err "options parsing error, should start with an option line."
  3379. return 1
  3380. fi
  3381. while read-0 opt full_txt;do
  3382. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3383. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3384. for to_remove in "$@"; do
  3385. str_matches "$to_remove" $multi_opts $single_opts && {
  3386. continue 2
  3387. }
  3388. done
  3389. echo -n "$full_txt"
  3390. done
  3391. } < <(options_parser)
  3392. }
  3393. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3394. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3395. multi_opts_filter() {
  3396. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3397. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3398. tr ',' "\n" | nspc
  3399. }
  3400. single_opts_filter() {
  3401. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3402. tr ',' "\n" | nspc
  3403. }
  3404. get_docker_compose_multi_opts_list() {
  3405. local action="$1" opts_list
  3406. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3407. echo "$opts_list" | multi_opts_filter
  3408. }
  3409. get_docker_compose_single_opts_list() {
  3410. local action="$1" opts_list
  3411. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3412. echo "$opts_list" | single_opts_filter
  3413. }
  3414. display_commands_help() {
  3415. local charm_actions
  3416. echo
  3417. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3418. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3419. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3420. if [ "$charm_actions_help" ]; then
  3421. echo
  3422. echo "${WHITE}Charm actions${NORMAL}:"
  3423. printf "%s\n" "$charm_actions_help" | \
  3424. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3425. fi
  3426. }
  3427. get_docker_charm_action() {
  3428. local services service charm relation_name target_service relation_config \
  3429. target_charm
  3430. services=($(get_compose_yml_content | yq -r 'keys().[]' 2>/dev/null)) || return 1
  3431. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3432. services=($(get_all_services)) || return 1
  3433. for service in "${services[@]}"; do
  3434. printf "%s:\n" "$service"
  3435. charm=$(get_service_charm "$service") || return 1
  3436. for action in $(charm.ls_direct_actions "$charm"); do
  3437. printf " %s:\n" "$action"
  3438. printf " type: %s\n" "direct"
  3439. done
  3440. while read-0 relation_name target_service _relation_config _tech_dep; do
  3441. target_charm=$(get_service_charm "$target_service") || return 1
  3442. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3443. printf " %s:\n" "$action"
  3444. printf " type: %s\n" "indirect"
  3445. printf " inherited: %s\n" "$target_charm"
  3446. done
  3447. done < <(get_service_relations "$service")
  3448. done
  3449. }
  3450. export -f get_docker_charm_action
  3451. get_docker_charm_action_help() {
  3452. local services service charm relation_name target_service relation_config \
  3453. target_charm
  3454. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3455. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3456. for service in "${services[@]}"; do
  3457. out=$(
  3458. charm=$(get_service_charm "$service") || return 1
  3459. for action in $(charm.ls_direct_actions "$charm"); do
  3460. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3461. done
  3462. while read-0 relation_name target_service _relation_config _tech_dep; do
  3463. target_charm=$(get_service_charm "$target_service") || return 1
  3464. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3465. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3466. done
  3467. done < <(get_service_relations "$service")
  3468. )
  3469. if [ "$out" ]; then
  3470. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3471. printf "%s\n" "$out"
  3472. fi
  3473. done
  3474. }
  3475. display_help() {
  3476. print_help
  3477. echo "${WHITE}Usage${NORMAL}:"
  3478. echo " $usage"
  3479. echo "${WHITE}Options${NORMAL}:"
  3480. echo " -h, --help Print this message and quit"
  3481. echo " (ignoring any other options)"
  3482. echo " -V, --version Print current version and quit"
  3483. echo " (ignoring any other options)"
  3484. echo " --dirs Display data dirs and quit"
  3485. echo " (ignoring any other options)"
  3486. echo " --get-project-name Display project name and quit"
  3487. echo " (ignoring any other options)"
  3488. echo " --get-available-actions Display all available actions and quit"
  3489. echo " (ignoring any other options)"
  3490. echo " -v, --verbose Be more verbose"
  3491. echo " -q, --quiet Be quiet"
  3492. echo " -d, --debug Print full debugging information (sets also verbose)"
  3493. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3494. echo " command line will be used."
  3495. echo " --no-relations Do not run any relation script"
  3496. echo " --no-hooks Do not run any hook script"
  3497. echo " --no-init Do not run any init script"
  3498. echo " --no-post-deploy Do not run any post-deploy script"
  3499. echo " --no-pre-deploy Do not run any pre-deploy script"
  3500. echo " --without-relation RELATION "
  3501. echo " Do not run given relation"
  3502. echo " -R, --rebuild-relations-to-service SERVICE"
  3503. echo " Will rebuild all relations to given service"
  3504. echo " --add-compose-content, -Y YAML"
  3505. echo " Will merge some direct YAML with the current compose"
  3506. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  3507. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3508. filter_docker_compose_help_message
  3509. display_commands_help
  3510. }
  3511. _graph_service() {
  3512. local service="$1" base="$1"
  3513. charm=$(get_service_charm "$service") || return 1
  3514. metadata=$(charm.metadata "$charm") || return 1
  3515. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3516. if [[ "$subordinate" =~ ^True|true$ ]]; then
  3517. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3518. master_charm=
  3519. while read-0 relation_name relation; do
  3520. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3521. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3522. if [ -z "$interface" ]; then
  3523. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3524. return 1
  3525. fi
  3526. ## Action provided by relation ?
  3527. target_service=
  3528. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3529. [ "$interface" == "$relation_name" ] && {
  3530. target_service="$candidate_target_service"
  3531. break
  3532. }
  3533. done < <(get_service_relations "$service")
  3534. if [ -z "$target_service" ]; then
  3535. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3536. "${DARKYELLOW}$service$NORMAL compose definition."
  3537. return 1
  3538. fi
  3539. master_service="$target_service"
  3540. master_charm=$(get_service_charm "$target_service") || return 1
  3541. break
  3542. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3543. fi
  3544. _graph_node_service "$service" "$base" "$charm"
  3545. _graph_edge_service "$service" "$subordinate" "$master_service"
  3546. }
  3547. _graph_node_service() {
  3548. local service="$1" base="$2" charm="$3"
  3549. cat <<EOF
  3550. "$(_graph_node_service_label ${service})" [
  3551. style = "filled, $([[ "$subordinate" =~ ^True|true$ ]] && echo "dashed" || echo "bold")"
  3552. penwidth = $([[ "$subordinate" =~ ^True|true$ ]] && echo "3" || echo "5")
  3553. color = $([ "$base" ] && echo "blue" || echo "black")
  3554. fillcolor = "white"
  3555. fontname = "Courier New"
  3556. shape = "Mrecord"
  3557. label =<$(_graph_node_service_content "$service")>
  3558. ];
  3559. EOF
  3560. }
  3561. _graph_edge_service() {
  3562. local service="$1" subordinate="$2" master_service="$3"
  3563. while read-0 relation_name target_service relation_config tech_dep; do
  3564. cat <<EOF
  3565. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3566. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3567. fontsize = 16
  3568. fontcolor = "black"
  3569. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3570. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3571. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3572. arrowtail = odot
  3573. # arrowhead = dotlicurve
  3574. taillabel = "$relation_name" ];
  3575. EOF
  3576. done < <(get_service_relations "$service") || return 1
  3577. }
  3578. _graph_node_service_label() {
  3579. local service="$1"
  3580. echo "service_$service"
  3581. }
  3582. _graph_node_service_content() {
  3583. local service="$1"
  3584. charm=$(get_service_charm "$service") || return 1
  3585. cat <<EOF
  3586. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3587. <tr>
  3588. <td bgcolor="black" align="center" colspan="2">
  3589. <font color="white">$service</font>
  3590. </td>
  3591. </tr>
  3592. $(if [ "$charm" != "$service" ]; then
  3593. cat <<EOF2
  3594. <tr>
  3595. <td align="left" port="r0">charm: $charm</td>
  3596. </tr>
  3597. EOF2
  3598. fi)
  3599. </table>
  3600. EOF
  3601. }
  3602. cla_contains () {
  3603. local e
  3604. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3605. return 1
  3606. }
  3607. filter_docker_compose_help_message() {
  3608. cat - |
  3609. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3610. s/docker-compose.yml/compose.yml/g;
  3611. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3612. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3613. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3614. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3615. }
  3616. graph() {
  3617. local services=("$@")
  3618. declare -A entries
  3619. cat <<EOF
  3620. digraph g {
  3621. graph [
  3622. fontsize=30
  3623. labelloc="t"
  3624. label=""
  3625. splines=true
  3626. overlap=false
  3627. #rankdir = "LR"
  3628. ];
  3629. ratio = auto;
  3630. EOF
  3631. for target_service in "$@"; do
  3632. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3633. for service in $services; do
  3634. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3635. if cla_contains "$service" "${services[@]}"; then
  3636. base=true
  3637. else
  3638. base=
  3639. fi
  3640. _graph_service "$service" "$base"
  3641. done
  3642. done
  3643. echo "}"
  3644. }
  3645. cached_wget() {
  3646. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  3647. url="$1"
  3648. if [ -e "$cache_file" ]; then
  3649. cat "$cache_file"
  3650. touch "$cache_file"
  3651. return 0
  3652. fi
  3653. wget -O- "${url}" |
  3654. tee "$cache_file"
  3655. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3656. rm "$cache_file"
  3657. die "Unable to fetch '$url'."
  3658. return 1
  3659. fi
  3660. }
  3661. export -f cached_wget
  3662. [ "$SOURCED" ] && return 0
  3663. trap_add "EXIT" clean_cache
  3664. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3665. if [ -r /etc/default/charm ]; then
  3666. . /etc/default/charm
  3667. fi
  3668. if [ -r "/etc/default/$exname" ]; then
  3669. . "/etc/default/$exname"
  3670. fi
  3671. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3672. ## userdir ? and global /etc/compose.yml ?
  3673. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3674. /etc/default/compose /etc/compose/local.conf; do
  3675. [ -e "$cfgfile" ] || continue
  3676. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3677. done
  3678. fi
  3679. _setup_state_dir
  3680. mkdir -p "$CACHEDIR" || exit 1
  3681. log () { cat; }
  3682. export -f log
  3683. ##
  3684. ## Argument parsing
  3685. ##
  3686. wrap_opts=()
  3687. services=()
  3688. remainder_args=()
  3689. compose_opts=()
  3690. compose_contents=()
  3691. action_opts=()
  3692. services_args=()
  3693. pos_arg_ct=0
  3694. no_hooks=
  3695. no_init=
  3696. action=
  3697. stage="main" ## switches from 'main', to 'action', 'remainder'
  3698. is_docker_compose_action=
  3699. rebuild_relations_to_service=()
  3700. color=
  3701. declare -A without_relations
  3702. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3703. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  3704. while read-0 arg; do
  3705. case "$stage" in
  3706. "main")
  3707. case "$arg" in
  3708. --help|-h)
  3709. no_init=true ; no_hooks=true ; no_relations=true
  3710. display_help
  3711. exit 0
  3712. ;;
  3713. --verbose|-v)
  3714. export VERBOSE=true
  3715. compose_opts+=("--verbose")
  3716. ;;
  3717. --quiet|-q)
  3718. export QUIET=true
  3719. export wrap_opts+=("-q")
  3720. log () { cat >&2; }
  3721. export -f log
  3722. ;;
  3723. --version|-V)
  3724. print_version
  3725. docker-compose --version
  3726. docker --version
  3727. exit 0
  3728. ;;
  3729. -f|--file)
  3730. read-0 value
  3731. [ -e "$value" ] || die "File $value doesn't exists"
  3732. export COMPOSE_YML_FILE="$value"
  3733. shift
  3734. ;;
  3735. -p|--project-name)
  3736. read-0 value
  3737. export DEFAULT_PROJECT_NAME="$value"
  3738. compose_opts+=("--project-name $value")
  3739. shift
  3740. ;;
  3741. --color|-c)
  3742. if [ "$color" == "0" ]; then
  3743. err "Conflicting option --color with previous --no-ansi."
  3744. exit 1
  3745. fi
  3746. color=1
  3747. ansi_color yes
  3748. ;;
  3749. --no-ansi)
  3750. if [ "$color" == "1" ]; then
  3751. err "Conflicting option --no-ansi with previous --color."
  3752. exit 1
  3753. fi
  3754. color=0
  3755. ansi_color no
  3756. compose_opts+=("--no-ansi")
  3757. ;;
  3758. --no-relations)
  3759. export no_relations=true
  3760. ;;
  3761. --without-relation)
  3762. read-0 value
  3763. without_relations["$value"]=1
  3764. shift
  3765. ;;
  3766. --no-hooks)
  3767. export no_hooks=true
  3768. ;;
  3769. --no-init)
  3770. export no_init=true
  3771. ;;
  3772. --no-post-deploy)
  3773. export no_post_deploy=true
  3774. ;;
  3775. --no-pre-deploy)
  3776. export no_pre_deploy=true
  3777. ;;
  3778. --rebuild-relations-to-service|-R)
  3779. read-0 value
  3780. rebuild_relations_to_service+=("$value")
  3781. shift
  3782. ;;
  3783. --debug|-d)
  3784. export DEBUG=true
  3785. export VERBOSE=true
  3786. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3787. ;;
  3788. --add-compose-content|-Y)
  3789. read-0 value
  3790. compose_contents+=("$value")
  3791. shift
  3792. ;;
  3793. --dirs)
  3794. echo "CACHEDIR: $CACHEDIR"
  3795. echo "VARDIR: $VARDIR"
  3796. exit 0
  3797. ;;
  3798. --get-project-name)
  3799. project=$(get_default_project_name) || exit 1
  3800. echo "$project"
  3801. exit 0
  3802. ;;
  3803. --get-available-actions)
  3804. get_docker_charm_action
  3805. exit $?
  3806. ;;
  3807. --dry-compose-run)
  3808. export DRY_COMPOSE_RUN=true
  3809. ;;
  3810. --*|-*)
  3811. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3812. read-0 value
  3813. compose_opts+=("$arg" "$value")
  3814. shift;
  3815. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3816. compose_opts+=("$arg")
  3817. else
  3818. err "Unknown option '$arg'. Please check help:"
  3819. display_help >&2
  3820. exit 1
  3821. fi
  3822. ;;
  3823. *)
  3824. action="$arg"
  3825. stage="action"
  3826. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3827. is_docker_compose_action=true
  3828. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3829. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3830. if [ "$DC_MATCH_MULTI" ]; then
  3831. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3832. fi
  3833. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3834. pos_args=("${pos_args[@]:1}")
  3835. # echo "USAGE: $DC_USAGE"
  3836. # echo "pos_args: ${pos_args[@]}"
  3837. # echo "MULTI: $DC_MATCH_MULTI"
  3838. # echo "SINGLE: $DC_MATCH_SINGLE"
  3839. # exit 1
  3840. else
  3841. stage="remainder"
  3842. fi
  3843. ;;
  3844. esac
  3845. ;;
  3846. "action") ## Only for docker-compose actions
  3847. case "$arg" in
  3848. --help|-h)
  3849. no_init=true ; no_hooks=true ; no_relations=true
  3850. action_opts+=("$arg")
  3851. ;;
  3852. --*|-*)
  3853. if [ "$is_docker_compose_action" ]; then
  3854. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3855. read-0 value
  3856. action_opts+=("$arg" "$value")
  3857. shift
  3858. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3859. action_opts+=("$arg")
  3860. else
  3861. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3862. docker-compose "$action" --help |
  3863. filter_docker_compose_help_message >&2
  3864. exit 1
  3865. fi
  3866. fi
  3867. ;;
  3868. *)
  3869. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3870. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3871. services_args+=("$arg")
  3872. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3873. services_args=("$arg") || exit 1
  3874. stage="remainder"
  3875. else
  3876. action_posargs+=("$arg")
  3877. ((pos_arg_ct++))
  3878. fi
  3879. ;;
  3880. esac
  3881. ;;
  3882. "remainder")
  3883. remainder_args+=("$arg")
  3884. while read-0 arg; do
  3885. remainder_args+=("$arg")
  3886. done
  3887. break 3
  3888. ;;
  3889. esac
  3890. shift
  3891. done < <(cla.normalize "$@")
  3892. export compose_contents
  3893. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3894. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3895. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3896. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3897. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3898. aexport remainder_args
  3899. ##
  3900. ## Actual code
  3901. ##
  3902. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3903. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3904. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3905. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3906. ##
  3907. ## Get services in command line.
  3908. ##
  3909. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3910. action_service=${remainder_args[0]}
  3911. if [ -z "$action_service" ]; then
  3912. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3913. display_commands_help
  3914. exit 1
  3915. fi
  3916. ## Required by has_service_action
  3917. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3918. NO_CONSTRAINT_CHECK=1 get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3919. remainder_args=("${remainder_args[@]:1}")
  3920. if has_service_action "$action_service" "$action" >/dev/null; then
  3921. is_service_action=true
  3922. services_args=("$action_service")
  3923. {
  3924. read-0 action_type
  3925. case "$action_type" in
  3926. "relation")
  3927. read-0 _ target_service _target_charm relation_name _ action_script_path
  3928. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3929. services_args+=("$target_service")
  3930. ;;
  3931. "direct")
  3932. read-0 _ action_script_path
  3933. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3934. ;;
  3935. esac
  3936. } < <(has_service_action "$action_service" "$action")
  3937. get_all_relations "${services_args[@]}" >/dev/null || {
  3938. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  3939. exit 1
  3940. }
  3941. ## Divert logging to stdout to stderr
  3942. log () { cat >&2; }
  3943. export -f log
  3944. else
  3945. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3946. fi
  3947. else
  3948. case "$action" in
  3949. ps|up)
  3950. if [ "${#services_args[@]}" == 0 ]; then
  3951. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3952. fi
  3953. ;;
  3954. config)
  3955. services_args=("${action_posargs[@]}")
  3956. ;;
  3957. esac
  3958. fi
  3959. export COMPOSE_ACTION="$action"
  3960. NO_CONSTRAINT_CHECK=True
  3961. case "$action" in
  3962. up)
  3963. NO_CONSTRAINT_CHECK=
  3964. ;;
  3965. esac
  3966. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3967. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3968. services=($(get_master_services "${services_args[@]}")) || exit 1
  3969. if [ "$action" == "up" ]; then
  3970. declare -A seen
  3971. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3972. mservice=$(get_master_service_for_service "$service") || exit 1
  3973. [ "${seen[$mservice]}" ] && continue
  3974. type="$(get_service_type "$mservice")" || exit 1
  3975. ## remove run-once
  3976. [ "$type" == "run-once" ] && continue
  3977. [ "$type" == "stub" ] && continue
  3978. seen[$mservice]=1
  3979. action_posargs+=("$mservice")
  3980. done
  3981. else
  3982. action_posargs+=("${services[@]}")
  3983. fi
  3984. ## Get rid of subordinates
  3985. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  3986. fi
  3987. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3988. err "Fails to compile base 'docker-compose.yml'"
  3989. exit 1
  3990. }
  3991. ##
  3992. ## Pre-action
  3993. ##
  3994. full_init=
  3995. case "$action" in
  3996. up|run)
  3997. full_init=true
  3998. post_hook=true
  3999. ;;
  4000. ""|down|restart|logs|config|ps)
  4001. full_init=
  4002. ;;
  4003. *)
  4004. if [ "$is_service_action" ]; then
  4005. full_init=true
  4006. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  4007. for keyword in "${keywords[@]}"; do
  4008. case "$keyword" in
  4009. no-hooks)
  4010. no_hooks=true
  4011. ;;
  4012. hooks)
  4013. full_init=true
  4014. ;;
  4015. esac
  4016. done
  4017. fi
  4018. ;;
  4019. esac
  4020. if [ -n "$full_init" ]; then
  4021. ## init in order
  4022. if [[ -z "$no_init" && -z "$no_hooks" ]]; then
  4023. Section setup host resources
  4024. setup_host_resources "${services_args[@]}" || exit 1
  4025. Section initialisation
  4026. run_service_hook init "${services_args[@]}" || exit 1
  4027. fi
  4028. ## Get relations
  4029. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  4030. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  4031. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  4032. rebuild_relations_to_service=($rebuild_relations_to_service)
  4033. project=$(get_default_project_name) || return 1
  4034. for service in "${rebuild_relations_to_service[@]}"; do
  4035. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  4036. [ -d "$dir" ] && {
  4037. debug rm -rf "$dir"
  4038. rm -rf "$dir"
  4039. }
  4040. done
  4041. done
  4042. fi
  4043. run_service_relations "${services_args[@]}" || exit 1
  4044. fi
  4045. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  4046. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  4047. fi
  4048. fi | log
  4049. if [ "${PIPESTATUS[0]}" != 0 ]; then
  4050. exit 1
  4051. fi
  4052. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  4053. charm=$(get_service_charm "${services_args[0]}") || exit 1
  4054. metadata=$(charm.metadata "$charm") || exit 1
  4055. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  4056. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4057. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  4058. fi
  4059. fi
  4060. export SERVICE_PACK="${services_args[*]}"
  4061. ##
  4062. ## Docker-compose
  4063. ##
  4064. errlvl="0"
  4065. case "$action" in
  4066. up|start|stop|build|run)
  4067. ## force daemon mode for up
  4068. if [[ "$action" == "up" ]]; then
  4069. if ! array_member action_opts -d; then
  4070. action_opts+=("-d")
  4071. fi
  4072. if ! array_member action_opts --remove-orphans; then
  4073. action_opts+=("--remove-orphans")
  4074. fi
  4075. fi
  4076. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4077. ;;
  4078. logs)
  4079. if ! array_member action_opts --tail; then ## force daemon mode for up
  4080. action_opts+=("--tail" "10")
  4081. fi
  4082. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4083. ;;
  4084. "")
  4085. launch_docker_compose "${compose_opts[@]}"
  4086. ;;
  4087. graph)
  4088. graph $SERVICE_PACK
  4089. ;;
  4090. config)
  4091. ## removing the services
  4092. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  4093. ## forcing docker-compose config to output the config file to stdout and not stderr
  4094. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  4095. echo "$out"
  4096. exit 1
  4097. }
  4098. echo "$out"
  4099. warn "Runtime configuration modification (from relations) are not included here."
  4100. ;;
  4101. down)
  4102. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  4103. debug "Adding a default argument of '--remove-orphans'"
  4104. action_opts+=("--remove-orphans")
  4105. fi
  4106. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  4107. ;;
  4108. *)
  4109. if [ "$is_service_action" ]; then
  4110. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  4111. errlvl="$?"
  4112. errlvl "$errlvl"
  4113. else
  4114. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  4115. fi
  4116. ;;
  4117. esac || exit 1
  4118. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  4119. run_service_hook post_deploy "${services_args[@]}" || exit 1
  4120. fi
  4121. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  4122. if [ "$SERVICE_TYPE" == "run-once" ]; then
  4123. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  4124. fi
  4125. fi
  4126. clean_unused_docker_compose || exit 1
  4127. exit "$errlvl"