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.

4195 lines
138 KiB

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