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.

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