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.

4221 lines
138 KiB

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