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.

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