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.

4243 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. providers_def=()
  2061. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2062. if [ "${#providers[@]}" == 1 ]; then
  2063. ts="${providers[0]}"
  2064. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2065. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2066. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2067. "${providers_def[0]}" "$relation_def" \
  2068. >> "${cache_file}.wip"
  2069. ## Adding service
  2070. [ "${services[$ts]}" ] && continue
  2071. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2072. services[$ts]=1
  2073. changed=1
  2074. continue
  2075. elif [ "${#providers[@]}" -gt 1 ]; then
  2076. msg=""
  2077. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2078. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2079. "(> 1 provider)."
  2080. continue
  2081. else
  2082. if [ "$auto" == "summon" ]; then
  2083. summon+=("$service" "$relation_name" "$relation_def")
  2084. fi
  2085. fi
  2086. ;;
  2087. ""|null|disable|disabled)
  2088. :
  2089. ;;
  2090. *)
  2091. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2092. return 1
  2093. ;;
  2094. esac
  2095. constraint=$(echo "$relation_def" | shyaml get-value constraint auto-pair 2>/dev/null)
  2096. case "$constraint" in
  2097. "required")
  2098. required+=("$service" "$relation_name" "$relation_def")
  2099. ;;
  2100. "recommended")
  2101. recommended+=("$service" "$relation_name" "$relation_def")
  2102. ;;
  2103. "optional")
  2104. optional+=("$service" "$relation_name" "$relation_def")
  2105. ;;
  2106. *)
  2107. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2108. return 1
  2109. ;;
  2110. esac
  2111. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2112. done
  2113. services_uses=("${new_services_uses[@]}")
  2114. if [ "$changed" ]; then
  2115. continue
  2116. fi
  2117. ## situation is stable
  2118. if [ "${#summon[@]}" != 0 ]; then
  2119. while [ "${#summon[@]}" != 0 ]; do
  2120. service="${summon[0]}"
  2121. relation_name="${summon[1]}"
  2122. relation_def="${summon[2]}"
  2123. summon=("${summon[@]:3}")
  2124. providers=()
  2125. providers_def=()
  2126. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2127. if [ "${#providers[@]}" == 0 ]; then
  2128. die "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2129. fi
  2130. if [ "${#providers[@]}" -gt 1 ]; then
  2131. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2132. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2133. "(> 1 provider). Choosing first."
  2134. fi
  2135. ts="${providers[0]}"
  2136. ## YYYvlab: should be seen even in no debug mode no ?
  2137. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2138. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2139. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2140. "${providers_def[0]}" "$relation_def" \
  2141. >> "${cache_file}.wip"
  2142. ## Adding service
  2143. [ "${services[$ts]}" ] && continue
  2144. array_read-0 services_uses < <(_get_services_uses "$ts")
  2145. services[$ts]=1
  2146. changed=1
  2147. done
  2148. continue
  2149. fi
  2150. [ "$NO_CONSTRAINT_CHECK" ] && break
  2151. if [ "${#required[@]}" != 0 ]; then
  2152. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2153. err "Required relations not satisfied"
  2154. return 1
  2155. fi
  2156. if [ "${#recommended[@]}" != 0 ]; then
  2157. ## make recommendation
  2158. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2159. fi
  2160. if [ "${#optional[@]}" != 0 ]; then
  2161. ## inform about options
  2162. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2163. fi
  2164. # if [ "${#required[@]}" != 0 ]; then
  2165. # err "Required relations not satisfied"
  2166. # return 1
  2167. # fi
  2168. if [ "${#recommended[@]}" != 0 ]; then
  2169. warn "Recommended relations not satisfied"
  2170. fi
  2171. break
  2172. done
  2173. if [ "$?" != 0 ]; then
  2174. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2175. return 1
  2176. fi
  2177. export ALL_RELATIONS="$cache_file"
  2178. mv "${cache_file}"{.wip,}
  2179. cat "$cache_file"
  2180. }
  2181. export -f get_all_relations
  2182. _display_solves() {
  2183. local array_name="$1" by_relation msg
  2184. ## inform about options
  2185. msg=""
  2186. declare -A by_relation
  2187. while read-0 service relation_name relation_def; do
  2188. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2189. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2190. if [ -z "$solves" ]; then
  2191. continue
  2192. fi
  2193. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2194. if [ "$auto" == "pair" ]; then
  2195. requirement="add provider in cluster to auto-pair"
  2196. else
  2197. requirement="add explicit relation"
  2198. fi
  2199. while read-0 name def; do
  2200. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2201. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2202. done < <(array_values_to_stdin "$array_name")
  2203. while read-0 relation_name message; do
  2204. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2205. "$relation_name" "$message" )"
  2206. done < <(array_kv_to_stdin by_relation)
  2207. if [ "$msg" ]; then
  2208. printf "%s\n" "${msg:1}"
  2209. fi
  2210. }
  2211. get_compose_relation_def() {
  2212. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2213. while read-0 relation_name target_service relation_config tech_dep; do
  2214. [ "$relation_name" == "$relation" ] || continue
  2215. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2216. done < <(get_compose_relations "$service") || return 1
  2217. }
  2218. export -f get_compose_relation_def
  2219. run_service_relations () {
  2220. local service services loaded subservices subservice
  2221. PROJECT_NAME=$(get_default_project_name) || return 1
  2222. export PROJECT_NAME
  2223. declare -A loaded
  2224. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2225. for service in $subservices; do
  2226. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2227. for subservice in $(get_service_deps "$service") "$service"; do
  2228. [ "${loaded[$subservice]}" ] && continue
  2229. export BASE_SERVICE_NAME=$service
  2230. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2231. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2232. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2233. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2234. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2235. while read-0 relation_name target_service relation_config tech_dep; do
  2236. export relation_config
  2237. export TARGET_SERVICE_NAME=$target_service
  2238. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2239. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2240. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2241. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2242. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2243. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2244. EOF
  2245. done < <(get_service_relations "$subservice") || return 1
  2246. loaded[$subservice]=1
  2247. done
  2248. done
  2249. }
  2250. export -f run_service_relations
  2251. _run_service_action_direct() {
  2252. local service="$1" action="$2" charm _dummy
  2253. shift; shift
  2254. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  2255. if read-0 _dummy || [ "$_dummy" ]; then
  2256. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2257. return 1
  2258. fi
  2259. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2260. export state_tmpdir
  2261. (
  2262. set +e ## Prevents unwanted leaks from parent shell
  2263. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2264. export METADATA_CONFIG=$(charm.metadata "$charm")
  2265. export SERVICE_NAME=$service
  2266. export ACTION_NAME=$action
  2267. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2268. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2269. export SERVICE_DATASTORE="$DATASTORE/$service"
  2270. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2271. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2272. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2273. )
  2274. }
  2275. export -f _run_service_action_direct
  2276. _run_service_action_relation() {
  2277. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2278. shift; shift
  2279. read-0 charm target_service target_charm relation_name relation_config || true
  2280. if read-0 _dummy || [ "$_dummy" ]; then
  2281. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2282. return 1
  2283. fi
  2284. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  2285. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2286. export state_tmpdir
  2287. {
  2288. (
  2289. set +e ## Prevents unwanted leaks from parent shell
  2290. export METADATA_CONFIG=$(charm.metadata "$charm")
  2291. export SERVICE_NAME=$service
  2292. export RELATION_TARGET_SERVICE="$target_service"
  2293. export RELATION_TARGET_CHARM="$target_charm"
  2294. export RELATION_BASE_SERVICE="$service"
  2295. export RELATION_BASE_CHARM="$charm"
  2296. export ACTION_NAME=$action
  2297. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2298. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2299. export SERVICE_DATASTORE="$DATASTORE/$service"
  2300. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2301. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2302. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2303. echo "$?" > "$action_errlvl_file"
  2304. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2305. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2306. if ! [ -e "$action_errlvl_file" ]; then
  2307. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2308. "to output an errlvl"
  2309. return 1
  2310. fi
  2311. return "$(cat "$action_errlvl_file")"
  2312. }
  2313. export -f _run_service_action_relation
  2314. get_relation_data_dir() {
  2315. local service="$1" target_service="$2" relation_name="$3" \
  2316. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2317. if [ -e "$cache_file" ]; then
  2318. # debug "$FUNCNAME: cache hit ($*)"
  2319. cat "$cache_file"
  2320. return 0
  2321. fi
  2322. project=$(get_default_project_name) || return 1
  2323. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2324. if ! [ -d "$relation_dir" ]; then
  2325. mkdir -p "$relation_dir" || return 1
  2326. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2327. fi
  2328. echo "$relation_dir" | tee "$cache_file"
  2329. }
  2330. export -f get_relation_data_dir
  2331. get_relation_data_file() {
  2332. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2333. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2334. relation_data_file="$relation_dir/data"
  2335. new=
  2336. if [ -e "$relation_data_file" ]; then
  2337. ## Has reference changed ?
  2338. new_md5=$(echo "$relation_config" | md5_compat)
  2339. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2340. new=true
  2341. fi
  2342. else
  2343. new=true
  2344. fi
  2345. if [ "$new" ]; then
  2346. echo "$relation_config" > "$relation_data_file"
  2347. chmod go-rwx "$relation_data_file" ## protecting this file
  2348. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2349. fi
  2350. echo "$relation_data_file"
  2351. }
  2352. export -f get_relation_data_file
  2353. has_service_action () {
  2354. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2355. charm target_charm relation_name target_service relation_config _tech_dep
  2356. if [ -e "$cache_file" ]; then
  2357. # debug "$FUNCNAME: cache hit ($*)"
  2358. cat "$cache_file"
  2359. return 0
  2360. fi
  2361. charm=$(get_service_charm "$service") || return 1
  2362. ## Action directly provided ?
  2363. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  2364. echo -en "direct\0$charm" | tee "$cache_file"
  2365. return 0
  2366. fi
  2367. ## Action provided by relation ?
  2368. while read-0 relation_name target_service relation_config _tech_dep; do
  2369. target_charm=$(get_service_charm "$target_service") || return 1
  2370. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  2371. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  2372. return 0
  2373. fi
  2374. done < <(get_service_relations "$service")
  2375. return 1
  2376. # master=$(get_top_master_service_for_service "$service")
  2377. # [ "$master" == "$charm" ] && return 1
  2378. # has_service_action "$master" "$action"
  2379. }
  2380. export -f has_service_action
  2381. run_service_action () {
  2382. local service="$1" action="$2"
  2383. shift ; shift
  2384. {
  2385. if ! read-0 action_type; then
  2386. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2387. info " Add an executable script to 'actions/$action' to implement action."
  2388. return 1
  2389. fi
  2390. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2391. } < <(has_service_action "$service" "$action")
  2392. }
  2393. export -f run_service_action
  2394. get_compose_relation_config() {
  2395. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2396. if [ -e "$cache_file" ]; then
  2397. # debug "$FUNCNAME: cache hit ($*)"
  2398. cat "$cache_file"
  2399. return 0
  2400. fi
  2401. compose_service_def=$(get_compose_service_def "$service") || return 1
  2402. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2403. }
  2404. export -f get_compose_relation_config
  2405. # ## Return key-values-0
  2406. # get_compose_relation_config_for_service() {
  2407. # local service=$1 relation_name=$2 relation_config
  2408. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2409. # if ! relation_config=$(
  2410. # echo "$compose_service_relations" |
  2411. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2412. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2413. # "relation config in compose configuration."
  2414. # return 1
  2415. # fi
  2416. # if [ -z "$relation_config" ]; then
  2417. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2418. # return 1
  2419. # fi
  2420. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2421. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2422. # return 1
  2423. # fi
  2424. # }
  2425. # export -f get_compose_relation_config_for_service
  2426. _get_container_relation() {
  2427. local metadata=$1 found relation_name relation_def
  2428. found=
  2429. while read-0 relation_name relation_def; do
  2430. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2431. found="$relation_name"
  2432. break
  2433. }
  2434. done < <(_get_charm_metadata_uses "$metadata")
  2435. if [ -z "$found" ]; then
  2436. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2437. "${WHITE}scope${NORMAL} set to 'container'."
  2438. fi
  2439. printf "%s" "$found"
  2440. }
  2441. _get_master_service_for_service_cached () {
  2442. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2443. charm requires master_charm target_charm target_service service_def found
  2444. if [ -e "$cache_file" ]; then
  2445. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2446. cat "$cache_file" &&
  2447. touch "$cache_file" || return 1
  2448. return 0
  2449. fi
  2450. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2451. ## just return service name
  2452. echo "$service" | tee "$cache_file"
  2453. return 0
  2454. fi
  2455. ## Action provided by relation ?
  2456. container_relation=$(_get_container_relation "$metadata") || exit 1
  2457. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2458. if [ -z "$target_service" ]; then
  2459. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2460. "${DARKYELLOW}$service$NORMAL compose definition."
  2461. err ${FUNCNAME[@]}
  2462. return 1
  2463. fi
  2464. echo "$target_service" | tee "$cache_file"
  2465. }
  2466. export -f _get_master_service_for_service_cached
  2467. get_master_service_for_service() {
  2468. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2469. charm metadata result
  2470. if [ -e "$cache_file" ]; then
  2471. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2472. cat "$cache_file" || return 1
  2473. return 0
  2474. fi
  2475. charm=$(get_service_charm "$service") || return 1
  2476. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2477. metadata=""
  2478. warn "No charm $DARKPINK$charm$NORMAL found."
  2479. }
  2480. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2481. echo "$result" | tee "$cache_file" || return 1
  2482. }
  2483. export -f get_master_service_for_service
  2484. get_top_master_service_for_service() {
  2485. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2486. current_service
  2487. if [ -e "$cache_file" ]; then
  2488. # debug "$FUNCNAME: cache hit ($*)"
  2489. cat "$cache_file"
  2490. return 0
  2491. fi
  2492. current_service="$service"
  2493. while true; do
  2494. master_service=$(get_master_service_for_service "$current_service") || return 1
  2495. [ "$master_service" == "$current_service" ] && break
  2496. current_service="$master_service"
  2497. done
  2498. echo "$current_service" | tee "$cache_file"
  2499. return 0
  2500. }
  2501. export -f get_top_master_service_for_service
  2502. ##
  2503. ## The result is a mixin that is not always a complete valid
  2504. ## docker-compose entry (thinking of subordinates). The result
  2505. ## will be merge with master charms.
  2506. _get_docker_compose_mixin_from_metadata_cached() {
  2507. local service="$1" charm="$2" metadata="$3" \
  2508. has_build_dir="$4" \
  2509. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2510. metadata_file metadata volumes docker_compose subordinate image mixin mixins
  2511. if [ -e "$cache_file" ]; then
  2512. #debug "$FUNCNAME: STATIC cache hit $1"
  2513. cat "$cache_file" &&
  2514. touch "$cache_file" || return 1
  2515. return 0
  2516. fi
  2517. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2518. if [ "$metadata" ]; then
  2519. ## resources to volumes
  2520. volumes=$(
  2521. for resource_type in data config; do
  2522. while read-0 resource; do
  2523. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2524. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2525. done
  2526. while read-0 resource; do
  2527. if [[ "$resource" == /*:/*:* ]]; then
  2528. echo " - $resource"
  2529. elif [[ "$resource" == /*:/* ]]; then
  2530. echo " - $resource:rw"
  2531. elif [[ "$resource" == /*:* ]]; then
  2532. echo " - ${resource%%:*}:$resource"
  2533. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2534. echo " - $resource:$resource:rw"
  2535. else
  2536. die "Invalid host-resource specified in 'metadata.yml'."
  2537. fi
  2538. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2539. while read-0 resource; do
  2540. dest="$(charm.get_dir "$charm")/resources$resource"
  2541. if ! [ -e "$dest" ]; then
  2542. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2543. fi
  2544. echo " - $dest:$resource:ro"
  2545. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2546. ) || return 1
  2547. if [ "$volumes" ]; then
  2548. mixins+=("volumes:"$'\n'"$volumes")
  2549. fi
  2550. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2551. if [ "$type" != "run-once" ]; then
  2552. mixins+=("restart: unless-stopped")
  2553. fi
  2554. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2555. if [ "$docker_compose" ]; then
  2556. mixins+=("$docker_compose")
  2557. fi
  2558. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2559. subordinate=true
  2560. fi
  2561. fi
  2562. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2563. [ "$image" == "None" ] && image=""
  2564. if [ "$image" ]; then
  2565. if [ "$subordinate" ]; then
  2566. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2567. return 1
  2568. fi
  2569. mixins+=("image: $image")
  2570. elif [ "$has_build_dir" ]; then
  2571. if [ "$subordinate" ]; then
  2572. err "Subordinate charm can not have a 'build' sub directory."
  2573. return 1
  2574. fi
  2575. mixins+=("build: $(charm.get_dir "$charm")/build")
  2576. fi
  2577. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2578. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2579. return 1
  2580. }
  2581. echo "$mixin" | tee "$cache_file"
  2582. }
  2583. export -f _get_docker_compose_mixin_from_metadata_cached
  2584. get_docker_compose_mixin_from_metadata() {
  2585. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2586. if [ -e "$cache_file" ]; then
  2587. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2588. cat "$cache_file"
  2589. return 0
  2590. fi
  2591. charm=$(get_service_charm "$service") || return 1
  2592. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2593. has_build_dir=
  2594. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2595. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2596. echo "$mixin" | tee "$cache_file"
  2597. }
  2598. export -f get_docker_compose_mixin_from_metadata
  2599. _save() {
  2600. local name="$1"
  2601. cat - | tee -a "$docker_compose_dir/.data/$name"
  2602. }
  2603. export -f _save
  2604. get_default_project_name() {
  2605. local normalized_path compose_yml_location name
  2606. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  2607. echo "$DEFAULT_PROJECT_NAME"
  2608. return 0
  2609. fi
  2610. compose_yml_location="$(get_compose_yml_location)" || return 1
  2611. if [ -n "$compose_yml_location" ]; then
  2612. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2613. name="${normalized_path%/*}" ## dirname
  2614. name="${name##*/}" ## basename
  2615. name="${name%%-deploy}" ## remove any '-deploy'
  2616. name="${name,,}" ## lowercase
  2617. e "$name"
  2618. return 0
  2619. fi
  2620. fi
  2621. echo "orphan"
  2622. return 0
  2623. }
  2624. export -f get_default_project_name
  2625. get_running_compose_containers() {
  2626. ## XXXvlab: docker bug: there will be a final newline anyway
  2627. docker ps --filter label="compose.service" --format='{{.ID}}'
  2628. }
  2629. export -f get_running_compose_containers
  2630. get_volumes_for_container() {
  2631. local container="$1"
  2632. docker inspect \
  2633. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2634. "$container"
  2635. }
  2636. export -f get_volumes_for_container
  2637. is_volume_used() {
  2638. local volume="$1" container_id src dst
  2639. while read -r container_id; do
  2640. while read-0 src dst; do
  2641. [[ "$src/" == "$volume"/* ]] && return 0
  2642. done < <(get_volumes_for_container "$container_id")
  2643. done < <(get_running_compose_containers)
  2644. return 1
  2645. }
  2646. export -f is_volume_used
  2647. clean_unused_docker_compose() {
  2648. for f in /var/lib/compose/docker-compose/*; do
  2649. [ -e "$f" ] || continue
  2650. is_volume_used "$f" && continue
  2651. debug "Cleaning unused docker-compose ${f##*/}"
  2652. rm -rf "$f" || return 1
  2653. done
  2654. return 0
  2655. }
  2656. export -f clean_unused_docker_compose
  2657. stdin_get_hash() {
  2658. local sha
  2659. sha=$(sha256sum) || return 1
  2660. sha=${sha:0:64}
  2661. echo "$sha"
  2662. }
  2663. export -f stdin_get_hash
  2664. file_get_hash() {
  2665. stdin_get_hash < "$1" || return 1
  2666. }
  2667. export -f file_get_hash
  2668. docker_compose_store() {
  2669. local file="$1" sha
  2670. sha=$(file_get_hash "$file") || return 1
  2671. project=$(get_default_project_name) || return 1
  2672. dst="/var/lib/compose/docker-compose/$sha/$project"
  2673. mkdir -p "$dst" || return 1
  2674. cat <<EOF > "$dst/.env" || return 1
  2675. DOCKER_COMPOSE_PATH=$dst
  2676. EOF
  2677. cp "$file" "$dst/docker-compose.yml" || return 1
  2678. mkdir -p "$dst/bin" || return 1
  2679. cat <<EOF > "$dst/bin/dc" || return 1
  2680. #!/bin/bash
  2681. $(declare -f read-0)
  2682. docker_run_opts=()
  2683. while read-0 opt; do
  2684. docker_run_opts+=("\$opt")
  2685. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2686. docker_run_opts+=(
  2687. "-w" "$dst"
  2688. "--entrypoint" "/usr/local/bin/docker-compose"
  2689. )
  2690. [ -t 1 ] && {
  2691. docker_run_opts+=("-ti")
  2692. }
  2693. exec docker run --rm "\${docker_run_opts[@]}" "${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2694. EOF
  2695. chmod +x "$dst/bin/dc" || return 1
  2696. printf "%s" "$sha"
  2697. }
  2698. export -f docker_compose_store
  2699. launch_docker_compose() {
  2700. local charm docker_compose_tmpdir docker_compose_dir
  2701. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2702. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2703. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2704. ## docker-compose will name network from the parent dir name
  2705. project=$(get_default_project_name)
  2706. mkdir -p "$docker_compose_tmpdir/$project"
  2707. docker_compose_dir="$docker_compose_tmpdir/$project"
  2708. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2709. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2710. # debug "Merging some config data in docker-compose.yml:"
  2711. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2712. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2713. fi
  2714. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2715. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2716. fi
  2717. ## XXXvlab: could be more specific and only link the needed charms
  2718. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2719. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2720. # if charm.exists "$charm"; then
  2721. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2722. # fi
  2723. # done
  2724. mkdir "$docker_compose_dir/.data"
  2725. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2726. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2727. fi
  2728. {
  2729. {
  2730. {
  2731. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2732. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  2733. else
  2734. cd "$docker_compose_dir" || return 1
  2735. fi
  2736. if [ -f ".env" ]; then
  2737. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2738. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2739. fi
  2740. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2741. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2742. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2743. if [ "$DRY_COMPOSE_RUN" ]; then
  2744. echo docker-compose "$@"
  2745. else
  2746. docker-compose "$@"
  2747. fi
  2748. echo "$?" > "$docker_compose_dir/.data/errlvl"
  2749. } | _save stdout
  2750. } 3>&1 1>&2 2>&3 | _save stderr
  2751. } 3>&1 1>&2 2>&3
  2752. 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
  2753. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  2754. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  2755. fi
  2756. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  2757. if [ -z "$docker_compose_errlvl" ]; then
  2758. err "Something went wrong before you could gather docker-compose errorlevel."
  2759. return 1
  2760. fi
  2761. return "$docker_compose_errlvl"
  2762. }
  2763. export -f launch_docker_compose
  2764. get_compose_yml_location() {
  2765. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  2766. echo "$COMPOSE_YML_FILE"
  2767. return 0
  2768. fi
  2769. parent=$(while ! [ -f "./compose.yml" ]; do
  2770. [ "$PWD" == "/" ] && exit 0
  2771. cd ..
  2772. done; echo "$PWD"
  2773. )
  2774. if [ "$parent" ]; then
  2775. echo "$parent/compose.yml"
  2776. return 0
  2777. fi
  2778. ## XXXvlab: do we need this additional environment variable,
  2779. ## COMPOSE_YML_FILE is not sufficient ?
  2780. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  2781. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  2782. warn "No 'compose.yml' was found in current or parent dirs," \
  2783. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  2784. "(${DEFAULT_COMPOSE_FILE})"
  2785. return 0
  2786. fi
  2787. echo "$DEFAULT_COMPOSE_FILE"
  2788. return 0
  2789. fi
  2790. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  2791. return 0
  2792. }
  2793. export -f get_compose_yml_location
  2794. get_compose_yml_content() {
  2795. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  2796. if [ -e "$cache_file" ]; then
  2797. cat "$cache_file" &&
  2798. touch "$cache_file" || return 1
  2799. return 0
  2800. fi
  2801. if [ -z "$COMPOSE_YML_FILE" ]; then
  2802. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2803. fi
  2804. if [ -e "$COMPOSE_YML_FILE" ]; then
  2805. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2806. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  2807. err "Could not read '$COMPOSE_YML_FILE'."
  2808. return 1
  2809. }
  2810. else
  2811. debug "No compose file found. Using an empty one."
  2812. COMPOSE_YML_CONTENT=""
  2813. fi
  2814. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  2815. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  2816. if [ "$?" != 0 ]; then
  2817. outputed_something=
  2818. while IFS='' read -r line1 && IFS='' read -r line2; do
  2819. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2820. outputed_something=true
  2821. echo "$line1 $GRAY($line2)$NORMAL"
  2822. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2823. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2824. prefix " $GRAY|$NORMAL "
  2825. [ "$outputed_something" ] || {
  2826. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2827. echo "$output" | prefix " $GRAY|$NORMAL "
  2828. }
  2829. return 1
  2830. fi
  2831. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  2832. }
  2833. export -f get_compose_yml_content
  2834. get_default_target_services() {
  2835. local services=("$@")
  2836. if [ -z "${services[*]}" ]; then
  2837. if [ "$DEFAULT_SERVICES" ]; then
  2838. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  2839. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  2840. services="$DEFAULT_SERVICES"
  2841. else
  2842. err "No service provided."
  2843. return 1
  2844. fi
  2845. fi
  2846. echo "${services[*]}"
  2847. }
  2848. export -f get_default_target_services
  2849. get_master_services() {
  2850. local loaded master_service service
  2851. declare -A loaded
  2852. for service in "$@"; do
  2853. master_service=$(get_top_master_service_for_service "$service") || return 1
  2854. if [ "${loaded[$master_service]}" ]; then
  2855. continue
  2856. fi
  2857. echo "$master_service"
  2858. loaded["$master_service"]=1
  2859. done | nspc
  2860. return "${PIPESTATUS[0]}"
  2861. }
  2862. export -f get_master_services
  2863. get_current_docker_container_id() {
  2864. local line
  2865. line=$(cat "/proc/self/cpuset") || return 1
  2866. [[ "$line" == *docker* ]] || return 1
  2867. echo "${line##*/}"
  2868. }
  2869. export -f get_current_docker_container_id
  2870. ## if we are in a docker compose, we might want to know what is the
  2871. ## real host path of some local paths.
  2872. get_host_path() {
  2873. local path="$1"
  2874. path=$(realpath "$path") || return 1
  2875. container_id=$(get_current_docker_container_id) || {
  2876. print "%s" "$path"
  2877. return 0
  2878. }
  2879. biggest_dst=
  2880. current_src=
  2881. while read-0 src dst; do
  2882. [[ "$path" == "$dst"* ]] || continue
  2883. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  2884. biggest_dst="$dst"
  2885. current_src="$src"
  2886. fi
  2887. done < <(get_volumes_for_container "$container_id")
  2888. if [ "$current_src" ]; then
  2889. printf "%s" "$current_src"
  2890. else
  2891. return 1
  2892. fi
  2893. }
  2894. export -f get_host_path
  2895. _setup_state_dir() {
  2896. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2897. #debug "Creating temporary state directory in '$state_tmpdir'."
  2898. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  2899. # rm -rf \"$state_tmpdir\""
  2900. trap_add EXIT "rm -rf \"$state_tmpdir\""
  2901. }
  2902. get_docker_compose_help_msg() {
  2903. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  2904. docker_compose_help_msg
  2905. if [ -e "$cache_file" ]; then
  2906. cat "$cache_file" &&
  2907. touch "$cache_file" || return 1
  2908. return 0
  2909. fi
  2910. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  2911. echo "$docker_compose_help_msg" |
  2912. tee "$cache_file" || return 1
  2913. }
  2914. get_docker_compose_usage() {
  2915. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  2916. docker_compose_help_msg
  2917. if [ -e "$cache_file" ]; then
  2918. cat "$cache_file" &&
  2919. touch "$cache_file" || return 1
  2920. return 0
  2921. fi
  2922. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  2923. echo "$docker_compose_help_msg" |
  2924. grep -m 1 "^Usage:" -A 10000 |
  2925. egrep -m 1 "^\$" -B 10000 |
  2926. nspc |
  2927. sed -r 's/^Usage: //g' |
  2928. tee "$cache_file" || return 1
  2929. }
  2930. get_docker_compose_opts_help() {
  2931. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  2932. docker_compose_help_msg
  2933. if [ -e "$cache_file" ]; then
  2934. cat "$cache_file" &&
  2935. touch "$cache_file" || return 1
  2936. return 0
  2937. fi
  2938. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2939. echo "$docker_compose_opts_help" |
  2940. grep '^Options:' -A 20000 |
  2941. tail -n +2 |
  2942. { cat ; echo; } |
  2943. egrep -m 1 "^\S*\$" -B 10000 |
  2944. head -n -1 |
  2945. tee "$cache_file" || return 1
  2946. }
  2947. get_docker_compose_commands_help() {
  2948. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  2949. docker_compose_help_msg
  2950. if [ -e "$cache_file" ]; then
  2951. cat "$cache_file" &&
  2952. touch "$cache_file" || return 1
  2953. return 0
  2954. fi
  2955. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2956. echo "$docker_compose_opts_help" |
  2957. grep '^Commands:' -A 20000 |
  2958. tail -n +2 |
  2959. { cat ; echo; } |
  2960. egrep -m 1 "^\S*\$" -B 10000 |
  2961. head -n -1 |
  2962. tee "$cache_file" || return 1
  2963. }
  2964. get_docker_compose_opts_list() {
  2965. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  2966. docker_compose_help_msg
  2967. if [ -e "$cache_file" ]; then
  2968. cat "$cache_file" &&
  2969. touch "$cache_file" || return 1
  2970. return 0
  2971. fi
  2972. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2973. echo "$docker_compose_opts_help" |
  2974. egrep "^\s+-" |
  2975. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2976. tee "$cache_file" || return 1
  2977. }
  2978. options_parser() {
  2979. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2980. printf "\0"
  2981. }
  2982. remove_options_in_option_help_msg() {
  2983. {
  2984. read-0 null
  2985. if [ "$null" ]; then
  2986. err "options parsing error, should start with an option line."
  2987. return 1
  2988. fi
  2989. while read-0 opt full_txt;do
  2990. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2991. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2992. for to_remove in "$@"; do
  2993. str_matches "$to_remove" $multi_opts $single_opts && {
  2994. continue 2
  2995. }
  2996. done
  2997. echo -n "$full_txt"
  2998. done
  2999. } < <(options_parser)
  3000. }
  3001. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3002. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3003. multi_opts_filter() {
  3004. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3005. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3006. tr ',' "\n" | nspc
  3007. }
  3008. single_opts_filter() {
  3009. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3010. tr ',' "\n" | nspc
  3011. }
  3012. get_docker_compose_multi_opts_list() {
  3013. local action="$1" opts_list
  3014. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3015. echo "$opts_list" | multi_opts_filter
  3016. }
  3017. get_docker_compose_single_opts_list() {
  3018. local action="$1" opts_list
  3019. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3020. echo "$opts_list" | single_opts_filter
  3021. }
  3022. display_commands_help() {
  3023. local charm_actions
  3024. echo
  3025. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3026. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3027. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3028. if [ "$charm_actions_help" ]; then
  3029. echo
  3030. echo "${WHITE}Charm actions${NORMAL}:"
  3031. printf "%s\n" "$charm_actions_help" | \
  3032. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3033. fi
  3034. }
  3035. get_docker_charm_action_help() {
  3036. local services service charm relation_name target_service relation_config \
  3037. target_charm
  3038. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3039. for service in "${services[@]}"; do
  3040. out=$(
  3041. charm=$(get_service_charm "$service") || return 1
  3042. for action in $(charm.ls_direct_actions "$charm"); do
  3043. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3044. done
  3045. while read-0 relation_name target_service _relation_config _tech_dep; do
  3046. target_charm=$(get_service_charm "$target_service") || return 1
  3047. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3048. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3049. done
  3050. done < <(get_compose_relations "$service")
  3051. )
  3052. if [ "$out" ]; then
  3053. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3054. printf "%s\n" "$out"
  3055. fi
  3056. done
  3057. }
  3058. display_help() {
  3059. print_help
  3060. echo "${WHITE}Usage${NORMAL}:"
  3061. echo " $usage"
  3062. echo "${WHITE}Options${NORMAL}:"
  3063. echo " -h, --help Print this message and quit"
  3064. echo " (ignoring any other options)"
  3065. echo " -V, --version Print current version and quit"
  3066. echo " (ignoring any other options)"
  3067. echo " --dirs Display data dirs and quit"
  3068. echo " (ignoring any other options)"
  3069. echo " -v, --verbose Be more verbose"
  3070. echo " -q, --quiet Be quiet"
  3071. echo " -d, --debug Print full debugging information (sets also verbose)"
  3072. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3073. echo " command line will be used."
  3074. echo " --no-relations Do not run any relation script"
  3075. echo " --no-hooks Do not run any init script"
  3076. echo " --no-init Do not run any init script"
  3077. echo " --without-relation RELATION "
  3078. echo " Do not run given relation"
  3079. echo " -R, --rebuild-relations-to-service SERVICE"
  3080. echo " Will rebuild all relations to given service"
  3081. echo " --add-compose-content, -Y YAML"
  3082. echo " Will merge some direct YAML with the current compose"
  3083. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3084. filter_docker_compose_help_message
  3085. display_commands_help
  3086. }
  3087. _graph_service() {
  3088. local service="$1" base="$1"
  3089. charm=$(get_service_charm "$service") || return 1
  3090. metadata=$(charm.metadata "$charm") || return 1
  3091. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3092. if [ "$subordinate" == "True" ]; then
  3093. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3094. master_charm=
  3095. while read-0 relation_name relation; do
  3096. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3097. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3098. if [ -z "$interface" ]; then
  3099. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3100. return 1
  3101. fi
  3102. ## Action provided by relation ?
  3103. target_service=
  3104. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3105. [ "$interface" == "$relation_name" ] && {
  3106. target_service="$candidate_target_service"
  3107. break
  3108. }
  3109. done < <(get_service_relations "$service")
  3110. if [ -z "$target_service" ]; then
  3111. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3112. "${DARKYELLOW}$service$NORMAL compose definition."
  3113. return 1
  3114. fi
  3115. master_service="$target_service"
  3116. master_charm=$(get_service_charm "$target_service") || return 1
  3117. break
  3118. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3119. fi
  3120. _graph_node_service "$service" "$base" "$charm"
  3121. _graph_edge_service "$service" "$subordinate" "$master_service"
  3122. }
  3123. _graph_node_service() {
  3124. local service="$1" base="$2" charm="$3"
  3125. cat <<EOF
  3126. "$(_graph_node_service_label ${service})" [
  3127. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  3128. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  3129. color = $([ "$base" ] && echo "blue" || echo "black")
  3130. fillcolor = "white"
  3131. fontname = "Courier New"
  3132. shape = "Mrecord"
  3133. label =<$(_graph_node_service_content "$service")>
  3134. ];
  3135. EOF
  3136. }
  3137. _graph_edge_service() {
  3138. local service="$1" subordinate="$2" master_service="$3"
  3139. while read-0 relation_name target_service relation_config tech_dep; do
  3140. cat <<EOF
  3141. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3142. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3143. fontsize = 16
  3144. fontcolor = "black"
  3145. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3146. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3147. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3148. arrowtail = odot
  3149. # arrowhead = dotlicurve
  3150. taillabel = "$relation_name" ];
  3151. EOF
  3152. done < <(get_service_relations "$service") || return 1
  3153. }
  3154. _graph_node_service_label() {
  3155. local service="$1"
  3156. echo "service_$service"
  3157. }
  3158. _graph_node_service_content() {
  3159. local service="$1"
  3160. charm=$(get_service_charm "$service") || return 1
  3161. cat <<EOF
  3162. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3163. <tr>
  3164. <td bgcolor="black" align="center" colspan="2">
  3165. <font color="white">$service</font>
  3166. </td>
  3167. </tr>
  3168. $(if [ "$charm" != "$service" ]; then
  3169. cat <<EOF2
  3170. <tr>
  3171. <td align="left" port="r0">charm: $charm</td>
  3172. </tr>
  3173. EOF2
  3174. fi)
  3175. </table>
  3176. EOF
  3177. }
  3178. cla_contains () {
  3179. local e
  3180. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3181. return 1
  3182. }
  3183. filter_docker_compose_help_message() {
  3184. cat - |
  3185. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3186. s/docker-compose.yml/compose.yml/g;
  3187. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3188. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3189. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3190. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3191. }
  3192. graph() {
  3193. local services=("$@")
  3194. declare -A entries
  3195. cat <<EOF
  3196. digraph g {
  3197. graph [
  3198. fontsize=30
  3199. labelloc="t"
  3200. label=""
  3201. splines=true
  3202. overlap=false
  3203. #rankdir = "LR"
  3204. ];
  3205. ratio = auto;
  3206. EOF
  3207. for target_service in "$@"; do
  3208. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3209. for service in $services; do
  3210. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3211. if cla_contains "$service" "${services[@]}"; then
  3212. base=true
  3213. else
  3214. base=
  3215. fi
  3216. _graph_service "$service" "$base"
  3217. done
  3218. done
  3219. echo "}"
  3220. }
  3221. cached_wget() {
  3222. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  3223. url="$1"
  3224. if [ -e "$cache_file" ]; then
  3225. cat "$cache_file"
  3226. touch "$cache_file"
  3227. return 0
  3228. fi
  3229. wget -O- "${url}" |
  3230. tee "$cache_file"
  3231. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3232. rm "$cache_file"
  3233. die "Unable to fetch '$url'."
  3234. return 1
  3235. fi
  3236. }
  3237. export -f cached_wget
  3238. [ "$SOURCED" ] && return 0
  3239. trap_add "EXIT" clean_cache
  3240. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3241. if [ -r /etc/default/charm ]; then
  3242. . /etc/default/charm
  3243. fi
  3244. if [ -r "/etc/default/$exname" ]; then
  3245. . "/etc/default/$exname"
  3246. fi
  3247. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3248. ## userdir ? and global /etc/compose.yml ?
  3249. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3250. /etc/default/compose /etc/compose/local.conf; do
  3251. [ -e "$cfgfile" ] || continue
  3252. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3253. done
  3254. fi
  3255. _setup_state_dir
  3256. mkdir -p "$CACHEDIR" || exit 1
  3257. ##
  3258. ## Argument parsing
  3259. ##
  3260. wrap_opts=()
  3261. services=()
  3262. remainder_args=()
  3263. compose_opts=()
  3264. compose_contents=()
  3265. action_opts=()
  3266. services_args=()
  3267. pos_arg_ct=0
  3268. no_hooks=
  3269. no_init=
  3270. action=
  3271. stage="main" ## switches from 'main', to 'action', 'remainder'
  3272. is_docker_compose_action=
  3273. rebuild_relations_to_service=()
  3274. declare -A without_relations
  3275. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3276. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  3277. while read-0 arg; do
  3278. case "$stage" in
  3279. "main")
  3280. case "$arg" in
  3281. --help|-h)
  3282. no_init=true ; no_hooks=true ; no_relations=true
  3283. display_help
  3284. exit 0
  3285. ;;
  3286. --verbose|-v)
  3287. export VERBOSE=true
  3288. compose_opts+=("--verbose")
  3289. ;;
  3290. --quiet|-q)
  3291. export QUIET=true
  3292. export wrap_opts+=("-q")
  3293. ;;
  3294. --version|-V)
  3295. print_version
  3296. docker-compose --version
  3297. docker --version
  3298. exit 0
  3299. ;;
  3300. -f|--file)
  3301. read-0 value
  3302. [ -e "$value" ] || die "File $value doesn't exists"
  3303. export COMPOSE_YML_FILE="$value"
  3304. shift
  3305. ;;
  3306. -p|--project-name)
  3307. read-0 value
  3308. export DEFAULT_PROJECT_NAME="$value"
  3309. compose_opts+=("--project-name $value")
  3310. shift
  3311. ;;
  3312. --no-relations)
  3313. export no_relations=true
  3314. ;;
  3315. --without-relation)
  3316. read-0 value
  3317. without_relations["$value"]=1
  3318. shift
  3319. ;;
  3320. --no-hooks)
  3321. export no_hooks=true
  3322. ;;
  3323. --no-init)
  3324. export no_init=true
  3325. ;;
  3326. --rebuild-relations-to-service|-R)
  3327. read-0 value
  3328. rebuild_relations_to_service+=("$value")
  3329. shift
  3330. ;;
  3331. --debug|-d)
  3332. export DEBUG=true
  3333. export VERBOSE=true
  3334. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3335. ;;
  3336. --add-compose-content|-Y)
  3337. read-0 value
  3338. compose_contents+=("$value")
  3339. shift
  3340. ;;
  3341. --dirs)
  3342. echo "CACHEDIR: $CACHEDIR"
  3343. echo "VARDIR: $VARDIR"
  3344. exit 0
  3345. ;;
  3346. --dry-compose-run)
  3347. export DRY_COMPOSE_RUN=true
  3348. ;;
  3349. --*|-*)
  3350. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3351. read-0 value
  3352. compose_opts+=("$arg" "$value")
  3353. shift;
  3354. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3355. compose_opts+=("$arg")
  3356. else
  3357. err "Unknown option '$arg'. Please check help:"
  3358. display_help >&2
  3359. exit 1
  3360. fi
  3361. ;;
  3362. *)
  3363. action="$arg"
  3364. stage="action"
  3365. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3366. is_docker_compose_action=true
  3367. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3368. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3369. if [ "$DC_MATCH_MULTI" ]; then
  3370. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3371. fi
  3372. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3373. pos_args=("${pos_args[@]:1}")
  3374. # echo "USAGE: $DC_USAGE"
  3375. # echo "pos_args: ${pos_args[@]}"
  3376. # echo "MULTI: $DC_MATCH_MULTI"
  3377. # echo "SINGLE: $DC_MATCH_SINGLE"
  3378. # exit 1
  3379. else
  3380. stage="remainder"
  3381. fi
  3382. ;;
  3383. esac
  3384. ;;
  3385. "action") ## Only for docker-compose actions
  3386. case "$arg" in
  3387. --help|-h)
  3388. no_init=true ; no_hooks=true ; no_relations=true
  3389. action_opts+=("$arg")
  3390. ;;
  3391. --*|-*)
  3392. if [ "$is_docker_compose_action" ]; then
  3393. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3394. read-0 value
  3395. action_opts+=("$arg" "$value")
  3396. shift
  3397. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3398. action_opts+=("$arg")
  3399. else
  3400. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3401. docker-compose "$action" --help |
  3402. filter_docker_compose_help_message >&2
  3403. exit 1
  3404. fi
  3405. fi
  3406. ;;
  3407. *)
  3408. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3409. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3410. services_args+=("$arg")
  3411. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3412. services_args=("$arg") || exit 1
  3413. stage="remainder"
  3414. else
  3415. action_posargs+=("$arg")
  3416. ((pos_arg_ct++))
  3417. fi
  3418. ;;
  3419. esac
  3420. ;;
  3421. "remainder")
  3422. remainder_args+=("$arg")
  3423. while read-0 arg; do
  3424. remainder_args+=("$arg")
  3425. done
  3426. break 3
  3427. ;;
  3428. esac
  3429. shift
  3430. done < <(cla.normalize "$@")
  3431. export compose_contents
  3432. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3433. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3434. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3435. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3436. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3437. aexport remainder_args
  3438. ##
  3439. ## Actual code
  3440. ##
  3441. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3442. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3443. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3444. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3445. ##
  3446. ## Get services in command line.
  3447. ##
  3448. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3449. action_service=${remainder_args[0]}
  3450. if [ -z "$action_service" ]; then
  3451. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3452. display_commands_help
  3453. exit 1
  3454. fi
  3455. remainder_args=("${remainder_args[@]:1}")
  3456. if has_service_action "$action_service" "$action" >/dev/null; then
  3457. is_service_action=true
  3458. {
  3459. read-0 action_type
  3460. case "$action_type" in
  3461. "relation")
  3462. read-0 _ target_service _target_charm relation_name
  3463. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3464. ;;
  3465. "direct")
  3466. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3467. ;;
  3468. esac
  3469. } < <(has_service_action "$action_service" "$action")
  3470. services_args=("$action_service")
  3471. else
  3472. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3473. fi
  3474. else
  3475. case "$action" in
  3476. ps|up)
  3477. if [ "${#services_args[@]}" == 0 ]; then
  3478. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3479. fi
  3480. ;;
  3481. config)
  3482. services_args=("${action_posargs[@]}")
  3483. ;;
  3484. esac
  3485. fi
  3486. NO_CONSTRAINT_CHECK=True
  3487. case "$action" in
  3488. up)
  3489. NO_CONSTRAINT_CHECK=
  3490. ;;
  3491. esac
  3492. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3493. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3494. services=($(get_master_services "${services_args[@]}")) || exit 1
  3495. if [ "$action" == "up" ]; then
  3496. declare -A seen
  3497. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3498. mservice=$(get_master_service_for_service "$service")
  3499. [ "${seen[$mservice]}" ] && continue
  3500. type="$(get_service_type "$mservice")" || exit 1
  3501. ## remove run-once
  3502. [ "$type" == "run-once" ] && continue
  3503. seen[$mservice]=1
  3504. action_posargs+=("$mservice")
  3505. done
  3506. else
  3507. action_posargs+=("${services[@]}")
  3508. fi
  3509. ## Get rid of subordinates
  3510. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  3511. fi
  3512. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3513. err "Fails to compile base 'docker-compose.yml'"
  3514. exit 1
  3515. }
  3516. ##
  3517. ## Pre-action
  3518. ##
  3519. full_init=
  3520. case "$action" in
  3521. up|run)
  3522. full_init=true
  3523. post_hook=true
  3524. ;;
  3525. ""|down|restart|logs|config|ps)
  3526. full_init=
  3527. ;;
  3528. *)
  3529. if [ "$is_service_action" ]; then
  3530. full_init=true
  3531. fi
  3532. ;;
  3533. esac
  3534. if [ -n "$full_init" ]; then
  3535. ## init in order
  3536. if [[ -z "$no_init" && -z "$no_hooks" ]]; then
  3537. Section setup host resources
  3538. setup_host_resources "${services_args[@]}" || exit 1
  3539. Section initialisation
  3540. run_service_hook init "${services_args[@]}" || exit 1
  3541. fi
  3542. ## Get relations
  3543. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  3544. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3545. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3546. rebuild_relations_to_service=($rebuild_relations_to_service)
  3547. project=$(get_default_project_name) || return 1
  3548. for service in "${rebuild_relations_to_service[@]}"; do
  3549. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3550. [ -d "$dir" ] && {
  3551. debug rm -rf "$dir"
  3552. rm -rf "$dir"
  3553. }
  3554. done
  3555. done
  3556. fi
  3557. run_service_relations "${services_args[@]}" || exit 1
  3558. fi
  3559. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3560. fi
  3561. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3562. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3563. metadata=$(charm.metadata "$charm") || exit 1
  3564. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3565. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3566. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3567. fi
  3568. fi
  3569. export SERVICE_PACK="${services_args[*]}"
  3570. ##
  3571. ## Docker-compose
  3572. ##
  3573. case "$action" in
  3574. up|start|stop|build|run)
  3575. ## force daemon mode for up
  3576. if [[ "$action" == "up" ]]; then
  3577. if ! array_member action_opts -d; then
  3578. action_opts+=("-d")
  3579. fi
  3580. if ! array_member action_opts --remove-orphans; then
  3581. action_opts+=("--remove-orphans")
  3582. fi
  3583. fi
  3584. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3585. ;;
  3586. logs)
  3587. if ! array_member action_opts --tail; then ## force daemon mode for up
  3588. action_opts+=("--tail" "10")
  3589. fi
  3590. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3591. ;;
  3592. "")
  3593. launch_docker_compose "${compose_opts[@]}"
  3594. ;;
  3595. graph)
  3596. graph $SERVICE_PACK
  3597. ;;
  3598. config)
  3599. ## removing the services
  3600. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3601. ## forcing docker-compose config to output the config file to stdout and not stderr
  3602. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3603. echo "$out"
  3604. exit 1
  3605. }
  3606. echo "$out"
  3607. warn "Runtime configuration modification (from relations) are not included here."
  3608. ;;
  3609. down)
  3610. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3611. debug "Adding a default argument of '--remove-orphans'"
  3612. action_opts+=("--remove-orphans")
  3613. fi
  3614. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3615. ;;
  3616. *)
  3617. if [ "$is_service_action" ]; then
  3618. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  3619. else
  3620. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3621. fi
  3622. ;;
  3623. esac || exit 1
  3624. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  3625. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3626. fi
  3627. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3628. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3629. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  3630. fi
  3631. fi
  3632. clean_unused_docker_compose || return 1