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.

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