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.

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