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.

4231 lines
139 KiB

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