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.

4216 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="$HOST_DATASTORE/${SERVICE_NAME}$DB_DATADIR"
  593. if is_db_locked; then
  594. info "Some process is using '$host_db_working_dir'. Trying to find a docker that would do this..."
  595. found=
  596. for docker_id in $(docker ps -q); do
  597. has_volume_mounted=$(
  598. docker inspect \
  599. --format "{{range .Mounts}}{{if eq .Destination \"$DB_DATADIR\"}}{{.Source}}{{end}}{{end}}" \
  600. "$docker_id")
  601. if [ "$has_volume_mounted" == "$host_db_working_dir" ]; then
  602. found="$docker_id"
  603. break
  604. fi
  605. done
  606. if [ -z "$found" ]; then
  607. err "Please shutdown any other docker using this directory."
  608. return 1
  609. fi
  610. export container_id="$found"
  611. info "Found docker $docker_id is already running."
  612. else
  613. verb "Database is not locked."
  614. if ! docker_has_image "$DOCKER_BASE_IMAGE"; then
  615. docker pull "$DOCKER_BASE_IMAGE"
  616. fi
  617. _set_server_db_params
  618. debug docker network create "$_DB_NAME"
  619. if ! network_id=$(docker network create "$_DB_NAME"); then
  620. err "'docker network create $_DB_NAME' failed !"
  621. _clean_docker "$_DB_NAME" "$container_id"
  622. rm "$state_tmpdir/${_DB_NAME}.working"
  623. return 1
  624. fi
  625. debug docker run -d \
  626. --name "$_DB_NAME" \
  627. "${server_docker_opts[@]}" \
  628. --network "$_DB_NAME" \
  629. -v "$host_db_working_dir:$DB_DATADIR" \
  630. "$DOCKER_BASE_IMAGE"
  631. if ! container_id=$(
  632. docker run -d \
  633. --name "$_DB_NAME" \
  634. "${server_docker_opts[@]}" \
  635. --network "$_DB_NAME" \
  636. -v "$host_db_working_dir:$DB_DATADIR" \
  637. "$DOCKER_BASE_IMAGE"
  638. ); then
  639. err "'docker run' failed !"
  640. _clean_docker "$_DB_NAME" "$container_id"
  641. rm "$state_tmpdir/${_DB_NAME}.working"
  642. return 1
  643. fi
  644. trap_add EXIT,ERR "_clean_docker \"$_DB_NAME\" \"$container_id\""
  645. fi
  646. if docker_ip=$(wait_for_docker_ip "$container_id"); then
  647. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  648. echo "$docker_ip" > "$_STATE_FILE"
  649. debug "written '$_STATE_FILE'"
  650. rm "$state_tmpdir/${_DB_NAME}.working"
  651. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  652. return 0
  653. else
  654. errlvl="$?"
  655. err "Db not found (errlvl: $errlvl). Tail of docker logs follows:"
  656. docker logs --tail=5 "$container_id" 2>&1 | prefix " | " >&2
  657. rm "$state_tmpdir/${_DB_NAME}.working"
  658. return "$errlvl"
  659. fi
  660. }
  661. export -f ensure_db_docker_running
  662. ## Require to set $db_docker_opts if needed, and $DB_PASSFILE
  663. ##
  664. _dcmd() {
  665. local docker_opts command="$1"
  666. shift
  667. debug "Db> $command $@"
  668. if [ "$HOST_DB_PASSFILE" -a -f "$LOCAL_DB_PASSFILE" -a "$CLIENT_DB_PASSFILE" ]; then
  669. verb "Found and using '$HOST_DB_PASSFILE' as '$CLIENT_DB_PASSFILE'."
  670. docker_opts=("${db_docker_opts[@]}" "-v" "$HOST_DB_PASSFILE:$CLIENT_DB_PASSFILE")
  671. else
  672. docker_opts=("${db_docker_opts[@]}")
  673. fi
  674. ## XXXX was here: actualy, we need only connection between this version and the client version
  675. debug docker run -i --rm \
  676. "${docker_opts[@]}" \
  677. --entrypoint "$command" "$DOCKER_BASE_IMAGE" "${db_cmd_opts[@]}" "$@"
  678. docker run -i --rm \
  679. "${docker_opts[@]}" \
  680. --entrypoint "$command" "$DOCKER_BASE_IMAGE" "${db_cmd_opts[@]}" "$@"
  681. }
  682. export -f _dcmd
  683. ## Executes code through db
  684. dcmd() {
  685. local fun
  686. [ "$DB_NAME" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_NAME."
  687. [ "$DB_DATADIR" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_DATADIR."
  688. # [ "$DB_PASSFILE" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_PASSFILE."
  689. [ "$_PID" ] || print_syntax_error "$FUNCNAME: You must provide \$_PID."
  690. for fun in is_db_locked _set_db_params ddb; do
  691. [ "$(type -t "$fun")" == "function" ] ||
  692. print_syntax_error "$FUNCNAME: You must provide function '$fun'."
  693. done
  694. ensure_db_docker_running </dev/null || return 1
  695. _dcmd "$@"
  696. }
  697. export -f dcmd
  698. get_docker_ips() {
  699. local name="$1" ip format network_id
  700. if ! docker inspect --format='{{ .NetworkSettings.Networks }}' "$name" >/dev/null 2>&1; then
  701. echo "default:$(docker inspect --format='{{ .NetworkSettings.IPAdress }}' "$name" 2>/dev/null)"
  702. else
  703. format='{{range $name, $conf := .NetworkSettings.Networks}}{{$name}}{{"\x00"}}{{$conf.IPAddress}}{{"\x00"}}{{end}}'
  704. while read-0 network_id ip; do
  705. printf "%s:%s\n" "$network_id" "$ip"
  706. done < <(docker inspect --format="$format" "$name")
  707. fi
  708. }
  709. export -f get_docker_ips
  710. get_docker_ip() {
  711. local name="$1"
  712. get_docker_ips "$name"
  713. }
  714. export -f get_docker_ip
  715. wait_docker_ip() {
  716. local name="$1" timeout="${2:-15}" timeout_count=0 docker_ip=
  717. start=$SECONDS
  718. while [ -z "$docker_ip" ]; do
  719. sleep 0.5
  720. docker_ip=$(get_docker_ip "$name") && break
  721. elapsed=$((SECONDS - start))
  722. if ((elapsed > timeout)); then
  723. err "${RED}timeout error${NORMAL}(${timeout}s):" \
  724. "Could not find '$name' docker container's IP."
  725. return 1
  726. fi
  727. [ "$elapsed" == "$old_elapsed" ] ||
  728. verb "Waiting for docker $name... ($elapsed/$timeout)"
  729. old_elapsed="$elapsed"
  730. done
  731. verb "Found docker $name network and IP: $docker_ip"
  732. echo "$docker_ip"
  733. }
  734. export -f wait_docker_ip
  735. wait_for_tcp_port() {
  736. local network=$1 host_port=$2 timeout=20
  737. verb "Trying to connect to $host_port"
  738. bash_image=${DEFAULT_BASH_IMAGE:-docker.0k.io/bash}
  739. echo docker run --rm -i --network "$network" "$bash_image" >&2
  740. docker run --rm -i --network "$network" "$bash_image" <<EOF
  741. start=\$SECONDS
  742. while true; do
  743. timeout 1 bash -c "</dev/tcp/${host_port/://}" >/dev/null 2>&1 && break
  744. sleep 0.2
  745. if [ "\$((SECONDS - start))" -gt "$timeout" ]; then
  746. exit 1
  747. fi
  748. done
  749. exit 0
  750. EOF
  751. if [ "$?" != 0 ]; then
  752. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  753. "Could not connect to $host_port."
  754. return 1
  755. fi
  756. return 0
  757. }
  758. export -f wait_for_tcp_port
  759. ## Warning: requires a ``ddb`` matching current database to be checked
  760. wait_for_docker_ip() {
  761. local name=$1 DOCKER_IP= DOCKER_NETWORK= docker_ips= docker_ip= elapsed timeout=10
  762. docker_ip=$(wait_docker_ip "$name" 5) || return 1
  763. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  764. if ! str_is_ipv4 "$DOCKER_IP"; then
  765. err "internal 'wait_docker_ip' did not return a valid IP. Returned IP is '$DOCKER_IP'."
  766. return 1
  767. fi
  768. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  769. while read-0 port; do
  770. IFS="/" read port type <<<"$port"
  771. [ "$type" == "tcp" ] || continue
  772. wait_for_tcp_port "$DOCKER_NETWORK" "$DOCKER_IP:${port}" || return 17
  773. info "Host/Port $DOCKER_IP:${port} checked ${GREEN}open${NORMAL}."
  774. ## XXXvlab: what to do with more than one port ?
  775. break
  776. done < <(image_exposed_ports_0 "$container_id")
  777. ## Checking direct connection
  778. timeout=30
  779. start=$SECONDS
  780. while true; do
  781. if err=$(echo "$check_command" | ddb 2>&1 >/dev/null); then
  782. break
  783. fi
  784. if ! [[ "$err" == *"the database system is starting up" ]]; then
  785. err "${RED}db connection error${NORMAL}:" \
  786. "Could not connect to db on $DOCKER_IP container's IP."
  787. echo " Note: IP up, TCP ports is(are) open" >&2
  788. if [ "$err" ]; then
  789. echo " Error:" >&2
  790. printf "%s\n" "$err" | prefix " ${RED}!${NORMAL} " >&2
  791. fi
  792. return 18
  793. fi
  794. debug "Got 'database system is starting up' error."
  795. elapsed=$((SECONDS - start))
  796. if ((elapsed > timeout)); then
  797. err "${RED}db connection error${NORMAL}:"\
  798. "Could not connect to db on $DOCKER_IP" \
  799. "container's IP. (IP up, TCP ports is(are) open, sql answer after ${timeout}s)"
  800. return 1
  801. fi
  802. sleep 0.2
  803. done
  804. echo "${DOCKER_NETWORK}:${DOCKER_IP}"
  805. return 0
  806. }
  807. export -f wait_for_docker_ip
  808. docker_add_host_declaration() {
  809. local src_docker=$1 domain=$2 dst_docker=$3 dst_docker_ip= dst_docker_network
  810. dst_docker_ip=$(wait_docker_ip "$dst_docker") || exit 1
  811. IFS=: read dst_docker_ip dst_docker_network <<<"$dst_docker_ip"
  812. docker exec -i "$src_docker" bash <<EOF
  813. if cat /etc/hosts | grep -E "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$" > /dev/null 2>&1; then
  814. sed -ri "s/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$/$dst_docker_ip $domain/g" /etc/hosts
  815. else
  816. echo "$dst_docker_ip $domain" >> /etc/hosts
  817. fi
  818. EOF
  819. }
  820. export -f docker_add_host_declaration
  821. get_running_containers_for_service() {
  822. local service="$1"
  823. docker ps --filter label="compose.service=$service" --format="{{.ID}}"
  824. }
  825. export -f get_running_containers_for_service
  826. get_container_network_ips() {
  827. local container="$1"
  828. docker inspect "$container" \
  829. --format='{{range $key, $val :=.NetworkSettings.Networks}}{{$key}}{{"\x00"}}{{$val.IPAddress}}{{"\x00"}}{{end}}'
  830. }
  831. export -f get_container_network_ips
  832. get_container_network_ip() {
  833. local container="$1"
  834. while read-0 network ip; do
  835. printf "%s\0" "$network" "$ip"
  836. break
  837. done < <(get_container_network_ips "$container")
  838. }
  839. export -f get_container_network_ip
  840. ##
  841. ## Internal Process
  842. ##
  843. get_docker_compose_links() {
  844. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  845. deps master_service master_target_service _relation_name \
  846. target_service _relation_config tech_dep
  847. if [ -z "$service" ]; then
  848. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  849. return 1
  850. fi
  851. if [ -e "$cache_file" ]; then
  852. # debug "$FUNCNAME: cache hit ($*)"
  853. cat "$cache_file"
  854. return 0
  855. fi
  856. master_service=$(get_top_master_service_for_service "$service") || return 1
  857. deps=()
  858. while read-0 _relation_name target_service _relation_config tech_dep; do
  859. master_target_service="$(get_top_master_service_for_service "$target_service")" || return 1
  860. [ "$master_service" == "$master_target_service" ] && continue
  861. type="$(get_service_type "$target_service")" || return 1
  862. [ "$type" == "run-once" ] && continue
  863. if [ "$tech_dep" == "reversed" ]; then
  864. deps+=("$(echo -en "$master_target_service:\n links:\n - $master_service")")
  865. elif [ "$tech_dep" == "True" ]; then
  866. deps+=("$(echo -en "$master_service:\n links:\n - $master_target_service")")
  867. fi
  868. ## XXXvlab: an attempt to add depends_on, but this doesn't work well actually
  869. ## as there's a circular dependency issue. We don't really want the full feature
  870. ## of depends_on, but just to add it as targets when doing an 'up'
  871. # deps+=("$(echo -en "$master_service:\n depends_on:\n - $master_target_service")")
  872. done < <(get_service_relations "$service")
  873. merge_yaml_str "${deps[@]}" | tee "$cache_file" || return 1
  874. if [ "${PIPESTATUS[0]}" != 0 ]; then
  875. rm "$cache_file"
  876. err "Failed to merge YAML from all ${WHITE}links${NORMAL} dependencies."
  877. return 1
  878. fi
  879. }
  880. _get_docker_compose_opts() {
  881. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  882. compose_def master_service docker_compose_opts
  883. if [ -z "$service" ]; then
  884. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  885. return 1
  886. fi
  887. if [ -e "$cache_file" ]; then
  888. # debug "$FUNCNAME: cache hit ($*)"
  889. cat "$cache_file"
  890. return 0
  891. fi
  892. compose_def="$(get_compose_service_def "$service")" || return 1
  893. master_service="$(get_top_master_service_for_service "$service")"
  894. if docker_compose_opts=$(echo "$compose_def" | shyaml get-value -y "docker-compose" 2>/dev/null); then
  895. yaml_key_val_str "$master_service" "$docker_compose_opts"
  896. fi | tee "$cache_file"
  897. if [ "${PIPESTATUS[0]}" != 0 ]; then
  898. rm "$cache_file"
  899. return 1
  900. fi
  901. }
  902. ##
  903. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  904. ## Some metadata.yml (of subordinates) will indeed modify other
  905. ## services than themselves.
  906. _get_docker_compose_service_mixin() {
  907. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  908. links_yaml base_mixin links_yaml docker_compose_options \
  909. charm charm_part
  910. if [ -z "$service" ]; then
  911. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  912. return 1
  913. fi
  914. if [ -e "$cache_file" ]; then
  915. # debug "$FUNCNAME: cache hit ($*)"
  916. cat "$cache_file"
  917. return 0
  918. fi
  919. master_service=$(get_top_master_service_for_service "$service") || {
  920. err "Failed to get top master service for service $DARKYELLOW$service$NORMAL"
  921. return 1
  922. }
  923. ## The compose part
  924. base_mixin="$master_service:
  925. labels:
  926. - compose.service=$service
  927. - compose.master-service=${master_service}
  928. - compose.project=$(get_default_project_name)"
  929. links_yaml=$(get_docker_compose_links "$service") || return 1
  930. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  931. ## the charm part
  932. charm_part=$(get_docker_compose_mixin_from_metadata "$service") || return 1
  933. ## Merge results
  934. if [ "$charm_part" ]; then
  935. charm_yaml="$(yaml_key_val_str "$master_service" "$charm_part")" || return 1
  936. merge_yaml_str "$base_mixin" "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  937. else
  938. merge_yaml_str "$base_mixin" "$links_yaml" "$docker_compose_options" || return 1
  939. fi | tee "$cache_file"
  940. if [ "${PIPESTATUS[0]}" != 0 ]; then
  941. err "Failed to constitute the base YAML for service '${DARKYELLOW}$service${NORMAL}'"
  942. rm "$cache_file"
  943. return 1
  944. fi
  945. }
  946. export -f _get_docker_compose_service_mixin
  947. ##
  948. ## Get full `docker-compose.yml` format for all listed services (and
  949. ## their deps)
  950. ##
  951. ## @export
  952. ## @cache: !system !nofail +stdout
  953. get_docker_compose () {
  954. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  955. entries services service start docker_compose_services
  956. if [ -e "$cache_file" ]; then
  957. # debug "$FUNCNAME: cache hit ($*)"
  958. cat "$cache_file"
  959. return 0
  960. fi
  961. ##
  962. ## Adding sub services configurations
  963. ##
  964. declare -A entries
  965. start_compilation=$SECONDS
  966. debug "Compiling 'docker-compose.yml' base for ${DARKYELLOW}$*$NORMAL..."
  967. for target_service in "$@"; do
  968. start=$SECONDS
  969. services=($(get_ordered_service_dependencies "$target_service")) || {
  970. err "Failed to get dependencies for $DARKYELLOW$target_service$NORMAL"
  971. return 1
  972. }
  973. if [ "$DEBUG" ]; then
  974. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" \
  975. "${services[@]::$((${#services[@]} - 1))}" \
  976. "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  977. fi
  978. for service in "${services[@]}"; do
  979. if [ "${entries[$service]}" ]; then
  980. ## Prevent double inclusion of same service if this
  981. ## service is deps of two or more of your
  982. ## requirements.
  983. continue
  984. fi
  985. ## mark the service as "loaded" as well as it's containers
  986. ## if this is a subordinate service
  987. start_service=$SECONDS
  988. entries[$service]=$(_get_docker_compose_service_mixin "$service") || {
  989. err "Failed to get service mixin for $DARKYELLOW$service$NORMAL"
  990. return 1
  991. }
  992. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  993. done
  994. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  995. done
  996. docker_compose_services=$(merge_yaml_str "${entries[@]}") || {
  997. err "Failed to merge YAML services entries together."
  998. return 1
  999. }
  1000. base_v2="version: '2.0'"
  1001. merge_yaml_str "$(yaml_key_val_str "services" "$docker_compose_services")" \
  1002. "$base_v2" > "$cache_file" || return 1
  1003. export _current_docker_compose="$(cat "$cache_file")"
  1004. echo "$_current_docker_compose"
  1005. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  1006. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  1007. # debug "$_current_docker_compose"
  1008. }
  1009. export -f get_docker_compose
  1010. _get_compose_service_def_cached () {
  1011. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1012. if [ -e "$cache_file" ]; then
  1013. #debug "$FUNCNAME: STATIC cache hit"
  1014. cat "$cache_file" &&
  1015. touch "$cache_file" || return 1
  1016. return 0
  1017. fi
  1018. value=$(echo "$docker_compose" | shyaml get-value "${service//./\\.}" 2>/dev/null)
  1019. [ "$value" == None ] && value=""
  1020. if ! echo "$value" | shyaml get-value "charm" >/dev/null 2>&1; then
  1021. if charm.exists "$service"; then
  1022. value=$(merge_yaml <(echo "charm: $service") <(echo "$value")) || {
  1023. err "Can't merge YAML infered 'charm: $service' with base ${DARKYELLOW}$service${NORMAL} YAML definition."
  1024. return 1
  1025. }
  1026. else
  1027. err "No ${WHITE}charm${NORMAL} value for service $DARKYELLOW$service$NORMAL" \
  1028. "in compose, nor same name charm found."
  1029. return 1
  1030. fi
  1031. fi
  1032. echo "$value" | tee "$cache_file" || return 1
  1033. # if [ "${PIPESTATUS[0]}" != 0 ]; then
  1034. # rm "$cache_file"
  1035. # return 1
  1036. # fi
  1037. return 0
  1038. # if [ "${PIPESTATUS[0]}" != 0 -o \! -s "$cache_file" ]; then
  1039. # rm "$cache_file"
  1040. # err "PAS OK $service: $value"
  1041. # return 1
  1042. # fi
  1043. }
  1044. export -f _get_compose_service_def_cached
  1045. ## XXXvlab: a lot to be done to cache the results
  1046. get_compose_service_def () {
  1047. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1048. result
  1049. if [ -e "$cache_file" ]; then
  1050. #debug "$FUNCNAME: SESSION cache hit"
  1051. cat "$cache_file" || return 1
  1052. return 0
  1053. fi
  1054. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  1055. docker_compose=$(get_compose_yml_content) || return 1
  1056. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  1057. charm=$(echo "$result" | shyaml get-value charm 2>/dev/null) || return 1
  1058. metadata=$(charm.metadata "$charm") || return 1
  1059. if default_options=$(printf "%s" "$metadata" | shyaml -y -q get-value default-options); then
  1060. default_options=$(yaml_key_val_str "options" "$default_options") || return 1
  1061. result=$(merge_yaml_str "$default_options" "$result") || return 1
  1062. fi
  1063. echo "$result" | tee "$cache_file" || return 1
  1064. }
  1065. export -f get_compose_service_def
  1066. _get_service_charm_cached () {
  1067. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1068. if [ -e "$cache_file" ]; then
  1069. # debug "$FUNCNAME: cache hit $1"
  1070. cat "$cache_file" &&
  1071. touch "$cache_file" || return 1
  1072. return 0
  1073. fi
  1074. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  1075. if [ -z "$charm" ]; then
  1076. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  1077. return 1
  1078. fi
  1079. echo "$charm" | tee "$cache_file" || return 1
  1080. }
  1081. export -f _get_service_charm_cached
  1082. get_service_charm () {
  1083. local service="$1"
  1084. if [ -z "$service" ]; then
  1085. echo ${FUNCNAME[@]} >&2
  1086. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  1087. return 1
  1088. fi
  1089. service_def=$(get_compose_service_def "$service") || return 1
  1090. _get_service_charm_cached "$service" "$service_def"
  1091. }
  1092. export -f get_service_charm
  1093. ## built above the docker-compose abstraction, so it relies on the
  1094. ## full docker-compose.yml to be already built.
  1095. get_service_def () {
  1096. local service="$1" def
  1097. if [ -z "$_current_docker_compose" ]; then
  1098. print_syntax_error "$FUNCNAME is meant to be called after"\
  1099. "\$_current_docker_compose has been calculated."
  1100. fi
  1101. def=$(echo "$_current_docker_compose" | shyaml get-value "services.${service//./\\.}" 2>/dev/null)
  1102. if [ -z "$def" ]; then
  1103. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  1104. return 1
  1105. fi
  1106. echo "$def"
  1107. }
  1108. export -f get_service_def
  1109. ## Return the base docker image name of a service
  1110. service_base_docker_image() {
  1111. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1112. master_service service_def service_image service_build service_dockerfile
  1113. if [ -e "$cache_file" ]; then
  1114. # debug "$FUNCNAME: cache hit ($*)"
  1115. cat "$cache_file"
  1116. return 0
  1117. fi
  1118. master_service="$(get_top_master_service_for_service "$service")" || {
  1119. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  1120. return 1
  1121. }
  1122. service_def="$(get_service_def "$master_service")" || {
  1123. err "Could not get docker-compose service definition for $DARKYELLOW$master_service$NORMAL."
  1124. return 1
  1125. }
  1126. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  1127. if [ "$?" != 0 ]; then
  1128. ## According to https://stackoverflow.com/questions/32230577 , if there's a build,
  1129. ## then the builded image will get name ${project}_${service}
  1130. project=$(get_default_project_name) || return 1
  1131. image_name="${project}_${service}"
  1132. if ! docker_has_image "$image_name"; then
  1133. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  1134. if [ "$?" != 0 ]; then
  1135. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  1136. echo "$service_def" >&2
  1137. return 1
  1138. fi
  1139. docker build "$service_build" -t "${project}_${service}" >&2 || {
  1140. err "Failed to build image for ${DARKYELLOW}$service${NORMAL}."
  1141. return 1
  1142. }
  1143. fi
  1144. printf "%s" "${project}_${service}"
  1145. else
  1146. printf "%s" "${service_image}"
  1147. fi | tee "$cache_file"
  1148. if [ "${PIPESTATUS[0]}" != 0 ]; then
  1149. rm "$cache_file"
  1150. return 1
  1151. fi
  1152. }
  1153. export -f service_base_docker_image
  1154. get_charm_relation_def () {
  1155. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1156. relation_def metadata
  1157. if [ -e "$cache_file" ]; then
  1158. # debug "$FUNCNAME: cache hit ($*)"
  1159. cat "$cache_file"
  1160. return 0
  1161. fi
  1162. metadata="$(charm.metadata "$charm")" || return 1
  1163. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  1164. echo "$relation_def" | tee "$cache_file"
  1165. }
  1166. export -f get_charm_relation_def
  1167. get_charm_tech_dep_orientation_for_relation() {
  1168. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1169. relation_def value
  1170. if [ -e "$cache_file" ]; then
  1171. # debug "$FUNCNAME: cache hit ($*)"
  1172. cat "$cache_file"
  1173. return 0
  1174. fi
  1175. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  1176. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1177. value=${value:-True}
  1178. printf "%s" "$value" | tee "$cache_file"
  1179. }
  1180. export -f get_charm_tech_dep_orientation_for_relation
  1181. get_service_relation_tech_dep() {
  1182. local service="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1183. charm tech_dep
  1184. if [ -e "$cache_file" ]; then
  1185. # debug "$FUNCNAME: cache hit ($*)"
  1186. cat "$cache_file"
  1187. return 0
  1188. fi
  1189. charm=$(get_service_charm "$service") || return 1
  1190. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$charm" "$relation_name")" || return 1
  1191. printf "%s" "$tech_dep" | tee "$cache_file"
  1192. }
  1193. export -f get_service_relation_tech_dep
  1194. ##
  1195. ## Use compose file to get deps, and relation definition in metadata.yml
  1196. ## for tech-dep attribute.
  1197. get_service_deps() {
  1198. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")"
  1199. if [ -e "$cache_file" ]; then
  1200. # debug "$FUNCNAME: cache hit ($*)"
  1201. cat "$cache_file"
  1202. return 0
  1203. fi
  1204. (
  1205. set -o pipefail
  1206. get_service_relations "$service" | \
  1207. while read-0 relation_name target_service _relation_config tech_dep; do
  1208. echo "$target_service"
  1209. done | tee "$cache_file"
  1210. ) || return 1
  1211. }
  1212. export -f get_service_deps
  1213. ## XXXvlab: cache was disabled because improper. Indeed, this needs to cache
  1214. ## 'depths' full state. Second, it should be
  1215. _rec_get_depth() {
  1216. local elt=$1 dep deps max
  1217. [ "${depths[$elt]}" ] && return 0
  1218. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$(declare -pA depths)" "$ALL_RELATIONS")"
  1219. if [ -e "$cache_file.depths" ]; then
  1220. #debug "$FUNCNAME: cache hit ($*) - $cache_file.depths"
  1221. while read-0 k v; do
  1222. depths["$k"]="$v"
  1223. done < "$cache_file.depths"
  1224. while read-0 k v; do
  1225. visited["$k"]="$v"
  1226. done < "$cache_file.visited"
  1227. return 0
  1228. fi
  1229. visited[$elt]=1
  1230. #debug "Setting visited[$elt]"
  1231. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1232. deps=$(get_service_deps "$elt") || {
  1233. debug "Failed get_service_deps $elt"
  1234. return 1
  1235. }
  1236. # debug "$elt deps are:" $deps
  1237. max=0
  1238. for dep in $deps; do
  1239. [ "${visited[$dep]}" ] && {
  1240. #debug "Already computing $dep"
  1241. continue
  1242. }
  1243. _rec_get_depth "$dep" || return 1
  1244. #debug "Requesting depth[$dep]"
  1245. if (( ${depths[$dep]} > max )); then
  1246. max="${depths[$dep]}"
  1247. fi
  1248. done
  1249. # debug "Setting depth[$elt] to $((max + 1))"
  1250. depths[$elt]=$((max + 1))
  1251. array_kv_to_stdin depths > "$cache_file.depths"
  1252. array_kv_to_stdin visited > "$cache_file.visited"
  1253. # debug "DEPTHS: $(declare -pA depths)"
  1254. # debug "$FUNCNAME: caching hit ($*) - $cache_file"
  1255. }
  1256. export -f _rec_get_depth
  1257. get_ordered_service_dependencies() {
  1258. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(H "$@" "$ALL_RELATIONS")" \
  1259. i value key heads depths visited
  1260. if [ -e "$cache_file" ]; then
  1261. # debug "$FUNCNAME: cache hit ($*)"
  1262. cat "$cache_file"
  1263. return 0
  1264. fi
  1265. #debug "Figuring ordered deps of $DARKYELLOW${services[@]}$NORMAL"
  1266. if [ -z "${services[*]}" ]; then
  1267. return 0
  1268. # print_syntax_error "$FUNCNAME: no arguments"
  1269. # return 1
  1270. fi
  1271. declare -A depths
  1272. declare -A visited
  1273. heads=("${services[@]}")
  1274. while [ "${#heads[@]}" != 0 ]; do
  1275. array_pop heads head
  1276. _rec_get_depth "$head" || return 1
  1277. done
  1278. i=0
  1279. while [ "${#depths[@]}" != 0 ]; do
  1280. for key in "${!depths[@]}"; do
  1281. value="${depths[$key]}"
  1282. if [ "$value" == "$i" ]; then
  1283. echo "$key"
  1284. unset depths[$key]
  1285. fi
  1286. done
  1287. ((i++))
  1288. done | tee "$cache_file"
  1289. }
  1290. export -f get_ordered_service_dependencies
  1291. run_service_hook () {
  1292. local action="$1" service subservice subservices loaded
  1293. shift
  1294. declare -A loaded
  1295. for service in "$@"; do
  1296. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1297. for subservice in $subservices; do
  1298. if [ "${loaded[$subservice]}" ]; then
  1299. ## Prevent double inclusion of same service if this
  1300. ## service is deps of two or more of your
  1301. ## requirements.
  1302. continue
  1303. fi
  1304. charm=$(get_service_charm "$subservice") || return 1
  1305. charm.has_hook "$charm" "$action" >/dev/null || continue
  1306. PROJECT_NAME=$(get_default_project_name) || return 1
  1307. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1308. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1309. DOCKER_BASE_IMAGE=$(service_base_docker_image "$MASTER_BASE_SERVICE_NAME") || return 1
  1310. Wrap "${wrap_opts[@]}" -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1311. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1312. export SERVICE_NAME=$subservice
  1313. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1314. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1315. export CHARM_NAME="$charm"
  1316. export PROJECT_NAME="$PROJECT_NAME"
  1317. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1318. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1319. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1320. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1321. charm.run_hook "local" "$charm" "$action"
  1322. EOF
  1323. loaded[$subservice]=1
  1324. done
  1325. done
  1326. return 0
  1327. }
  1328. host_resource_get() {
  1329. local location="$1" cfg="$2"
  1330. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1331. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1332. return 1
  1333. }
  1334. if fn.exists host_resource_get_$type; then
  1335. host_resource_get_$type "$location" "$cfg"
  1336. else
  1337. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1338. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1339. "$DARKYELLOW$subservice$NORMAL config."
  1340. return 1
  1341. fi
  1342. }
  1343. export -f host_resource_get
  1344. host_resource_get_git() {
  1345. local location="$1" cfg="$2" branch parent url
  1346. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1347. branch=${branch:-master}
  1348. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1349. parent="$(dirname "$location")"
  1350. (
  1351. mkdir -p "$parent" && cd "$parent" &&
  1352. git clone -b "$branch" "$url" "$(basename "$location")"
  1353. ) || return 1
  1354. }
  1355. export -f host_resource_get_git
  1356. host_resource_get_git-sub() {
  1357. local location="$1" cfg="$2" branch parent url
  1358. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1359. branch=${branch:-master}
  1360. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1361. parent="$(dirname "$location")"
  1362. (
  1363. mkdir -p "$parent" && cd "$parent" &&
  1364. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1365. ) || return 1
  1366. }
  1367. export -f host_resource_get_git-sub
  1368. setup_host_resource () {
  1369. local subservice="$1" service_def location get cfg
  1370. service_def=$(get_compose_service_def "$subservice") || return 1
  1371. while read-0 location cfg; do
  1372. ## XXXvlab: will it be a git resources always ?
  1373. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1374. err "Hum, location '$location' does not seem to be a git directory."
  1375. return 1
  1376. fi
  1377. if [ -d "$location" ]; then
  1378. info "host resource '$location' already set up."
  1379. continue
  1380. fi
  1381. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1382. if [ -z "$get" ]; then
  1383. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1384. "specified for $DARKYELLOW$subservice$NORMAL."
  1385. return 1
  1386. fi
  1387. host_resource_get "$location" "$get" || return 1
  1388. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1389. }
  1390. export -f setup_host_resource
  1391. setup_host_resources () {
  1392. local service subservices subservice loaded
  1393. declare -A loaded
  1394. for service in "$@"; do
  1395. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1396. for subservice in $subservices; do
  1397. if [ "${loaded[$subservice]}" ]; then
  1398. ## Prevent double inclusion of same service if this
  1399. ## service is deps of two or more of your
  1400. ## requirements.
  1401. continue
  1402. fi
  1403. setup_host_resource "$subservice" || return 1
  1404. loaded[$subservice]=1
  1405. done
  1406. done
  1407. return 0
  1408. }
  1409. export -f setup_host_resources
  1410. ## Works on stdin
  1411. cfg-get-value () {
  1412. local key="$1" out
  1413. if [ -z "$key" ]; then
  1414. yaml_get_interpret || return 1
  1415. return 0
  1416. fi
  1417. if ! out=$(shyaml -y get-value "$key" 2>/dev/null); then
  1418. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1419. return 1
  1420. fi
  1421. echo "$out" | yaml_get_interpret
  1422. }
  1423. export -f cfg-get-value
  1424. relation-get () {
  1425. cfg-get-value "$1" < "$RELATION_DATA_FILE"
  1426. }
  1427. export -f relation-get
  1428. expand_vars() {
  1429. local unlikely_prefix="UNLIKELY_PREFIX"
  1430. content=$(cat -)
  1431. ## find first identifier not in content
  1432. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1433. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1434. size_prefix="${#unlikely_prefix}"
  1435. first_matching=$(echo "$remaining_lines" |
  1436. grep -v "^$unlikely_prefix$" |
  1437. uniq -w "$((size_prefix + 1))" -c |
  1438. sort -rn |
  1439. head -n 1)
  1440. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1441. first_matching="${first_matching#* }"
  1442. next_char=${first_matching:$size_prefix:1}
  1443. if [ "$next_char" != "0" ]; then
  1444. unlikely_prefix+="0"
  1445. else
  1446. unlikely_prefix+="1"
  1447. fi
  1448. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1449. done
  1450. eval "cat <<$unlikely_prefix
  1451. $content
  1452. $unlikely_prefix"
  1453. }
  1454. export -f expand_vars
  1455. yaml_get_interpret() {
  1456. local content tag
  1457. content=$(cat -)
  1458. tag=$(echo "$content" | shyaml -y get-value) || return 1
  1459. tag="${tag%% *}"
  1460. content=$(echo "$content" | shyaml get-value) || return 1
  1461. if ! [ "${tag:0:1}" == "!" ]; then
  1462. echo "$content" || return 1
  1463. return 0
  1464. fi
  1465. case "$tag" in
  1466. "!bash-stdout")
  1467. echo "$content" | bash || {
  1468. err "shell code didn't end with errorlevel 0"
  1469. return 1
  1470. }
  1471. ;;
  1472. "!var-expand")
  1473. echo "$content" | expand_vars || {
  1474. err "shell expansion failed"
  1475. return 1
  1476. }
  1477. ;;
  1478. *)
  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"|"summon")
  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. if [ "$auto" == "summon" ]; then
  2070. summon+=("$service" "$relation_name" "$relation_def")
  2071. fi
  2072. fi
  2073. ;;
  2074. ""|null|disable|disabled)
  2075. :
  2076. ;;
  2077. *)
  2078. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2079. return 1
  2080. ;;
  2081. esac
  2082. constraint=$(echo "$relation_def" | shyaml get-value constraint auto-pair 2>/dev/null)
  2083. case "$constraint" in
  2084. "required")
  2085. required+=("$service" "$relation_name" "$relation_def")
  2086. ;;
  2087. "recommended")
  2088. recommended+=("$service" "$relation_name" "$relation_def")
  2089. ;;
  2090. "optional")
  2091. optional+=("$service" "$relation_name" "$relation_def")
  2092. ;;
  2093. *)
  2094. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2095. return 1
  2096. ;;
  2097. esac
  2098. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2099. done
  2100. services_uses=("${new_services_uses[@]}")
  2101. if [ "$changed" ]; then
  2102. continue
  2103. fi
  2104. ## situation is stable
  2105. if [ "${#summon[@]}" != 0 ]; then
  2106. while [ "${#summon[@]}" != 0 ]; do
  2107. service="${summon[0]}"
  2108. relation_name="${summon[1]}"
  2109. relation_def="${summon[2]}"
  2110. summon=("${summon[@]:3}")
  2111. providers=()
  2112. providers_def=()
  2113. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2114. if [ "${#providers[@]}" == 0 ]; then
  2115. die "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2116. fi
  2117. if [ "${#providers[@]}" -gt 1 ]; then
  2118. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2119. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2120. "(> 1 provider). Choosing first."
  2121. fi
  2122. ts="${providers[0]}"
  2123. ## YYYvlab: should be seen even in no debug mode no ?
  2124. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2125. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2126. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2127. "${providers_def[0]}" "$relation_def" \
  2128. >> "${cache_file}.wip"
  2129. ## Adding service
  2130. [ "${services[$ts]}" ] && continue
  2131. array_read-0 services_uses < <(_get_services_uses "$ts")
  2132. services[$ts]=1
  2133. changed=1
  2134. done
  2135. continue
  2136. fi
  2137. [ "$NO_CONSTRAINT_CHECK" ] && break
  2138. if [ "${#required[@]}" != 0 ]; then
  2139. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2140. err "Required relations not satisfied"
  2141. return 1
  2142. fi
  2143. if [ "${#recommended[@]}" != 0 ]; then
  2144. ## make recommendation
  2145. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2146. fi
  2147. if [ "${#optional[@]}" != 0 ]; then
  2148. ## inform about options
  2149. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2150. fi
  2151. # if [ "${#required[@]}" != 0 ]; then
  2152. # err "Required relations not satisfied"
  2153. # return 1
  2154. # fi
  2155. if [ "${#recommended[@]}" != 0 ]; then
  2156. warn "Recommended relations not satisfied"
  2157. fi
  2158. break
  2159. done
  2160. if [ "$?" != 0 ]; then
  2161. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2162. return 1
  2163. fi
  2164. export ALL_RELATIONS="$cache_file"
  2165. mv "${cache_file}"{.wip,}
  2166. cat "$cache_file"
  2167. }
  2168. export -f get_all_relations
  2169. _display_solves() {
  2170. local array_name="$1" by_relation msg
  2171. ## inform about options
  2172. msg=""
  2173. declare -A by_relation
  2174. while read-0 service relation_name relation_def; do
  2175. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2176. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2177. if [ -z "$solves" ]; then
  2178. continue
  2179. fi
  2180. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2181. if [ "$auto" == "pair" ]; then
  2182. requirement="add provider in cluster to auto-pair"
  2183. else
  2184. requirement="add explicit relation"
  2185. fi
  2186. while read-0 name def; do
  2187. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2188. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2189. done < <(array_values_to_stdin "$array_name")
  2190. while read-0 relation_name message; do
  2191. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2192. "$relation_name" "$message" )"
  2193. done < <(array_kv_to_stdin by_relation)
  2194. if [ "$msg" ]; then
  2195. printf "%s\n" "${msg:1}"
  2196. fi
  2197. }
  2198. get_compose_relation_def() {
  2199. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2200. while read-0 relation_name target_service relation_config tech_dep; do
  2201. [ "$relation_name" == "$relation" ] || continue
  2202. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2203. done < <(get_compose_relations "$service") || return 1
  2204. }
  2205. export -f get_compose_relation_def
  2206. run_service_relations () {
  2207. local service services loaded subservices subservice
  2208. PROJECT_NAME=$(get_default_project_name) || return 1
  2209. export PROJECT_NAME
  2210. declare -A loaded
  2211. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2212. for service in $subservices; do
  2213. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2214. for subservice in $(get_service_deps "$service") "$service"; do
  2215. [ "${loaded[$subservice]}" ] && continue
  2216. export BASE_SERVICE_NAME=$service
  2217. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2218. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2219. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2220. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2221. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2222. while read-0 relation_name target_service relation_config tech_dep; do
  2223. export relation_config
  2224. export TARGET_SERVICE_NAME=$target_service
  2225. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2226. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2227. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2228. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2229. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2230. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2231. EOF
  2232. done < <(get_service_relations "$subservice") || return 1
  2233. loaded[$subservice]=1
  2234. done
  2235. done
  2236. }
  2237. export -f run_service_relations
  2238. _run_service_action_direct() {
  2239. local service="$1" action="$2" charm _dummy
  2240. shift; shift
  2241. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  2242. if read-0 _dummy || [ "$_dummy" ]; then
  2243. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2244. return 1
  2245. fi
  2246. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2247. export state_tmpdir
  2248. (
  2249. set +e ## Prevents unwanted leaks from parent shell
  2250. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2251. export METADATA_CONFIG=$(charm.metadata "$charm")
  2252. export SERVICE_NAME=$service
  2253. export ACTION_NAME=$action
  2254. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2255. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2256. export SERVICE_DATASTORE="$DATASTORE/$service"
  2257. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2258. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2259. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2260. )
  2261. }
  2262. export -f _run_service_action_direct
  2263. _run_service_action_relation() {
  2264. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2265. shift; shift
  2266. read-0 charm target_service target_charm relation_name relation_config || true
  2267. if read-0 _dummy || [ "$_dummy" ]; then
  2268. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2269. return 1
  2270. fi
  2271. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  2272. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2273. export state_tmpdir
  2274. {
  2275. (
  2276. set +e ## Prevents unwanted leaks from parent shell
  2277. export METADATA_CONFIG=$(charm.metadata "$charm")
  2278. export SERVICE_NAME=$service
  2279. export RELATION_TARGET_SERVICE="$target_service"
  2280. export RELATION_TARGET_CHARM="$target_charm"
  2281. export RELATION_BASE_SERVICE="$service"
  2282. export RELATION_BASE_CHARM="$charm"
  2283. export ACTION_NAME=$action
  2284. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2285. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2286. export SERVICE_DATASTORE="$DATASTORE/$service"
  2287. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2288. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2289. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2290. echo "$?" > "$action_errlvl_file"
  2291. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2292. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2293. if ! [ -e "$action_errlvl_file" ]; then
  2294. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2295. "to output an errlvl"
  2296. return 1
  2297. fi
  2298. return "$(cat "$action_errlvl_file")"
  2299. }
  2300. export -f _run_service_action_relation
  2301. get_relation_data_dir() {
  2302. local service="$1" target_service="$2" relation_name="$3" \
  2303. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2304. if [ -e "$cache_file" ]; then
  2305. # debug "$FUNCNAME: cache hit ($*)"
  2306. cat "$cache_file"
  2307. return 0
  2308. fi
  2309. project=$(get_default_project_name) || return 1
  2310. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2311. if ! [ -d "$relation_dir" ]; then
  2312. mkdir -p "$relation_dir" || return 1
  2313. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2314. fi
  2315. echo "$relation_dir" | tee "$cache_file"
  2316. }
  2317. export -f get_relation_data_dir
  2318. get_relation_data_file() {
  2319. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2320. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2321. relation_data_file="$relation_dir/data"
  2322. new=
  2323. if [ -e "$relation_data_file" ]; then
  2324. ## Has reference changed ?
  2325. new_md5=$(echo "$relation_config" | md5_compat)
  2326. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2327. new=true
  2328. fi
  2329. else
  2330. new=true
  2331. fi
  2332. if [ "$new" ]; then
  2333. echo "$relation_config" > "$relation_data_file"
  2334. chmod go-rwx "$relation_data_file" ## protecting this file
  2335. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2336. fi
  2337. echo "$relation_data_file"
  2338. }
  2339. export -f get_relation_data_file
  2340. has_service_action () {
  2341. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2342. charm target_charm relation_name target_service relation_config _tech_dep
  2343. if [ -e "$cache_file" ]; then
  2344. # debug "$FUNCNAME: cache hit ($*)"
  2345. cat "$cache_file"
  2346. return 0
  2347. fi
  2348. charm=$(get_service_charm "$service") || return 1
  2349. ## Action directly provided ?
  2350. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  2351. echo -en "direct\0$charm" | tee "$cache_file"
  2352. return 0
  2353. fi
  2354. ## Action provided by relation ?
  2355. while read-0 relation_name target_service relation_config _tech_dep; do
  2356. target_charm=$(get_service_charm "$target_service") || return 1
  2357. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  2358. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  2359. return 0
  2360. fi
  2361. done < <(get_service_relations "$service")
  2362. return 1
  2363. # master=$(get_top_master_service_for_service "$service")
  2364. # [ "$master" == "$charm" ] && return 1
  2365. # has_service_action "$master" "$action"
  2366. }
  2367. export -f has_service_action
  2368. run_service_action () {
  2369. local service="$1" action="$2"
  2370. shift ; shift
  2371. {
  2372. if ! read-0 action_type; then
  2373. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2374. info " Add an executable script to 'actions/$action' to implement action."
  2375. return 1
  2376. fi
  2377. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2378. } < <(has_service_action "$service" "$action")
  2379. }
  2380. export -f run_service_action
  2381. get_compose_relation_config() {
  2382. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2383. if [ -e "$cache_file" ]; then
  2384. # debug "$FUNCNAME: cache hit ($*)"
  2385. cat "$cache_file"
  2386. return 0
  2387. fi
  2388. compose_service_def=$(get_compose_service_def "$service") || return 1
  2389. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2390. }
  2391. export -f get_compose_relation_config
  2392. # ## Return key-values-0
  2393. # get_compose_relation_config_for_service() {
  2394. # local service=$1 relation_name=$2 relation_config
  2395. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2396. # if ! relation_config=$(
  2397. # echo "$compose_service_relations" |
  2398. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2399. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2400. # "relation config in compose configuration."
  2401. # return 1
  2402. # fi
  2403. # if [ -z "$relation_config" ]; then
  2404. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2405. # return 1
  2406. # fi
  2407. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2408. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2409. # return 1
  2410. # fi
  2411. # }
  2412. # export -f get_compose_relation_config_for_service
  2413. _get_container_relation() {
  2414. local metadata=$1 found relation_name relation_def
  2415. found=
  2416. while read-0 relation_name relation_def; do
  2417. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2418. found="$relation_name"
  2419. break
  2420. }
  2421. done < <(_get_charm_metadata_uses "$metadata")
  2422. if [ -z "$found" ]; then
  2423. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2424. "${WHITE}scope${NORMAL} set to 'container'."
  2425. fi
  2426. printf "%s" "$found"
  2427. }
  2428. _get_master_service_for_service_cached () {
  2429. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2430. charm requires master_charm target_charm target_service service_def found
  2431. if [ -e "$cache_file" ]; then
  2432. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2433. cat "$cache_file" &&
  2434. touch "$cache_file" || return 1
  2435. return 0
  2436. fi
  2437. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2438. ## just return service name
  2439. echo "$service" | tee "$cache_file"
  2440. return 0
  2441. fi
  2442. ## Action provided by relation ?
  2443. container_relation=$(_get_container_relation "$metadata")
  2444. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2445. if [ -z "$target_service" ]; then
  2446. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2447. "${DARKYELLOW}$service$NORMAL compose definition."
  2448. err ${FUNCNAME[@]}
  2449. return 1
  2450. fi
  2451. echo "$target_service" | tee "$cache_file"
  2452. }
  2453. export -f _get_master_service_for_service_cached
  2454. get_master_service_for_service() {
  2455. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2456. charm metadata result
  2457. if [ -e "$cache_file" ]; then
  2458. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2459. cat "$cache_file" || return 1
  2460. return 0
  2461. fi
  2462. charm=$(get_service_charm "$service") || return 1
  2463. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2464. metadata=""
  2465. warn "No charm $DARKPINK$charm$NORMAL found."
  2466. }
  2467. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2468. echo "$result" | tee "$cache_file" || return 1
  2469. }
  2470. export -f get_master_service_for_service
  2471. get_top_master_service_for_service() {
  2472. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2473. current_service
  2474. if [ -e "$cache_file" ]; then
  2475. # debug "$FUNCNAME: cache hit ($*)"
  2476. cat "$cache_file"
  2477. return 0
  2478. fi
  2479. current_service="$service"
  2480. while true; do
  2481. master_service=$(get_master_service_for_service "$current_service") || return 1
  2482. [ "$master_service" == "$current_service" ] && break
  2483. current_service="$master_service"
  2484. done
  2485. echo "$current_service" | tee "$cache_file"
  2486. return 0
  2487. }
  2488. export -f get_top_master_service_for_service
  2489. ##
  2490. ## The result is a mixin that is not always a complete valid
  2491. ## docker-compose entry (thinking of subordinates). The result
  2492. ## will be merge with master charms.
  2493. _get_docker_compose_mixin_from_metadata_cached() {
  2494. local service="$1" charm="$2" metadata="$3" \
  2495. has_build_dir="$4" \
  2496. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2497. metadata_file metadata volumes docker_compose subordinate image mixin mixins
  2498. if [ -e "$cache_file" ]; then
  2499. #debug "$FUNCNAME: STATIC cache hit $1"
  2500. cat "$cache_file" &&
  2501. touch "$cache_file" || return 1
  2502. return 0
  2503. fi
  2504. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2505. if [ "$metadata" ]; then
  2506. ## resources to volumes
  2507. volumes=$(
  2508. for resource_type in data config; do
  2509. while read-0 resource; do
  2510. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2511. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2512. done
  2513. while read-0 resource; do
  2514. if [[ "$resource" == /*:/*:* ]]; then
  2515. echo " - $resource"
  2516. elif [[ "$resource" == /*:/* ]]; then
  2517. echo " - $resource:rw"
  2518. elif [[ "$resource" == /*:* ]]; then
  2519. echo " - ${resource%%:*}:$resource"
  2520. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2521. echo " - $resource:$resource:rw"
  2522. else
  2523. die "Invalid host-resource specified in 'metadata.yml'."
  2524. fi
  2525. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2526. while read-0 resource; do
  2527. dest="$(charm.get_dir "$charm")/resources$resource"
  2528. if ! [ -e "$dest" ]; then
  2529. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2530. fi
  2531. echo " - $dest:$resource:ro"
  2532. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2533. ) || return 1
  2534. if [ "$volumes" ]; then
  2535. mixins+=("volumes:"$'\n'"$volumes")
  2536. fi
  2537. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2538. if [ "$type" != "run-once" ]; then
  2539. mixins+=("restart: unless-stopped")
  2540. fi
  2541. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2542. if [ "$docker_compose" ]; then
  2543. mixins+=("$docker_compose")
  2544. fi
  2545. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2546. subordinate=true
  2547. fi
  2548. fi
  2549. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2550. [ "$image" == "None" ] && image=""
  2551. if [ "$image" ]; then
  2552. if [ "$subordinate" ]; then
  2553. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2554. return 1
  2555. fi
  2556. mixins+=("image: $image")
  2557. elif [ "$has_build_dir" ]; then
  2558. if [ "$subordinate" ]; then
  2559. err "Subordinate charm can not have a 'build' sub directory."
  2560. return 1
  2561. fi
  2562. mixins+=("build: $(charm.get_dir "$charm")/build")
  2563. fi
  2564. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2565. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2566. return 1
  2567. }
  2568. echo "$mixin" | tee "$cache_file"
  2569. }
  2570. export -f _get_docker_compose_mixin_from_metadata_cached
  2571. get_docker_compose_mixin_from_metadata() {
  2572. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2573. if [ -e "$cache_file" ]; then
  2574. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2575. cat "$cache_file"
  2576. return 0
  2577. fi
  2578. charm=$(get_service_charm "$service") || return 1
  2579. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2580. has_build_dir=
  2581. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2582. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2583. echo "$mixin" | tee "$cache_file"
  2584. }
  2585. export -f get_docker_compose_mixin_from_metadata
  2586. _save() {
  2587. local name="$1"
  2588. cat - | tee -a "$docker_compose_dir/.data/$name"
  2589. }
  2590. export -f _save
  2591. get_default_project_name() {
  2592. if [ "$DEFAULT_PROJECT_NAME" ]; then
  2593. echo "$DEFAULT_PROJECT_NAME"
  2594. return 0
  2595. fi
  2596. compose_yml_location="$(get_compose_yml_location)" || return 1
  2597. if [ "$compose_yml_location" ]; then
  2598. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2599. name="$(basename "$(dirname "$normalized_path")")"
  2600. echo "${name%%-deploy}"
  2601. return 0
  2602. fi
  2603. fi
  2604. echo "orphan"
  2605. return 0
  2606. }
  2607. export -f get_default_project_name
  2608. get_running_compose_containers() {
  2609. ## XXXvlab: docker bug: there will be a final newline anyway
  2610. docker ps --filter label="compose.service" --format='{{.ID}}'
  2611. }
  2612. export -f get_running_compose_containers
  2613. get_volumes_for_container() {
  2614. local container="$1"
  2615. docker inspect \
  2616. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2617. "$container"
  2618. }
  2619. export -f get_volumes_for_container
  2620. is_volume_used() {
  2621. local volume="$1" container_id src dst
  2622. while read -r container_id; do
  2623. while read-0 src dst; do
  2624. [[ "$src/" == "$volume"/* ]] && return 0
  2625. done < <(get_volumes_for_container "$container_id")
  2626. done < <(get_running_compose_containers)
  2627. return 1
  2628. }
  2629. export -f is_volume_used
  2630. clean_unused_docker_compose() {
  2631. for f in /var/lib/compose/docker-compose/*; do
  2632. [ -e "$f" ] || continue
  2633. is_volume_used "$f" && continue
  2634. debug "Cleaning unused docker-compose ${f##*/}"
  2635. rm -rf "$f" || return 1
  2636. done
  2637. return 0
  2638. }
  2639. export -f clean_unused_docker_compose
  2640. stdin_get_hash() {
  2641. local sha
  2642. sha=$(sha256sum) || return 1
  2643. sha=${sha:0:64}
  2644. echo "$sha"
  2645. }
  2646. export -f stdin_get_hash
  2647. file_get_hash() {
  2648. stdin_get_hash < "$1" || return 1
  2649. }
  2650. export -f file_get_hash
  2651. docker_compose_store() {
  2652. local file="$1" sha
  2653. sha=$(file_get_hash "$file") || return 1
  2654. project=$(get_default_project_name) || return 1
  2655. dst="/var/lib/compose/docker-compose/$sha/$project"
  2656. mkdir -p "$dst" || return 1
  2657. cat <<EOF > "$dst/.env" || return 1
  2658. DOCKER_COMPOSE_PATH=$dst
  2659. EOF
  2660. cp "$file" "$dst/docker-compose.yml" || return 1
  2661. mkdir -p "$dst/bin" || return 1
  2662. cat <<EOF > "$dst/bin/dc" || return 1
  2663. #!/bin/bash
  2664. $(declare -f read-0)
  2665. docker_run_opts=()
  2666. while read-0 opt; do
  2667. docker_run_opts+=("\$opt")
  2668. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2669. docker_run_opts+=(
  2670. "-w" "$dst"
  2671. "--entrypoint" "/usr/local/bin/docker-compose"
  2672. )
  2673. [ -t 1 ] && {
  2674. docker_run_opts+=("-ti")
  2675. }
  2676. exec docker run --rm "\${docker_run_opts[@]}" "${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2677. EOF
  2678. chmod +x "$dst/bin/dc" || return 1
  2679. printf "%s" "$sha"
  2680. }
  2681. launch_docker_compose() {
  2682. local charm docker_compose_tmpdir docker_compose_dir
  2683. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2684. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2685. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2686. ## docker-compose will name network from the parent dir name
  2687. project=$(get_default_project_name)
  2688. mkdir -p "$docker_compose_tmpdir/$project"
  2689. docker_compose_dir="$docker_compose_tmpdir/$project"
  2690. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2691. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2692. # debug "Merging some config data in docker-compose.yml:"
  2693. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2694. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2695. fi
  2696. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2697. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2698. fi
  2699. ## XXXvlab: could be more specific and only link the needed charms
  2700. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2701. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2702. # if charm.exists "$charm"; then
  2703. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2704. # fi
  2705. # done
  2706. mkdir "$docker_compose_dir/.data"
  2707. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2708. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2709. fi
  2710. {
  2711. {
  2712. {
  2713. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2714. cd "/var/lib/compose/docker-compose/$sha/$project"
  2715. else
  2716. cd "$docker_compose_dir"
  2717. fi
  2718. if [ -f ".env" ]; then
  2719. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2720. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2721. fi
  2722. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2723. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2724. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2725. if [ "$DRY_COMPOSE_RUN" ]; then
  2726. echo docker-compose "$@"
  2727. else
  2728. docker-compose "$@"
  2729. fi
  2730. echo "$?" > "$docker_compose_dir/.data/errlvl"
  2731. } | _save stdout
  2732. } 3>&1 1>&2 2>&3 | _save stderr
  2733. } 3>&1 1>&2 2>&3
  2734. 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
  2735. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  2736. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  2737. fi
  2738. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  2739. if [ -z "$docker_compose_errlvl" ]; then
  2740. err "Something went wrong before you could gather docker-compose errorlevel."
  2741. return 1
  2742. fi
  2743. return "$docker_compose_errlvl"
  2744. }
  2745. export -f launch_docker_compose
  2746. get_compose_yml_location() {
  2747. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  2748. echo "$COMPOSE_YML_FILE"
  2749. return 0
  2750. fi
  2751. parent=$(while ! [ -f "./compose.yml" ]; do
  2752. [ "$PWD" == "/" ] && exit 0
  2753. cd ..
  2754. done; echo "$PWD"
  2755. )
  2756. if [ "$parent" ]; then
  2757. echo "$parent/compose.yml"
  2758. return 0
  2759. fi
  2760. ## XXXvlab: do we need this additional environment variable,
  2761. ## COMPOSE_YML_FILE is not sufficient ?
  2762. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  2763. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  2764. warn "No 'compose.yml' was found in current or parent dirs," \
  2765. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  2766. "(${DEFAULT_COMPOSE_FILE})"
  2767. return 0
  2768. fi
  2769. echo "$DEFAULT_COMPOSE_FILE"
  2770. return 0
  2771. fi
  2772. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  2773. return 0
  2774. }
  2775. export -f get_compose_yml_location
  2776. get_compose_yml_content() {
  2777. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  2778. if [ -e "$cache_file" ]; then
  2779. cat "$cache_file" &&
  2780. touch "$cache_file" || return 1
  2781. return 0
  2782. fi
  2783. if [ -z "$COMPOSE_YML_FILE" ]; then
  2784. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2785. fi
  2786. if [ -e "$COMPOSE_YML_FILE" ]; then
  2787. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2788. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  2789. err "Could not read '$COMPOSE_YML_FILE'."
  2790. return 1
  2791. }
  2792. else
  2793. debug "No compose file found. Using an empty one."
  2794. COMPOSE_YML_CONTENT=""
  2795. fi
  2796. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  2797. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  2798. if [ "$?" != 0 ]; then
  2799. outputed_something=
  2800. while IFS='' read -r line1 && IFS='' read -r line2; do
  2801. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2802. outputed_something=true
  2803. echo "$line1 $GRAY($line2)$NORMAL"
  2804. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2805. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2806. prefix " $GRAY|$NORMAL "
  2807. [ "$outputed_something" ] || {
  2808. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2809. echo "$output" | prefix " $GRAY|$NORMAL "
  2810. }
  2811. return 1
  2812. fi
  2813. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  2814. }
  2815. export -f get_compose_yml_content
  2816. get_default_target_services() {
  2817. local services=("$@")
  2818. if [ -z "${services[*]}" ]; then
  2819. if [ "$DEFAULT_SERVICES" ]; then
  2820. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  2821. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  2822. services="$DEFAULT_SERVICES"
  2823. else
  2824. err "No service provided."
  2825. return 1
  2826. fi
  2827. fi
  2828. echo "${services[*]}"
  2829. }
  2830. export -f get_default_target_services
  2831. get_master_services() {
  2832. local loaded master_service service
  2833. declare -A loaded
  2834. for service in "$@"; do
  2835. master_service=$(get_top_master_service_for_service "$service") || return 1
  2836. if [ "${loaded[$master_service]}" ]; then
  2837. continue
  2838. fi
  2839. echo "$master_service"
  2840. loaded["$master_service"]=1
  2841. done | nspc
  2842. return "${PIPESTATUS[0]}"
  2843. }
  2844. export -f get_master_services
  2845. get_current_docker_container_id() {
  2846. local line
  2847. line=$(cat "/proc/self/cpuset") || return 1
  2848. [[ "$line" == *docker* ]] || return 1
  2849. echo "${line##*/}"
  2850. }
  2851. export -f get_current_docker_container_id
  2852. ## if we are in a docker compose, we might want to know what is the
  2853. ## real host path of some local paths.
  2854. get_host_path() {
  2855. local path="$1"
  2856. path=$(realpath "$path") || return 1
  2857. container_id=$(get_current_docker_container_id) || {
  2858. print "%s" "$path"
  2859. return 0
  2860. }
  2861. biggest_dst=
  2862. current_src=
  2863. while read-0 src dst; do
  2864. [[ "$path" == "$dst"* ]] || continue
  2865. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  2866. biggest_dst="$dst"
  2867. current_src="$src"
  2868. fi
  2869. done < <(get_volumes_for_container "$container_id")
  2870. if [ "$current_src" ]; then
  2871. printf "%s" "$current_src"
  2872. else
  2873. return 1
  2874. fi
  2875. }
  2876. export -f get_host_path
  2877. _setup_state_dir() {
  2878. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2879. #debug "Creating temporary state directory in '$state_tmpdir'."
  2880. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  2881. # rm -rf \"$state_tmpdir\""
  2882. trap_add EXIT "rm -rf \"$state_tmpdir\""
  2883. }
  2884. get_docker_compose_help_msg() {
  2885. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2886. docker_compose_help_msg
  2887. if [ -e "$cache_file" ]; then
  2888. cat "$cache_file" &&
  2889. touch "$cache_file" || return 1
  2890. return 0
  2891. fi
  2892. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  2893. echo "$docker_compose_help_msg" |
  2894. tee "$cache_file" || return 1
  2895. }
  2896. get_docker_compose_usage() {
  2897. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2898. docker_compose_help_msg
  2899. if [ -e "$cache_file" ]; then
  2900. cat "$cache_file" &&
  2901. touch "$cache_file" || return 1
  2902. return 0
  2903. fi
  2904. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  2905. echo "$docker_compose_help_msg" |
  2906. grep -m 1 "^Usage:" -A 10000 |
  2907. egrep -m 1 "^\$" -B 10000 |
  2908. nspc |
  2909. sed -r 's/^Usage: //g' |
  2910. tee "$cache_file" || return 1
  2911. }
  2912. get_docker_compose_opts_help() {
  2913. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2914. docker_compose_help_msg
  2915. if [ -e "$cache_file" ]; then
  2916. cat "$cache_file" &&
  2917. touch "$cache_file" || return 1
  2918. return 0
  2919. fi
  2920. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2921. echo "$docker_compose_opts_help" |
  2922. grep '^Options:' -A 20000 |
  2923. tail -n +2 |
  2924. { cat ; echo; } |
  2925. egrep -m 1 "^\S*\$" -B 10000 |
  2926. head -n -1 |
  2927. tee "$cache_file" || return 1
  2928. }
  2929. get_docker_compose_commands_help() {
  2930. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2931. docker_compose_help_msg
  2932. if [ -e "$cache_file" ]; then
  2933. cat "$cache_file" &&
  2934. touch "$cache_file" || return 1
  2935. return 0
  2936. fi
  2937. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2938. echo "$docker_compose_opts_help" |
  2939. grep '^Commands:' -A 20000 |
  2940. tail -n +2 |
  2941. { cat ; echo; } |
  2942. egrep -m 1 "^\S*\$" -B 10000 |
  2943. head -n -1 |
  2944. tee "$cache_file" || return 1
  2945. }
  2946. get_docker_compose_opts_list() {
  2947. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2948. docker_compose_help_msg
  2949. if [ -e "$cache_file" ]; then
  2950. cat "$cache_file" &&
  2951. touch "$cache_file" || return 1
  2952. return 0
  2953. fi
  2954. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2955. echo "$docker_compose_opts_help" |
  2956. egrep "^\s+-" |
  2957. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2958. tee "$cache_file" || return 1
  2959. }
  2960. options_parser() {
  2961. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2962. printf "\0"
  2963. }
  2964. remove_options_in_option_help_msg() {
  2965. {
  2966. read-0 null
  2967. if [ "$null" ]; then
  2968. err "options parsing error, should start with an option line."
  2969. return 1
  2970. fi
  2971. while read-0 opt full_txt;do
  2972. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2973. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2974. for to_remove in "$@"; do
  2975. str_matches "$to_remove" $multi_opts $single_opts && {
  2976. continue 2
  2977. }
  2978. done
  2979. echo -n "$full_txt"
  2980. done
  2981. } < <(options_parser)
  2982. }
  2983. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2984. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2985. multi_opts_filter() {
  2986. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2987. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2988. tr ',' "\n" | nspc
  2989. }
  2990. single_opts_filter() {
  2991. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2992. tr ',' "\n" | nspc
  2993. }
  2994. get_docker_compose_multi_opts_list() {
  2995. local action="$1" opts_list
  2996. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2997. echo "$opts_list" | multi_opts_filter
  2998. }
  2999. get_docker_compose_single_opts_list() {
  3000. local action="$1" opts_list
  3001. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3002. echo "$opts_list" | single_opts_filter
  3003. }
  3004. display_commands_help() {
  3005. local charm_actions
  3006. echo
  3007. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3008. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3009. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3010. if [ "$charm_actions_help" ]; then
  3011. echo
  3012. echo "${WHITE}Charm actions${NORMAL}:"
  3013. printf "%s\n" "$charm_actions_help" | \
  3014. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3015. fi
  3016. }
  3017. get_docker_charm_action_help() {
  3018. local services service charm relation_name target_service relation_config \
  3019. target_charm
  3020. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3021. for service in "${services[@]}"; do
  3022. out=$(
  3023. charm=$(get_service_charm "$service") || return 1
  3024. for action in $(charm.ls_direct_actions "$charm"); do
  3025. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3026. done
  3027. while read-0 relation_name target_service _relation_config _tech_dep; do
  3028. target_charm=$(get_service_charm "$target_service") || return 1
  3029. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3030. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3031. done
  3032. done < <(get_compose_relations "$service")
  3033. )
  3034. if [ "$out" ]; then
  3035. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3036. printf "%s\n" "$out"
  3037. fi
  3038. done
  3039. }
  3040. display_help() {
  3041. print_help
  3042. echo "${WHITE}Options${NORMAL}:"
  3043. echo " -h, --help Print this message and quit"
  3044. echo " (ignoring any other options)"
  3045. echo " -V, --version Print current version and quit"
  3046. echo " (ignoring any other options)"
  3047. echo " --dirs Display data dirs and quit"
  3048. echo " (ignoring any other options)"
  3049. echo " -v, --verbose Be more verbose"
  3050. echo " -q, --quiet Be quiet"
  3051. echo " -d, --debug Print full debugging information (sets also verbose)"
  3052. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3053. echo " command line will be used."
  3054. echo " --rebuild-relations-to-service, -R SERVICE"
  3055. echo " Will rebuild all relations to given service"
  3056. echo " --add-compose-content, -Y YAML"
  3057. echo " Will merge some direct YAML with the current compose"
  3058. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3059. filter_docker_compose_help_message
  3060. display_commands_help
  3061. }
  3062. _graph_service() {
  3063. local service="$1" base="$1"
  3064. charm=$(get_service_charm "$service") || return 1
  3065. metadata=$(charm.metadata "$charm") || return 1
  3066. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3067. if [ "$subordinate" == "True" ]; then
  3068. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3069. master_charm=
  3070. while read-0 relation_name relation; do
  3071. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3072. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3073. if [ -z "$interface" ]; then
  3074. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3075. return 1
  3076. fi
  3077. ## Action provided by relation ?
  3078. target_service=
  3079. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3080. [ "$interface" == "$relation_name" ] && {
  3081. target_service="$candidate_target_service"
  3082. break
  3083. }
  3084. done < <(get_service_relations "$service")
  3085. if [ -z "$target_service" ]; then
  3086. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3087. "${DARKYELLOW}$service$NORMAL compose definition."
  3088. return 1
  3089. fi
  3090. master_service="$target_service"
  3091. master_charm=$(get_service_charm "$target_service") || return 1
  3092. break
  3093. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3094. fi
  3095. _graph_node_service "$service" "$base" "$charm"
  3096. _graph_edge_service "$service" "$subordinate" "$master_service"
  3097. }
  3098. _graph_node_service() {
  3099. local service="$1" base="$2" charm="$3"
  3100. cat <<EOF
  3101. "$(_graph_node_service_label ${service})" [
  3102. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  3103. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  3104. color = $([ "$base" ] && echo "blue" || echo "black")
  3105. fillcolor = "white"
  3106. fontname = "Courier New"
  3107. shape = "Mrecord"
  3108. label =<$(_graph_node_service_content "$service")>
  3109. ];
  3110. EOF
  3111. }
  3112. _graph_edge_service() {
  3113. local service="$1" subordinate="$2" master_service="$3"
  3114. while read-0 relation_name target_service relation_config tech_dep; do
  3115. cat <<EOF
  3116. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3117. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3118. fontsize = 16
  3119. fontcolor = "black"
  3120. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3121. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3122. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3123. arrowtail = odot
  3124. # arrowhead = dotlicurve
  3125. taillabel = "$relation_name" ];
  3126. EOF
  3127. done < <(get_service_relations "$service") || return 1
  3128. }
  3129. _graph_node_service_label() {
  3130. local service="$1"
  3131. echo "service_$service"
  3132. }
  3133. _graph_node_service_content() {
  3134. local service="$1"
  3135. charm=$(get_service_charm "$service") || return 1
  3136. cat <<EOF
  3137. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3138. <tr>
  3139. <td bgcolor="black" align="center" colspan="2">
  3140. <font color="white">$service</font>
  3141. </td>
  3142. </tr>
  3143. $(if [ "$charm" != "$service" ]; then
  3144. cat <<EOF2
  3145. <tr>
  3146. <td align="left" port="r0">charm: $charm</td>
  3147. </tr>
  3148. EOF2
  3149. fi)
  3150. </table>
  3151. EOF
  3152. }
  3153. cla_contains () {
  3154. local e
  3155. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3156. return 1
  3157. }
  3158. filter_docker_compose_help_message() {
  3159. cat - |
  3160. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3161. s/docker-compose.yml/compose.yml/g;
  3162. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3163. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3164. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3165. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3166. }
  3167. graph() {
  3168. local services=("$@")
  3169. declare -A entries
  3170. cat <<EOF
  3171. digraph g {
  3172. graph [
  3173. fontsize=30
  3174. labelloc="t"
  3175. label=""
  3176. splines=true
  3177. overlap=false
  3178. #rankdir = "LR"
  3179. ];
  3180. ratio = auto;
  3181. EOF
  3182. for target_service in "$@"; do
  3183. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3184. for service in $services; do
  3185. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3186. if cla_contains "$service" "${services[@]}"; then
  3187. base=true
  3188. else
  3189. base=
  3190. fi
  3191. _graph_service "$service" "$base"
  3192. done
  3193. done
  3194. echo "}"
  3195. }
  3196. cached_wget() {
  3197. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3198. url="$1"
  3199. if [ -e "$cache_file" ]; then
  3200. cat "$cache_file"
  3201. touch "$cache_file"
  3202. return 0
  3203. fi
  3204. wget -O- "${url}" |
  3205. tee "$cache_file"
  3206. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3207. rm "$cache_file"
  3208. die "Unable to fetch '$url'."
  3209. return 1
  3210. fi
  3211. }
  3212. export -f cached_wget
  3213. [ "$SOURCED" ] && return 0
  3214. trap_add "EXIT" clean_cache
  3215. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3216. if [ -r /etc/default/charm ]; then
  3217. . /etc/default/charm
  3218. fi
  3219. if [ -r "/etc/default/$exname" ]; then
  3220. . "/etc/default/$exname"
  3221. fi
  3222. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3223. ## userdir ? and global /etc/compose.yml ?
  3224. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3225. /etc/default/compose /etc/compose/local.conf; do
  3226. [ -e "$cfgfile" ] || continue
  3227. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3228. done
  3229. fi
  3230. _setup_state_dir
  3231. mkdir -p "$CACHEDIR" || exit 1
  3232. ##
  3233. ## Argument parsing
  3234. ##
  3235. wrap_opts=()
  3236. services=()
  3237. remainder_args=()
  3238. compose_opts=()
  3239. compose_contents=()
  3240. action_opts=()
  3241. services_args=()
  3242. pos_arg_ct=0
  3243. no_hooks=
  3244. no_init=
  3245. action=
  3246. stage="main" ## switches from 'main', to 'action', 'remainder'
  3247. is_docker_compose_action=
  3248. rebuild_relations_to_service=()
  3249. declare -A without_relations
  3250. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3251. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  3252. while read-0 arg; do
  3253. case "$stage" in
  3254. "main")
  3255. case "$arg" in
  3256. --help|-h)
  3257. no_init=true ; no_hooks=true ; no_relations=true
  3258. display_help
  3259. exit 0
  3260. ;;
  3261. --verbose|-v)
  3262. export VERBOSE=true
  3263. compose_opts+=("--verbose")
  3264. ;;
  3265. --quiet|-q)
  3266. export QUIET=true
  3267. export wrap_opts+=("-q")
  3268. ;;
  3269. --version|-V)
  3270. print_version
  3271. docker-compose --version
  3272. docker --version
  3273. exit 0
  3274. ;;
  3275. -f|--file)
  3276. read-0 value
  3277. [ -e "$value" ] || die "File $value doesn't exists"
  3278. export COMPOSE_YML_FILE="$value"
  3279. shift
  3280. ;;
  3281. -p|--project-name)
  3282. read-0 value
  3283. export DEFAULT_PROJECT_NAME="$value"
  3284. compose_opts+=("--project-name $value")
  3285. shift
  3286. ;;
  3287. --no-relations)
  3288. export no_relations=true
  3289. ;;
  3290. --without-relation)
  3291. read-0 value
  3292. without_relations["$value"]=1
  3293. shift
  3294. ;;
  3295. --no-hooks)
  3296. export no_hooks=true
  3297. ;;
  3298. --no-init)
  3299. export no_init=true
  3300. ;;
  3301. --rebuild-relations-to-service|-R)
  3302. read-0 value
  3303. rebuild_relations_to_service+=("$value")
  3304. shift
  3305. ;;
  3306. --debug)
  3307. export DEBUG=true
  3308. export VERBOSE=true
  3309. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3310. ;;
  3311. --add-compose-content|-Y)
  3312. read-0 value
  3313. compose_contents+=("$value")
  3314. shift
  3315. ;;
  3316. --dirs)
  3317. echo "CACHEDIR: $CACHEDIR"
  3318. echo "VARDIR: $VARDIR"
  3319. exit 0
  3320. ;;
  3321. --dry-compose-run)
  3322. export DRY_COMPOSE_RUN=true
  3323. ;;
  3324. --*|-*)
  3325. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3326. read-0 value
  3327. compose_opts+=("$arg" "$value")
  3328. shift;
  3329. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3330. compose_opts+=("$arg")
  3331. else
  3332. err "Unknown option '$arg'. Please check help:"
  3333. display_help >&2
  3334. exit 1
  3335. fi
  3336. ;;
  3337. *)
  3338. action="$arg"
  3339. stage="action"
  3340. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3341. is_docker_compose_action=true
  3342. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3343. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3344. if [ "$DC_MATCH_MULTI" ]; then
  3345. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3346. fi
  3347. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3348. pos_args=("${pos_args[@]:1}")
  3349. # echo "USAGE: $DC_USAGE"
  3350. # echo "pos_args: ${pos_args[@]}"
  3351. # echo "MULTI: $DC_MATCH_MULTI"
  3352. # echo "SINGLE: $DC_MATCH_SINGLE"
  3353. # exit 1
  3354. else
  3355. stage="remainder"
  3356. fi
  3357. ;;
  3358. esac
  3359. ;;
  3360. "action") ## Only for docker-compose actions
  3361. case "$arg" in
  3362. --help|-h)
  3363. no_init=true ; no_hooks=true ; no_relations=true
  3364. action_opts+=("$arg")
  3365. ;;
  3366. --*|-*)
  3367. if [ "$is_docker_compose_action" ]; then
  3368. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3369. read-0 value
  3370. action_opts+=("$arg" "$value")
  3371. shift
  3372. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3373. action_opts+=("$arg")
  3374. else
  3375. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3376. docker-compose "$action" --help |
  3377. filter_docker_compose_help_message >&2
  3378. exit 1
  3379. fi
  3380. fi
  3381. ;;
  3382. *)
  3383. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3384. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3385. services_args+=("$arg")
  3386. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3387. services_args=("$arg") || exit 1
  3388. stage="remainder"
  3389. else
  3390. action_posargs+=("$arg")
  3391. ((pos_arg_ct++))
  3392. fi
  3393. ;;
  3394. esac
  3395. ;;
  3396. "remainder")
  3397. remainder_args+=("$arg")
  3398. while read-0 arg; do
  3399. remainder_args+=("$arg")
  3400. done
  3401. break 3
  3402. ;;
  3403. esac
  3404. shift
  3405. done < <(cla.normalize "$@")
  3406. export compose_contents
  3407. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3408. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3409. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3410. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3411. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3412. aexport remainder_args
  3413. ##
  3414. ## Actual code
  3415. ##
  3416. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3417. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3418. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3419. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3420. ##
  3421. ## Get services in command line.
  3422. ##
  3423. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3424. action_service=${remainder_args[0]}
  3425. if [ -z "$action_service" ]; then
  3426. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3427. display_commands_help
  3428. exit 1
  3429. fi
  3430. remainder_args=("${remainder_args[@]:1}")
  3431. if has_service_action "$action_service" "$action" >/dev/null; then
  3432. is_service_action=true
  3433. {
  3434. read-0 action_type
  3435. case "$action_type" in
  3436. "relation")
  3437. read-0 _ target_service _target_charm relation_name
  3438. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3439. ;;
  3440. "direct")
  3441. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3442. ;;
  3443. esac
  3444. } < <(has_service_action "$action_service" "$action")
  3445. services_args=("$action_service")
  3446. else
  3447. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3448. fi
  3449. else
  3450. case "$action" in
  3451. ps|up)
  3452. if [ "${#services_args[@]}" == 0 ]; then
  3453. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3454. fi
  3455. ;;
  3456. config)
  3457. services_args=("${action_posargs[@]}")
  3458. ;;
  3459. esac
  3460. fi
  3461. NO_CONSTRAINT_CHECK=True
  3462. case "$action" in
  3463. up)
  3464. NO_CONSTRAINT_CHECK=
  3465. ;;
  3466. esac
  3467. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3468. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3469. services=($(get_master_services "${services_args[@]}")) || exit 1
  3470. if [ "$action" == "up" ]; then
  3471. ## remove run-once
  3472. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3473. type="$(get_service_type "$service")" || exit 1
  3474. if [ "$type" != "run-once" ]; then
  3475. action_posargs+=("$service")
  3476. fi
  3477. done
  3478. else
  3479. action_posargs+=("${services[@]}")
  3480. fi
  3481. ## Get rid of subordinates
  3482. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  3483. fi
  3484. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3485. err "Fails to compile base 'docker-compose.yml'"
  3486. exit 1
  3487. }
  3488. ##
  3489. ## Pre-action
  3490. ##
  3491. full_init=
  3492. case "$action" in
  3493. up|run)
  3494. full_init=true
  3495. post_hook=true
  3496. ;;
  3497. ""|down|restart|logs|config|ps)
  3498. full_init=
  3499. ;;
  3500. *)
  3501. if [ "$is_service_action" ]; then
  3502. full_init=true
  3503. fi
  3504. ;;
  3505. esac
  3506. if [ "$full_init" ]; then
  3507. ## init in order
  3508. if [ -z "$no_init" ]; then
  3509. Section setup host resources
  3510. setup_host_resources "${services_args[@]}" || exit 1
  3511. Section initialisation
  3512. run_service_hook init "${services_args[@]}" || exit 1
  3513. fi
  3514. ## Get relations
  3515. if [ -z "$no_relations" ]; then
  3516. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3517. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3518. rebuild_relations_to_service=($rebuild_relations_to_service)
  3519. project=$(get_default_project_name) || return 1
  3520. for service in "${rebuild_relations_to_service[@]}"; do
  3521. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3522. [ -d "$dir" ] && {
  3523. debug rm -rf "$dir"
  3524. rm -rf "$dir"
  3525. }
  3526. done
  3527. done
  3528. fi
  3529. run_service_relations "${services_args[@]}" || exit 1
  3530. fi
  3531. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3532. fi
  3533. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3534. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3535. metadata=$(charm.metadata "$charm") || exit 1
  3536. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3537. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3538. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3539. fi
  3540. fi
  3541. export SERVICE_PACK="${services_args[*]}"
  3542. ##
  3543. ## Docker-compose
  3544. ##
  3545. case "$action" in
  3546. up|start|stop|build|run)
  3547. ## force daemon mode for up
  3548. if [[ "$action" == "up" ]]; then
  3549. if ! array_member action_opts -d; then
  3550. action_opts+=("-d")
  3551. fi
  3552. if ! array_member action_opts --remove-orphans; then
  3553. action_opts+=("--remove-orphans")
  3554. fi
  3555. fi
  3556. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3557. ;;
  3558. logs)
  3559. if ! array_member action_opts --tail; then ## force daemon mode for up
  3560. action_opts+=("--tail" "10")
  3561. fi
  3562. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3563. ;;
  3564. "")
  3565. launch_docker_compose "${compose_opts[@]}"
  3566. ;;
  3567. graph)
  3568. graph $SERVICE_PACK
  3569. ;;
  3570. config)
  3571. ## removing the services
  3572. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3573. ## forcing docker-compose config to output the config file to stdout and not stderr
  3574. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3575. echo "$out"
  3576. exit 1
  3577. }
  3578. echo "$out"
  3579. warn "Runtime configuration modification (from relations) are not included here."
  3580. ;;
  3581. down)
  3582. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3583. debug "Adding a default argument of '--remove-orphans'"
  3584. action_opts+=("--remove-orphans")
  3585. fi
  3586. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3587. ;;
  3588. *)
  3589. if [ "$is_service_action" ]; then
  3590. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  3591. else
  3592. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3593. fi
  3594. ;;
  3595. esac || exit 1
  3596. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  3597. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3598. fi
  3599. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3600. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3601. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  3602. fi
  3603. fi
  3604. clean_unused_docker_compose || return 1