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.

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