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.

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