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.

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