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.

4188 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. *)
  1457. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1458. return 1
  1459. ;;
  1460. esac
  1461. }
  1462. export -f yaml_get_interpret
  1463. options-get () {
  1464. local key="$1" out
  1465. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1466. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1467. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1468. return 1
  1469. fi
  1470. echo "$out" | yaml_get_interpret
  1471. }
  1472. export -f options-get
  1473. relation-base-compose-get () {
  1474. local key="$1" out
  1475. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1476. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1477. return 1
  1478. fi
  1479. echo "$out" | yaml_get_interpret
  1480. }
  1481. export -f relation-base-compose-get
  1482. relation-target-compose-get () {
  1483. local key="$1" out
  1484. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1485. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1486. return 1
  1487. fi
  1488. echo "$out" | yaml_get_interpret
  1489. }
  1490. export -f relation-target-compose-get
  1491. relation-set () {
  1492. local key="$1" value="$2"
  1493. if [ -z "$RELATION_DATA_FILE" ]; then
  1494. err "$FUNCNAME: relation does not seems to be correctly setup."
  1495. return 1
  1496. fi
  1497. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1498. err "$FUNCNAME: can't read relation's data." >&2
  1499. return 1
  1500. fi
  1501. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1502. }
  1503. export -f relation-set
  1504. _config_merge() {
  1505. local config_filename="$1" mixin="$2"
  1506. touch "$config_filename" &&
  1507. merge_yaml "$config_filename" "$mixin" > "$config_filename.tmp" || return 1
  1508. mv "$config_filename.tmp" "$config_filename"
  1509. }
  1510. export -f _config_merge
  1511. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1512. config-add() {
  1513. local metadata="$1"
  1514. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1515. }
  1516. export -f config-add
  1517. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1518. init-config-add() {
  1519. local metadata="$1"
  1520. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1521. <(yaml_key_val_str "services" "$metadata")
  1522. }
  1523. export -f init-config-add
  1524. docker_get_uid() {
  1525. local service="$1" user="$2" uid
  1526. uid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"") || {
  1527. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1528. return 1
  1529. }
  1530. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid'"
  1531. echo "$uid"
  1532. }
  1533. export -f docker_get_uid
  1534. docker_get_uid_gid() {
  1535. local service="$1" user="$2" group="$3" uid
  1536. uid_gid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"; id -g \"$group\"") || {
  1537. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1538. return 1
  1539. }
  1540. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid_gid'"
  1541. echo "$uid_gid"
  1542. }
  1543. export -f docker_get_uid_gid
  1544. logstdout() {
  1545. local name="$1"
  1546. sed -r 's%^%'"${name}"'> %g'
  1547. }
  1548. export -f logstdout
  1549. logstderr() {
  1550. local name="$1"
  1551. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1552. }
  1553. export -f logstderr
  1554. _run_service_relation () {
  1555. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1556. charm=$(get_service_charm "$service") || return 1
  1557. target_charm=$(get_service_charm "$target_service") || return 1
  1558. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1559. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1560. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1561. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1562. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1563. export BASE_SERVICE_NAME=$service
  1564. export BASE_CHARM_NAME=$charm
  1565. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1566. export TARGET_SERVICE_NAME=$target_service
  1567. export TARGET_CHARM_NAME=$target_charm
  1568. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1569. export RELATION_DATA_FILE
  1570. target_errlvl=0
  1571. if [ -z "$target_script_name" ]; then
  1572. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1573. else
  1574. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1575. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1576. RELATION_CONFIG="$relation_dir/config_provider"
  1577. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1578. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1579. {
  1580. (
  1581. SERVICE_NAME=$target_service
  1582. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1583. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1584. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1585. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1586. echo "$?" > "$relation_dir/target_errlvl"
  1587. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1588. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1589. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1590. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1591. "failed before outputing an errorlevel."
  1592. ((target_errlvl |= "1" ))
  1593. }
  1594. if [ -e "$RELATION_CONFIG" ]; then
  1595. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1596. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1597. rm "$RELATION_CONFIG"
  1598. ((target_errlvl |= "$?"))
  1599. fi
  1600. fi
  1601. if [ "$target_errlvl" == 0 ]; then
  1602. errlvl=0
  1603. if [ "$base_script_name" ]; then
  1604. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1605. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1606. RELATION_CONFIG="$relation_dir/config_providee"
  1607. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1608. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1609. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1610. {
  1611. (
  1612. SERVICE_NAME=$service
  1613. SERVICE_DATASTORE="$DATASTORE/$service"
  1614. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1615. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1616. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1617. echo "$?" > "$relation_dir/errlvl"
  1618. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1619. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1620. errlvl="$(cat "$relation_dir/errlvl")" || {
  1621. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1622. "failed before outputing an errorlevel."
  1623. ((errlvl |= "1" ))
  1624. }
  1625. if [ -e "$RELATION_CONFIG" ]; then
  1626. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1627. rm "$RELATION_CONFIG"
  1628. ((errlvl |= "$?" ))
  1629. fi
  1630. if [ "$errlvl" != 0 ]; then
  1631. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1632. fi
  1633. else
  1634. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1635. fi
  1636. else
  1637. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1638. fi
  1639. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1640. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1641. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1642. return 0
  1643. else
  1644. return 1
  1645. fi
  1646. }
  1647. export -f _run_service_relation
  1648. _get_compose_relations_cached () {
  1649. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1650. relation_name relation_def target_service
  1651. if [ -e "$cache_file" ]; then
  1652. #debug "$FUNCNAME: STATIC cache hit $1"
  1653. cat "$cache_file" &&
  1654. touch "$cache_file" || return 1
  1655. return 0
  1656. fi
  1657. (
  1658. set -o pipefail
  1659. if [ "$compose_service_def" ]; then
  1660. while read-0 relation_name relation_def; do
  1661. ## XXXvlab: could we use braces here instead of parenthesis ?
  1662. (
  1663. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1664. "str")
  1665. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  1666. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1667. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1668. ;;
  1669. "sequence")
  1670. while read-0 target_service; do
  1671. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1672. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1673. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1674. ;;
  1675. "struct")
  1676. while read-0 target_service relation_config; do
  1677. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1678. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  1679. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1680. ;;
  1681. esac
  1682. ) </dev/null >> "$cache_file" || return 1
  1683. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1684. fi
  1685. )
  1686. if [ "$?" != 0 ]; then
  1687. err "Error while looking for compose relations."
  1688. rm -f "$cache_file" ## no cache
  1689. return 1
  1690. fi
  1691. [ -e "$cache_file" ] && cat "$cache_file"
  1692. return 0
  1693. }
  1694. export -f _get_compose_relations_cached
  1695. get_compose_relations () {
  1696. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1697. compose_def
  1698. if [ -e "$cache_file" ]; then
  1699. #debug "$FUNCNAME: SESSION cache hit $1"
  1700. cat "$cache_file"
  1701. return 0
  1702. fi
  1703. compose_def="$(get_compose_service_def "$service")" || return 1
  1704. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1705. if [ "$?" != 0 ]; then
  1706. rm -f "$cache_file" ## no cache
  1707. return 1
  1708. fi
  1709. cat "$cache_file"
  1710. }
  1711. export -f get_compose_relations
  1712. get_service_relations () {
  1713. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1714. s rn ts rc td
  1715. if [ -e "$cache_file" ]; then
  1716. #debug "$FUNCNAME: SESSION cache hit $1"
  1717. cat "$cache_file"
  1718. return 0
  1719. fi
  1720. if [ -z "$ALL_RELATIONS" ]; then
  1721. err "Can't access global \$ALL_RELATIONS"
  1722. return 1
  1723. fi
  1724. while read-0 s rn ts rc td; do
  1725. [[ "$s" == "$service" ]] || continue
  1726. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  1727. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  1728. if [ "$?" != 0 ]; then
  1729. rm -f "$cache_file" ## no cache
  1730. return 1
  1731. fi
  1732. cat "$cache_file"
  1733. }
  1734. export -f get_service_relations
  1735. get_service_relation() {
  1736. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1737. rn ts rc td
  1738. if [ -e "$cache_file" ]; then
  1739. #debug "$FUNCNAME: SESSION cache hit $1"
  1740. cat "$cache_file"
  1741. return 0
  1742. fi
  1743. while read-0 rn ts rc td; do
  1744. [ "$relation" == "$rn" ] && {
  1745. printf "%s\0" "$ts" "$rc" "$td"
  1746. break
  1747. }
  1748. done < <(get_service_relations "$service") > "$cache_file"
  1749. if [ "$?" != 0 ]; then
  1750. rm -f "$cache_file" ## no cache
  1751. return 1
  1752. fi
  1753. cat "$cache_file"
  1754. }
  1755. export -f get_service_relation
  1756. _get_charm_metadata_uses() {
  1757. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  1758. if [ -e "$cache_file" ]; then
  1759. #debug "$FUNCNAME: SESSION cache hit $1"
  1760. cat "$cache_file" || return 1
  1761. return 0
  1762. fi
  1763. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  1764. }
  1765. export -f _get_charm_metadata_uses
  1766. _get_service_metadata() {
  1767. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1768. charm
  1769. if [ -e "$cache_file" ]; then
  1770. #debug "$FUNCNAME: SESSION cache hit $1"
  1771. cat "$cache_file"
  1772. return 0
  1773. fi
  1774. charm="$(get_service_charm "$service")" || return 1
  1775. charm.metadata "$charm" > "$cache_file"
  1776. if [ "$?" != 0 ]; then
  1777. rm -f "$cache_file" ## no cache
  1778. return 1
  1779. fi
  1780. cat "$cache_file"
  1781. }
  1782. export -f _get_service_metadata
  1783. _get_service_uses() {
  1784. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1785. metadata
  1786. if [ -e "$cache_file" ]; then
  1787. #debug "$FUNCNAME: SESSION cache hit $1"
  1788. cat "$cache_file"
  1789. return 0
  1790. fi
  1791. metadata="$(_get_service_metadata "$service")" || return 1
  1792. _get_charm_metadata_uses "$metadata" > "$cache_file"
  1793. if [ "$?" != 0 ]; then
  1794. rm -f "$cache_file" ## no cache
  1795. return 1
  1796. fi
  1797. cat "$cache_file"
  1798. }
  1799. export -f _get_service_uses
  1800. _get_services_uses() {
  1801. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1802. service rn rd
  1803. if [ -e "$cache_file" ]; then
  1804. #debug "$FUNCNAME: SESSION cache hit $1"
  1805. cat "$cache_file"
  1806. return 0
  1807. fi
  1808. for service in "$@"; do
  1809. _get_service_uses "$service" | while read-0 rn rd; do
  1810. printf "%s\0" "$service" "$rn" "$rd"
  1811. done
  1812. [ "${PIPESTATUS[0]}" == 0 ] || {
  1813. return 1
  1814. }
  1815. done > "${cache_file}.wip"
  1816. mv "${cache_file}"{.wip,} &&
  1817. cat "$cache_file" || return 1
  1818. }
  1819. export -f _get_services_uses
  1820. _get_provides_provides() {
  1821. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1822. service rn rd
  1823. if [ -e "$cache_file" ]; then
  1824. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  1825. cat "$cache_file"
  1826. return 0
  1827. fi
  1828. type=$(printf "%s" "$provides" | shyaml get-type)
  1829. case "$type" in
  1830. sequence)
  1831. while read-0 prov; do
  1832. printf "%s\0" "$prov" ""
  1833. done < <(echo "$provides" | shyaml get-values-0)
  1834. ;;
  1835. struct)
  1836. printf "%s" "$provides" | shyaml key-values-0
  1837. ;;
  1838. str)
  1839. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  1840. ;;
  1841. *)
  1842. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  1843. return 1
  1844. esac | tee "$cache_file"
  1845. return "${PIPESTATUS[0]}"
  1846. }
  1847. _get_metadata_provides() {
  1848. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1849. service rn rd
  1850. if [ -e "$cache_file" ]; then
  1851. #debug "$FUNCNAME: CACHEDIR cache hit"
  1852. cat "$cache_file"
  1853. return 0
  1854. fi
  1855. provides=$(printf "%s" "$metadata" | shyaml get-value -y -q provides "")
  1856. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  1857. _get_provides_provides "$provides" | tee "$cache_file"
  1858. return "${PIPESTATUS[0]}"
  1859. }
  1860. _get_services_provides() {
  1861. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1862. service rn rd
  1863. if [ -e "$cache_file" ]; then
  1864. #debug "$FUNCNAME: SESSION cache hit $1"
  1865. cat "$cache_file"
  1866. return 0
  1867. fi
  1868. ## YYY: replace the inner loop by a cached function
  1869. for service in "$@"; do
  1870. metadata="$(_get_service_metadata "$service")" || return 1
  1871. while read-0 rn rd; do
  1872. printf "%s\0" "$service" "$rn" "$rd"
  1873. done < <(_get_metadata_provides "$metadata")
  1874. done > "$cache_file"
  1875. if [ "$?" != 0 ]; then
  1876. rm -f "$cache_file" ## no cache
  1877. return 1
  1878. fi
  1879. cat "$cache_file"
  1880. }
  1881. export -f _get_services_provides
  1882. _get_charm_provides() {
  1883. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(charm.store_metadata_hash)"
  1884. if [ -e "$cache_file" ]; then
  1885. #debug "$FUNCNAME: SESSION cache hit"
  1886. cat "$cache_file"
  1887. return 0
  1888. fi
  1889. start="$SECONDS"
  1890. debug "Getting charm provider list..."
  1891. while read-0 charm _ realpath metadata; do
  1892. metadata="$(charm.metadata "$charm")" || continue
  1893. # echo "reading $charm" >&2
  1894. while read-0 rn rd; do
  1895. printf "%s\0" "$charm" "$rn" "$rd"
  1896. done < <(_get_metadata_provides "$metadata")
  1897. done < <(charm.ls) | tee "$cache_file"
  1898. errlvl="${PIPESTATUS[0]}"
  1899. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  1900. return "$errlvl"
  1901. }
  1902. _get_charm_providing() {
  1903. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1904. relation="$1"
  1905. if [ -e "$cache_file" ]; then
  1906. #debug "$FUNCNAME: SESSION cache hit $1"
  1907. cat "$cache_file"
  1908. return 0
  1909. fi
  1910. while read-0 charm relation_name relation_def; do
  1911. [ "$relation_name" == "$relation" ] || continue
  1912. printf "%s\0" "$charm" "$relation_def"
  1913. done < <(_get_charm_provides) > "$cache_file"
  1914. if [ "$?" != 0 ]; then
  1915. rm -f "$cache_file" ## no cache
  1916. return 1
  1917. fi
  1918. cat "$cache_file"
  1919. }
  1920. _get_services_providing() {
  1921. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1922. relation="$1"
  1923. shift ## services is "$@"
  1924. if [ -e "$cache_file" ]; then
  1925. #debug "$FUNCNAME: SESSION cache hit $1"
  1926. cat "$cache_file"
  1927. return 0
  1928. fi
  1929. while read-0 service relation_name relation_def; do
  1930. [ "$relation_name" == "$relation" ] || continue
  1931. printf "%s\0" "$service" "$relation_def"
  1932. done < <(_get_services_provides "$@") > "$cache_file"
  1933. if [ "$?" != 0 ]; then
  1934. rm -f "$cache_file" ## no cache
  1935. return 1
  1936. fi
  1937. cat "$cache_file"
  1938. }
  1939. export -f _get_services_provides
  1940. _out_new_relation_from_defs() {
  1941. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  1942. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1943. ## YYYvlab: should be seen even in no debug mode no ?
  1944. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1945. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1946. td=${td:-True}
  1947. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  1948. printf "%s\0" "$service" "$relation_name" "$ts" "$rc" "$td"
  1949. }
  1950. get_all_relations () {
  1951. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1952. services
  1953. if [ -e "${cache_file}" ]; then
  1954. #debug "$FUNCNAME: SESSION cache hit $1"
  1955. cat "${cache_file}"
  1956. return 0
  1957. fi
  1958. declare -A services
  1959. services_uses=()
  1960. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1961. _get_services_uses "$@" || return 1
  1962. array_read-0 services_uses < <(_get_services_uses "$@")
  1963. services_provides=()
  1964. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1965. _get_services_provides "$@" || return 1
  1966. array_read-0 services_provides < <(_get_services_provides "$@")
  1967. for service in "$@"; do
  1968. services[$service]=1
  1969. done
  1970. all_services=("$@")
  1971. while [ "${#all_services[@]}" != 0 ]; do
  1972. array_pop all_services service
  1973. while read-0 relation_name ts relation_config tech_dep; do
  1974. printf "%s\0" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  1975. ## adding target services ?
  1976. [ "${services[$ts]}" ] && continue
  1977. array_read-0 services_uses < <(_get_services_uses "$ts")
  1978. all_services+=("$ts")
  1979. services[$ts]=1
  1980. done < <(get_compose_relations "$service")
  1981. done > "${cache_file}.wip"
  1982. while true; do
  1983. changed=
  1984. new_services_uses=()
  1985. summon=()
  1986. required=()
  1987. recommended=()
  1988. optional=()
  1989. while [ "${#services_uses[@]}" != 0 ]; do
  1990. service="${services_uses[0]}"
  1991. relation_name="${services_uses[1]}"
  1992. relation_def="${services_uses[2]}"
  1993. services_uses=("${services_uses[@]:3}")
  1994. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1995. ## is this "use" declaration satisfied ?
  1996. found=
  1997. while read-0 s rn ts rc td; do
  1998. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  1999. if [ "$default_options" ]; then
  2000. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  2001. fi
  2002. found="$ts"
  2003. fi
  2004. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td"
  2005. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  2006. mv "${cache_file}.wip.new" "${cache_file}.wip"
  2007. if [ "$found" ]; then ## this "use" declaration was satisfied
  2008. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation " \
  2009. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  2010. continue
  2011. fi
  2012. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  2013. case "$auto" in
  2014. "pair")
  2015. service_list=()
  2016. array_read-0 service_list < <(array_keys_to_stdin services)
  2017. providers=()
  2018. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2019. if [ "${#providers[@]}" == 1 ]; then
  2020. ts="${providers[0]}"
  2021. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2022. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2023. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2024. "${providers_def[0]}" "$relation_def" \
  2025. >> "${cache_file}.wip"
  2026. ## Adding service
  2027. [ "${services[$ts]}" ] && continue
  2028. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2029. services[$ts]=1
  2030. changed=1
  2031. continue
  2032. elif [ "${#providers[@]}" -gt 1 ]; then
  2033. msg=""
  2034. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2035. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2036. "(> 1 provider)."
  2037. continue
  2038. else
  2039. : ## Do nothing
  2040. fi
  2041. ;;
  2042. "summon")
  2043. summon+=("$service" "$relation_name" "$relation_def")
  2044. ;;
  2045. ""|null|disable|disabled)
  2046. :
  2047. ;;
  2048. *)
  2049. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2050. return 1
  2051. ;;
  2052. esac
  2053. constraint=$(echo "$relation_def" | shyaml get-value constraint auto-pair 2>/dev/null)
  2054. case "$constraint" in
  2055. "required")
  2056. required+=("$service" "$relation_name" "$relation_def")
  2057. ;;
  2058. "recommended")
  2059. recommended+=("$service" "$relation_name" "$relation_def")
  2060. ;;
  2061. "optional")
  2062. optional+=("$service" "$relation_name" "$relation_def")
  2063. ;;
  2064. *)
  2065. err "Invalid ${WHITE}constraint${NORMAL} value '$contraint'."
  2066. return 1
  2067. ;;
  2068. esac
  2069. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2070. done
  2071. services_uses=("${new_services_uses[@]}")
  2072. if [ "$changed" ]; then
  2073. continue
  2074. fi
  2075. ## situation is stable
  2076. if [ "${#summon[@]}" != 0 ]; then
  2077. while [ "${#summon[@]}" != 0 ]; do
  2078. service="${summon[0]}"
  2079. relation_name="${summon[1]}"
  2080. relation_def="${summon[2]}"
  2081. summon=("${summon[@]:3}")
  2082. providers=()
  2083. providers_def=()
  2084. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2085. if [ "${#providers[@]}" == 0 ]; then
  2086. die "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2087. fi
  2088. if [ "${#providers[@]}" -gt 1 ]; then
  2089. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2090. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2091. "(> 1 provider). Choosing first."
  2092. fi
  2093. ts="${providers[0]}"
  2094. ## YYYvlab: should be seen even in no debug mode no ?
  2095. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2096. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2097. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2098. "${providers_def[0]}" "$relation_def" \
  2099. >> "${cache_file}.wip"
  2100. ## Adding service
  2101. [ "${services[$ts]}" ] && continue
  2102. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2103. services[$ts]=1
  2104. changed=1
  2105. done
  2106. continue
  2107. fi
  2108. [ "$NO_CONSTRAINT_CHECK" ] && break
  2109. if [ "${#required[@]}" != 0 ]; then
  2110. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2111. err "Required relations not satisfied"
  2112. return 1
  2113. fi
  2114. if [ "${#recommended[@]}" != 0 ]; then
  2115. ## make recommendation
  2116. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2117. fi
  2118. if [ "${#optional[@]}" != 0 ]; then
  2119. ## inform about options
  2120. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2121. fi
  2122. # if [ "${#required[@]}" != 0 ]; then
  2123. # err "Required relations not satisfied"
  2124. # return 1
  2125. # fi
  2126. if [ "${#recommended[@]}" != 0 ]; then
  2127. warn "Recommended relations not satisfied"
  2128. fi
  2129. break
  2130. done
  2131. if [ "$?" != 0 ]; then
  2132. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2133. return 1
  2134. fi
  2135. export ALL_RELATIONS="$cache_file"
  2136. mv "${cache_file}"{.wip,}
  2137. cat "$cache_file"
  2138. }
  2139. export -f get_all_relations
  2140. _display_solves() {
  2141. local array_name="$1" by_relation msg
  2142. ## inform about options
  2143. msg=""
  2144. declare -A by_relation
  2145. while read-0 service relation_name relation_def; do
  2146. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2147. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2148. if [ -z "$solves" ]; then
  2149. continue
  2150. fi
  2151. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2152. if [ "$auto" == "pair" ]; then
  2153. requirement="add provider in cluster to auto-pair"
  2154. else
  2155. requirement="add explicit relation"
  2156. fi
  2157. while read-0 name def; do
  2158. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2159. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2160. done < <(array_values_to_stdin "$array_name")
  2161. while read-0 relation_name message; do
  2162. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2163. "$relation_name" "$message" )"
  2164. done < <(array_kv_to_stdin by_relation)
  2165. if [ "$msg" ]; then
  2166. printf "%s\n" "${msg:1}"
  2167. fi
  2168. }
  2169. get_compose_relation_def() {
  2170. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2171. while read-0 relation_name target_service relation_config tech_dep; do
  2172. [ "$relation_name" == "$relation" ] || continue
  2173. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2174. done < <(get_compose_relations "$service") || return 1
  2175. }
  2176. export -f get_compose_relation_def
  2177. run_service_relations () {
  2178. local service services loaded subservices subservice
  2179. PROJECT_NAME=$(get_default_project_name) || return 1
  2180. export PROJECT_NAME
  2181. declare -A loaded
  2182. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2183. for service in $subservices; do
  2184. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2185. for subservice in $(get_service_deps "$service") "$service"; do
  2186. [ "${loaded[$subservice]}" ] && continue
  2187. export BASE_SERVICE_NAME=$service
  2188. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2189. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2190. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2191. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2192. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2193. while read-0 relation_name target_service relation_config tech_dep; do
  2194. export relation_config
  2195. export TARGET_SERVICE_NAME=$target_service
  2196. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2197. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2198. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2199. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2200. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2201. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2202. EOF
  2203. done < <(get_service_relations "$subservice") || return 1
  2204. loaded[$subservice]=1
  2205. done
  2206. done
  2207. }
  2208. export -f run_service_relations
  2209. _run_service_action_direct() {
  2210. local service="$1" action="$2" charm _dummy
  2211. shift; shift
  2212. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  2213. if read-0 _dummy || [ "$_dummy" ]; then
  2214. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2215. return 1
  2216. fi
  2217. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2218. export state_tmpdir
  2219. {
  2220. (
  2221. set +e ## Prevents unwanted leaks from parent shell
  2222. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2223. export METADATA_CONFIG=$(charm.metadata "$charm")
  2224. export SERVICE_NAME=$service
  2225. export ACTION_NAME=$action
  2226. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2227. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2228. export SERVICE_DATASTORE="$DATASTORE/$service"
  2229. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2230. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2231. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2232. echo "$?" > "$action_errlvl_file"
  2233. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2234. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2235. if ! [ -e "$action_errlvl_file" ]; then
  2236. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2237. "to output an errlvl"
  2238. return 1
  2239. fi
  2240. return "$(cat "$action_errlvl_file")"
  2241. }
  2242. export -f _run_service_action_direct
  2243. _run_service_action_relation() {
  2244. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2245. shift; shift
  2246. read-0 charm target_service target_charm relation_name relation_config || true
  2247. if read-0 _dummy || [ "$_dummy" ]; then
  2248. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2249. return 1
  2250. fi
  2251. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  2252. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2253. export state_tmpdir
  2254. {
  2255. (
  2256. set +e ## Prevents unwanted leaks from parent shell
  2257. export METADATA_CONFIG=$(charm.metadata "$charm")
  2258. export SERVICE_NAME=$service
  2259. export RELATION_TARGET_SERVICE="$target_service"
  2260. export RELATION_TARGET_CHARM="$target_charm"
  2261. export RELATION_BASE_SERVICE="$service"
  2262. export RELATION_BASE_CHARM="$charm"
  2263. export ACTION_NAME=$action
  2264. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2265. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2266. export SERVICE_DATASTORE="$DATASTORE/$service"
  2267. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2268. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2269. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2270. echo "$?" > "$action_errlvl_file"
  2271. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2272. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2273. if ! [ -e "$action_errlvl_file" ]; then
  2274. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2275. "to output an errlvl"
  2276. return 1
  2277. fi
  2278. return "$(cat "$action_errlvl_file")"
  2279. }
  2280. export -f _run_service_action_relation
  2281. get_relation_data_dir() {
  2282. local service="$1" target_service="$2" relation_name="$3" \
  2283. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2284. if [ -e "$cache_file" ]; then
  2285. # debug "$FUNCNAME: cache hit ($*)"
  2286. cat "$cache_file"
  2287. return 0
  2288. fi
  2289. project=$(get_default_project_name) || return 1
  2290. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2291. if ! [ -d "$relation_dir" ]; then
  2292. mkdir -p "$relation_dir" || return 1
  2293. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2294. fi
  2295. echo "$relation_dir" | tee "$cache_file"
  2296. }
  2297. export -f get_relation_data_dir
  2298. get_relation_data_file() {
  2299. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2300. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2301. relation_data_file="$relation_dir/data"
  2302. new=
  2303. if [ -e "$relation_data_file" ]; then
  2304. ## Has reference changed ?
  2305. new_md5=$(echo "$relation_config" | md5_compat)
  2306. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2307. new=true
  2308. fi
  2309. else
  2310. new=true
  2311. fi
  2312. if [ "$new" ]; then
  2313. echo "$relation_config" > "$relation_data_file"
  2314. chmod go-rwx "$relation_data_file" ## protecting this file
  2315. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2316. fi
  2317. echo "$relation_data_file"
  2318. }
  2319. export -f get_relation_data_file
  2320. has_service_action () {
  2321. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2322. charm target_charm relation_name target_service relation_config _tech_dep
  2323. if [ -e "$cache_file" ]; then
  2324. # debug "$FUNCNAME: cache hit ($*)"
  2325. cat "$cache_file"
  2326. return 0
  2327. fi
  2328. charm=$(get_service_charm "$service") || return 1
  2329. ## Action directly provided ?
  2330. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  2331. echo -en "direct\0$charm" | tee "$cache_file"
  2332. return 0
  2333. fi
  2334. ## Action provided by relation ?
  2335. while read-0 relation_name target_service relation_config _tech_dep; do
  2336. target_charm=$(get_service_charm "$target_service") || return 1
  2337. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  2338. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  2339. return 0
  2340. fi
  2341. done < <(get_service_relations "$service")
  2342. return 1
  2343. # master=$(get_top_master_service_for_service "$service")
  2344. # [ "$master" == "$charm" ] && return 1
  2345. # has_service_action "$master" "$action"
  2346. }
  2347. export -f has_service_action
  2348. run_service_action () {
  2349. local service="$1" action="$2"
  2350. shift ; shift
  2351. {
  2352. if ! read-0 action_type; then
  2353. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2354. info " Add an executable script to 'actions/$action' to implement action."
  2355. return 1
  2356. fi
  2357. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  2358. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2359. } < <(has_service_action "$service" "$action")
  2360. }
  2361. export -f run_service_action
  2362. get_compose_relation_config() {
  2363. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2364. if [ -e "$cache_file" ]; then
  2365. # debug "$FUNCNAME: cache hit ($*)"
  2366. cat "$cache_file"
  2367. return 0
  2368. fi
  2369. compose_service_def=$(get_compose_service_def "$service") || return 1
  2370. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2371. }
  2372. export -f get_compose_relation_config
  2373. # ## Return key-values-0
  2374. # get_compose_relation_config_for_service() {
  2375. # local service=$1 relation_name=$2 relation_config
  2376. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2377. # if ! relation_config=$(
  2378. # echo "$compose_service_relations" |
  2379. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2380. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2381. # "relation config in compose configuration."
  2382. # return 1
  2383. # fi
  2384. # if [ -z "$relation_config" ]; then
  2385. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2386. # return 1
  2387. # fi
  2388. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2389. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2390. # return 1
  2391. # fi
  2392. # }
  2393. # export -f get_compose_relation_config_for_service
  2394. _get_container_relation() {
  2395. local metadata=$1 found relation_name relation_def
  2396. found=
  2397. while read-0 relation_name relation_def; do
  2398. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2399. found="$relation_name"
  2400. break
  2401. }
  2402. done < <(_get_charm_metadata_uses "$metadata")
  2403. if [ -z "$found" ]; then
  2404. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2405. "${WHITE}scope${NORMAL} set to 'container'."
  2406. fi
  2407. printf "%s" "$found"
  2408. }
  2409. _get_master_service_for_service_cached () {
  2410. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2411. charm requires master_charm target_charm target_service service_def found
  2412. if [ -e "$cache_file" ]; then
  2413. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2414. cat "$cache_file" &&
  2415. touch "$cache_file" || return 1
  2416. return 0
  2417. fi
  2418. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2419. ## just return service name
  2420. echo "$service" | tee "$cache_file"
  2421. return 0
  2422. fi
  2423. ## Action provided by relation ?
  2424. container_relation=$(_get_container_relation "$metadata") || exit 1
  2425. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2426. if [ -z "$target_service" ]; then
  2427. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2428. "${DARKYELLOW}$service$NORMAL compose definition."
  2429. err ${FUNCNAME[@]}
  2430. return 1
  2431. fi
  2432. echo "$target_service" | tee "$cache_file"
  2433. }
  2434. export -f _get_master_service_for_service_cached
  2435. get_master_service_for_service() {
  2436. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2437. charm metadata result
  2438. if [ -e "$cache_file" ]; then
  2439. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2440. cat "$cache_file" || return 1
  2441. return 0
  2442. fi
  2443. charm=$(get_service_charm "$service") || return 1
  2444. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2445. metadata=""
  2446. warn "No charm $DARKPINK$charm$NORMAL found."
  2447. }
  2448. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2449. echo "$result" | tee "$cache_file" || return 1
  2450. }
  2451. export -f get_master_service_for_service
  2452. get_top_master_service_for_service() {
  2453. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2454. current_service
  2455. if [ -e "$cache_file" ]; then
  2456. # debug "$FUNCNAME: cache hit ($*)"
  2457. cat "$cache_file"
  2458. return 0
  2459. fi
  2460. current_service="$service"
  2461. while true; do
  2462. master_service=$(get_master_service_for_service "$current_service") || return 1
  2463. [ "$master_service" == "$current_service" ] && break
  2464. current_service="$master_service"
  2465. done
  2466. echo "$current_service" | tee "$cache_file"
  2467. return 0
  2468. }
  2469. export -f get_top_master_service_for_service
  2470. ##
  2471. ## The result is a mixin that is not always a complete valid
  2472. ## docker-compose entry (thinking of subordinates). The result
  2473. ## will be merge with master charms.
  2474. _get_docker_compose_mixin_from_metadata_cached() {
  2475. local service="$1" charm="$2" metadata="$3" \
  2476. has_build_dir="$4" \
  2477. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2478. metadata_file metadata volumes docker_compose subordinate image mixin mixins
  2479. if [ -e "$cache_file" ]; then
  2480. #debug "$FUNCNAME: STATIC cache hit $1"
  2481. cat "$cache_file" &&
  2482. touch "$cache_file" || return 1
  2483. return 0
  2484. fi
  2485. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2486. if [ "$metadata" ]; then
  2487. ## resources to volumes
  2488. volumes=$(
  2489. for resource_type in data config; do
  2490. while read-0 resource; do
  2491. eval "echo \" - \$${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2492. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2493. done
  2494. while read-0 resource; do
  2495. if [[ "$resource" == /*:/*:* ]]; then
  2496. echo " - $resource"
  2497. elif [[ "$resource" == /*:/* ]]; then
  2498. echo " - $resource:rw"
  2499. elif [[ "$resource" == /*:* ]]; then
  2500. echo " - ${resource%%:*}:$resource"
  2501. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2502. echo " - $resource:$resource:rw"
  2503. else
  2504. die "Invalid host-resource specified in 'metadata.yml'."
  2505. fi
  2506. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2507. while read-0 resource; do
  2508. dest="$(charm.get_dir "$charm")/resources$resource"
  2509. if ! [ -e "$dest" ]; then
  2510. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2511. fi
  2512. echo " - $dest:$resource:ro"
  2513. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2514. ) || return 1
  2515. if [ "$volumes" ]; then
  2516. mixins+=("volumes:"$'\n'"$volumes")
  2517. fi
  2518. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2519. if [ "$type" != "run-once" ]; then
  2520. mixins+=("restart: unless-stopped")
  2521. fi
  2522. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2523. if [ "$docker_compose" ]; then
  2524. mixins+=("$docker_compose")
  2525. fi
  2526. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2527. subordinate=true
  2528. fi
  2529. fi
  2530. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2531. [ "$image" == "None" ] && image=""
  2532. if [ "$image" ]; then
  2533. if [ "$subordinate" ]; then
  2534. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2535. return 1
  2536. fi
  2537. mixins+=("image: $image")
  2538. elif [ "$has_build_dir" ]; then
  2539. if [ "$subordinate" ]; then
  2540. err "Subordinate charm can not have a 'build' sub directory."
  2541. return 1
  2542. fi
  2543. mixins+=("build: $(charm.get_dir "$charm")/build")
  2544. fi
  2545. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2546. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2547. return 1
  2548. }
  2549. echo "$mixin" | tee "$cache_file"
  2550. }
  2551. export -f _get_docker_compose_mixin_from_metadata_cached
  2552. get_docker_compose_mixin_from_metadata() {
  2553. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2554. if [ -e "$cache_file" ]; then
  2555. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2556. cat "$cache_file"
  2557. return 0
  2558. fi
  2559. charm=$(get_service_charm "$service") || return 1
  2560. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2561. has_build_dir=
  2562. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2563. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2564. echo "$mixin" | tee "$cache_file"
  2565. }
  2566. export -f get_docker_compose_mixin_from_metadata
  2567. _save() {
  2568. local name="$1"
  2569. cat - | tee -a "$docker_compose_dir/.data/$name"
  2570. }
  2571. export -f _save
  2572. get_default_project_name() {
  2573. if [ "$DEFAULT_PROJECT_NAME" ]; then
  2574. echo "$DEFAULT_PROJECT_NAME"
  2575. return 0
  2576. fi
  2577. compose_yml_location="$(get_compose_yml_location)" || return 1
  2578. if [ "$compose_yml_location" ]; then
  2579. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2580. name="$(basename "$(dirname "$normalized_path")")"
  2581. echo "${name%%-deploy}"
  2582. return 0
  2583. fi
  2584. fi
  2585. echo "orphan"
  2586. return 0
  2587. }
  2588. export -f get_default_project_name
  2589. get_running_compose_containers() {
  2590. ## XXXvlab: docker bug: there will be a final newline anyway
  2591. docker ps --filter label="compose.service" --format='{{.ID}}'
  2592. }
  2593. export -f get_running_compose_containers
  2594. get_volumes_for_container() {
  2595. local container="$1"
  2596. docker inspect \
  2597. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2598. "$container"
  2599. }
  2600. export -f get_volumes_for_container
  2601. is_volume_used() {
  2602. local volume="$1" container_id src dst
  2603. while read -r container_id; do
  2604. while read-0 src dst; do
  2605. [[ "$src" == "$volume"/* ]] && return 0
  2606. done < <(get_volumes_for_container "$container_id")
  2607. done < <(get_running_compose_containers)
  2608. return 1
  2609. }
  2610. export -f is_volume_used
  2611. clean_unused_docker_compose() {
  2612. for f in /var/lib/compose/docker-compose/*; do
  2613. [ -e "$f" ] || continue
  2614. is_volume_used "$f" && continue
  2615. debug "Cleaning unused docker-compose ${f##*/}"
  2616. rm -rf "$f" || return 1
  2617. done
  2618. return 0
  2619. }
  2620. export -f clean_unused_docker_compose
  2621. stdin_get_hash() {
  2622. local sha
  2623. sha=$(sha256sum) || return 1
  2624. sha=${sha:0:64}
  2625. echo "$sha"
  2626. }
  2627. export -f stdin_get_hash
  2628. file_get_hash() {
  2629. stdin_get_hash < "$1" || return 1
  2630. }
  2631. export -f file_get_hash
  2632. docker_compose_store() {
  2633. local file="$1" sha
  2634. sha=$(file_get_hash "$file") || return 1
  2635. project=$(get_default_project_name) || return 1
  2636. dst="/var/lib/compose/docker-compose/$sha/$project"
  2637. mkdir -p "$dst" || return 1
  2638. cat <<EOF > "$dst/.env" || return 1
  2639. DOCKER_COMPOSE_PATH=$dst
  2640. EOF
  2641. cp "$file" "$dst/docker-compose.yml" || return 1
  2642. mkdir -p "$dst/bin" || return 1
  2643. cat <<EOF > "$dst/bin/dc" || return 1
  2644. #!/bin/bash
  2645. $(declare -f read-0)
  2646. docker_run_opts=()
  2647. while read-0 opt; do
  2648. docker_run_opts+=("\$opt")
  2649. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2650. docker_run_opts+=(
  2651. "-w" "$dst"
  2652. "--entrypoint" "/usr/local/bin/docker-compose"
  2653. )
  2654. [ -t 1 ] && {
  2655. docker_run_opts+=("-ti")
  2656. }
  2657. exec docker run --rm "\${docker_run_opts[@]}" "${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2658. EOF
  2659. chmod +x "$dst/bin/dc" || return 1
  2660. printf "%s" "$sha"
  2661. }
  2662. launch_docker_compose() {
  2663. local charm docker_compose_tmpdir docker_compose_dir
  2664. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2665. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2666. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2667. ## docker-compose will name network from the parent dir name
  2668. project=$(get_default_project_name)
  2669. mkdir -p "$docker_compose_tmpdir/$project"
  2670. docker_compose_dir="$docker_compose_tmpdir/$project"
  2671. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2672. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2673. # debug "Merging some config data in docker-compose.yml:"
  2674. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2675. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2676. fi
  2677. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2678. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2679. fi
  2680. ## XXXvlab: could be more specific and only link the needed charms
  2681. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2682. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2683. # if charm.exists "$charm"; then
  2684. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2685. # fi
  2686. # done
  2687. mkdir "$docker_compose_dir/.data"
  2688. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2689. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2690. fi
  2691. {
  2692. {
  2693. {
  2694. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2695. cd "/var/lib/compose/docker-compose/$sha/$project"
  2696. else
  2697. cd "$docker_compose_dir"
  2698. fi
  2699. if [ -f ".env" ]; then
  2700. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2701. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2702. fi
  2703. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2704. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2705. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2706. if [ "$DRY_COMPOSE_RUN" ]; then
  2707. echo docker-compose "$@"
  2708. else
  2709. docker-compose "$@"
  2710. fi
  2711. echo "$?" > "$docker_compose_dir/.data/errlvl"
  2712. } | _save stdout
  2713. } 3>&1 1>&2 2>&3 | _save stderr
  2714. } 3>&1 1>&2 2>&3
  2715. 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
  2716. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  2717. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  2718. fi
  2719. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  2720. if [ -z "$docker_compose_errlvl" ]; then
  2721. err "Something went wrong before you could gather docker-compose errorlevel."
  2722. return 1
  2723. fi
  2724. return "$docker_compose_errlvl"
  2725. }
  2726. export -f launch_docker_compose
  2727. get_compose_yml_location() {
  2728. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  2729. echo "$COMPOSE_YML_FILE"
  2730. return 0
  2731. fi
  2732. parent=$(while ! [ -f "./compose.yml" ]; do
  2733. [ "$PWD" == "/" ] && exit 0
  2734. cd ..
  2735. done; echo "$PWD"
  2736. )
  2737. if [ "$parent" ]; then
  2738. echo "$parent/compose.yml"
  2739. return 0
  2740. fi
  2741. ## XXXvlab: do we need this additional environment variable,
  2742. ## COMPOSE_YML_FILE is not sufficient ?
  2743. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  2744. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  2745. warn "No 'compose.yml' was found in current or parent dirs," \
  2746. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  2747. "(${DEFAULT_COMPOSE_FILE})"
  2748. return 0
  2749. fi
  2750. echo "$DEFAULT_COMPOSE_FILE"
  2751. return 0
  2752. fi
  2753. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  2754. return 0
  2755. }
  2756. export -f get_compose_yml_location
  2757. get_compose_yml_content() {
  2758. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  2759. if [ -e "$cache_file" ]; then
  2760. cat "$cache_file" &&
  2761. touch "$cache_file" || return 1
  2762. return 0
  2763. fi
  2764. if [ -z "$COMPOSE_YML_FILE" ]; then
  2765. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2766. fi
  2767. if [ -e "$COMPOSE_YML_FILE" ]; then
  2768. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2769. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  2770. err "Could not read '$COMPOSE_YML_FILE'."
  2771. return 1
  2772. }
  2773. else
  2774. debug "No compose file found. Using an empty one."
  2775. COMPOSE_YML_CONTENT=""
  2776. fi
  2777. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  2778. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  2779. if [ "$?" != 0 ]; then
  2780. outputed_something=
  2781. while IFS='' read -r line1 && IFS='' read -r line2; do
  2782. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2783. outputed_something=true
  2784. echo "$line1 $GRAY($line2)$NORMAL"
  2785. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2786. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2787. prefix " $GRAY|$NORMAL "
  2788. [ "$outputed_something" ] || {
  2789. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2790. echo "$output" | prefix " $GRAY|$NORMAL "
  2791. }
  2792. return 1
  2793. fi
  2794. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  2795. }
  2796. export -f get_compose_yml_content
  2797. get_default_target_services() {
  2798. local services=("$@")
  2799. if [ -z "${services[*]}" ]; then
  2800. if [ "$DEFAULT_SERVICES" ]; then
  2801. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  2802. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  2803. services="$DEFAULT_SERVICES"
  2804. else
  2805. err "No service provided."
  2806. return 1
  2807. fi
  2808. fi
  2809. echo "${services[*]}"
  2810. }
  2811. export -f get_default_target_services
  2812. get_master_services() {
  2813. local loaded master_service service
  2814. declare -A loaded
  2815. for service in "$@"; do
  2816. master_service=$(get_top_master_service_for_service "$service") || return 1
  2817. if [ "${loaded[$master_service]}" ]; then
  2818. continue
  2819. fi
  2820. echo "$master_service"
  2821. loaded["$master_service"]=1
  2822. done | nspc
  2823. return "${PIPESTATUS[0]}"
  2824. }
  2825. export -f get_master_services
  2826. get_current_docker_container_id() {
  2827. local line
  2828. line=$(cat "/proc/self/cpuset") || return 1
  2829. [[ "$line" == *docker* ]] || return 1
  2830. echo "${line##*/}"
  2831. }
  2832. export -f get_current_docker_container_id
  2833. ## if we are in a docker compose, we might want to know what is the
  2834. ## real host path of some local paths.
  2835. get_host_path() {
  2836. local path="$1"
  2837. path=$(realpath "$path") || return 1
  2838. container_id=$(get_current_docker_container_id) || {
  2839. print "%s" "$path"
  2840. return 0
  2841. }
  2842. biggest_dst=
  2843. current_src=
  2844. while read-0 src dst; do
  2845. [[ "$path" == "$dst"* ]] || continue
  2846. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  2847. biggest_dst="$dst"
  2848. current_src="$src"
  2849. fi
  2850. done < <(get_volumes_for_container "$container_id")
  2851. if [ "$current_src" ]; then
  2852. printf "%s" "$current_src"
  2853. else
  2854. return 1
  2855. fi
  2856. }
  2857. export -f get_host_path
  2858. _setup_state_dir() {
  2859. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2860. #debug "Creating temporary state directory in '$state_tmpdir'."
  2861. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  2862. # rm -rf \"$state_tmpdir\""
  2863. trap_add EXIT "rm -rf \"$state_tmpdir\""
  2864. }
  2865. get_docker_compose_help_msg() {
  2866. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2867. docker_compose_help_msg
  2868. if [ -e "$cache_file" ]; then
  2869. cat "$cache_file" &&
  2870. touch "$cache_file" || return 1
  2871. return 0
  2872. fi
  2873. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  2874. echo "$docker_compose_help_msg" |
  2875. tee "$cache_file" || return 1
  2876. }
  2877. get_docker_compose_usage() {
  2878. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2879. docker_compose_help_msg
  2880. if [ -e "$cache_file" ]; then
  2881. cat "$cache_file" &&
  2882. touch "$cache_file" || return 1
  2883. return 0
  2884. fi
  2885. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  2886. echo "$docker_compose_help_msg" |
  2887. grep -m 1 "^Usage:" -A 10000 |
  2888. egrep -m 1 "^\$" -B 10000 |
  2889. nspc |
  2890. sed -r 's/^Usage: //g' |
  2891. tee "$cache_file" || return 1
  2892. }
  2893. get_docker_compose_opts_help() {
  2894. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2895. docker_compose_help_msg
  2896. if [ -e "$cache_file" ]; then
  2897. cat "$cache_file" &&
  2898. touch "$cache_file" || return 1
  2899. return 0
  2900. fi
  2901. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2902. echo "$docker_compose_opts_help" |
  2903. grep '^Options:' -A 20000 |
  2904. tail -n +2 |
  2905. { cat ; echo; } |
  2906. egrep -m 1 "^\S*\$" -B 10000 |
  2907. head -n -1 |
  2908. tee "$cache_file" || return 1
  2909. }
  2910. get_docker_compose_commands_help() {
  2911. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2912. docker_compose_help_msg
  2913. if [ -e "$cache_file" ]; then
  2914. cat "$cache_file" &&
  2915. touch "$cache_file" || return 1
  2916. return 0
  2917. fi
  2918. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2919. echo "$docker_compose_opts_help" |
  2920. grep '^Commands:' -A 20000 |
  2921. tail -n +2 |
  2922. { cat ; echo; } |
  2923. egrep -m 1 "^\S*\$" -B 10000 |
  2924. head -n -1 |
  2925. tee "$cache_file" || return 1
  2926. }
  2927. get_docker_compose_opts_list() {
  2928. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2929. docker_compose_help_msg
  2930. if [ -e "$cache_file" ]; then
  2931. cat "$cache_file" &&
  2932. touch "$cache_file" || return 1
  2933. return 0
  2934. fi
  2935. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2936. echo "$docker_compose_opts_help" |
  2937. egrep "^\s+-" |
  2938. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2939. tee "$cache_file" || return 1
  2940. }
  2941. options_parser() {
  2942. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2943. printf "\0"
  2944. }
  2945. remove_options_in_option_help_msg() {
  2946. {
  2947. read-0 null
  2948. if [ "$null" ]; then
  2949. err "options parsing error, should start with an option line."
  2950. return 1
  2951. fi
  2952. while read-0 opt full_txt;do
  2953. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2954. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2955. for to_remove in "$@"; do
  2956. str_matches "$to_remove" $multi_opts $single_opts && {
  2957. continue 2
  2958. }
  2959. done
  2960. echo -n "$full_txt"
  2961. done
  2962. } < <(options_parser)
  2963. }
  2964. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2965. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2966. multi_opts_filter() {
  2967. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2968. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2969. tr ',' "\n" | nspc
  2970. }
  2971. single_opts_filter() {
  2972. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2973. tr ',' "\n" | nspc
  2974. }
  2975. get_docker_compose_multi_opts_list() {
  2976. local action="$1" opts_list
  2977. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2978. echo "$opts_list" | multi_opts_filter
  2979. }
  2980. get_docker_compose_single_opts_list() {
  2981. local action="$1" opts_list
  2982. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2983. echo "$opts_list" | single_opts_filter
  2984. }
  2985. display_commands_help() {
  2986. local charm_actions
  2987. echo
  2988. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2989. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2990. charm_actions_help=$(get_docker_charm_action_help) || return 1
  2991. if [ "$charm_actions_help" ]; then
  2992. echo
  2993. echo "${WHITE}Charm actions${NORMAL}:"
  2994. printf "%s\n" "$charm_actions_help" | \
  2995. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  2996. fi
  2997. }
  2998. get_docker_charm_action_help() {
  2999. local services service charm relation_name target_service relation_config \
  3000. target_charm
  3001. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3002. for service in "${services[@]}"; do
  3003. out=$(
  3004. charm=$(get_service_charm "$service") || return 1
  3005. for action in $(charm.ls_direct_actions "$charm"); do
  3006. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3007. done
  3008. while read-0 relation_name target_service _relation_config _tech_dep; do
  3009. target_charm=$(get_service_charm "$target_service") || return 1
  3010. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3011. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3012. done
  3013. done < <(get_compose_relations "$service")
  3014. )
  3015. if [ "$out" ]; then
  3016. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3017. printf "%s\n" "$out"
  3018. fi
  3019. done
  3020. }
  3021. display_help() {
  3022. print_help
  3023. echo "${WHITE}Options${NORMAL}:"
  3024. echo " -h, --help Print this message and quit"
  3025. echo " (ignoring any other options)"
  3026. echo " -V, --version Print current version and quit"
  3027. echo " (ignoring any other options)"
  3028. echo " --dirs Display data dirs and quit"
  3029. echo " (ignoring any other options)"
  3030. echo " -v, --verbose Be more verbose"
  3031. echo " -q, --quiet Be quiet"
  3032. echo " -d, --debug Print full debugging information (sets also verbose)"
  3033. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3034. echo " command line will be used."
  3035. echo " --rebuild-relations-to-service, -R SERVICE"
  3036. echo " Will rebuild all relations to given service"
  3037. echo " --add-compose-content, -Y YAML"
  3038. echo " Will merge some direct YAML with the current compose"
  3039. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3040. filter_docker_compose_help_message
  3041. display_commands_help
  3042. }
  3043. _graph_service() {
  3044. local service="$1" base="$1"
  3045. charm=$(get_service_charm "$service") || return 1
  3046. metadata=$(charm.metadata "$charm") || return 1
  3047. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3048. if [ "$subordinate" == "True" ]; then
  3049. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3050. master_charm=
  3051. while read-0 relation_name relation; do
  3052. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3053. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3054. if [ -z "$interface" ]; then
  3055. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3056. return 1
  3057. fi
  3058. ## Action provided by relation ?
  3059. target_service=
  3060. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3061. [ "$interface" == "$relation_name" ] && {
  3062. target_service="$candidate_target_service"
  3063. break
  3064. }
  3065. done < <(get_service_relations "$service")
  3066. if [ -z "$target_service" ]; then
  3067. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3068. "${DARKYELLOW}$service$NORMAL compose definition."
  3069. return 1
  3070. fi
  3071. master_service="$target_service"
  3072. master_charm=$(get_service_charm "$target_service") || return 1
  3073. break
  3074. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3075. fi
  3076. _graph_node_service "$service" "$base" "$charm"
  3077. _graph_edge_service "$service" "$subordinate" "$master_service"
  3078. }
  3079. _graph_node_service() {
  3080. local service="$1" base="$2" charm="$3"
  3081. cat <<EOF
  3082. "$(_graph_node_service_label ${service})" [
  3083. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  3084. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  3085. color = $([ "$base" ] && echo "blue" || echo "black")
  3086. fillcolor = "white"
  3087. fontname = "Courier New"
  3088. shape = "Mrecord"
  3089. label =<$(_graph_node_service_content "$service")>
  3090. ];
  3091. EOF
  3092. }
  3093. _graph_edge_service() {
  3094. local service="$1" subordinate="$2" master_service="$3"
  3095. while read-0 relation_name target_service relation_config tech_dep; do
  3096. cat <<EOF
  3097. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3098. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3099. fontsize = 16
  3100. fontcolor = "black"
  3101. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3102. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3103. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3104. arrowtail = odot
  3105. # arrowhead = dotlicurve
  3106. taillabel = "$relation_name" ];
  3107. EOF
  3108. done < <(get_service_relations "$service") || return 1
  3109. }
  3110. _graph_node_service_label() {
  3111. local service="$1"
  3112. echo "service_$service"
  3113. }
  3114. _graph_node_service_content() {
  3115. local service="$1"
  3116. charm=$(get_service_charm "$service") || return 1
  3117. cat <<EOF
  3118. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3119. <tr>
  3120. <td bgcolor="black" align="center" colspan="2">
  3121. <font color="white">$service</font>
  3122. </td>
  3123. </tr>
  3124. $(if [ "$charm" != "$service" ]; then
  3125. cat <<EOF2
  3126. <tr>
  3127. <td align="left" port="r0">charm: $charm</td>
  3128. </tr>
  3129. EOF2
  3130. fi)
  3131. </table>
  3132. EOF
  3133. }
  3134. cla_contains () {
  3135. local e
  3136. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3137. return 1
  3138. }
  3139. filter_docker_compose_help_message() {
  3140. cat - |
  3141. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3142. s/docker-compose.yml/compose.yml/g;
  3143. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3144. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3145. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3146. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3147. }
  3148. graph() {
  3149. local services=("$@")
  3150. declare -A entries
  3151. cat <<EOF
  3152. digraph g {
  3153. graph [
  3154. fontsize=30
  3155. labelloc="t"
  3156. label=""
  3157. splines=true
  3158. overlap=false
  3159. #rankdir = "LR"
  3160. ];
  3161. ratio = auto;
  3162. EOF
  3163. for target_service in "$@"; do
  3164. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3165. for service in $services; do
  3166. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3167. if cla_contains "$service" "${services[@]}"; then
  3168. base=true
  3169. else
  3170. base=
  3171. fi
  3172. _graph_service "$service" "$base"
  3173. done
  3174. done
  3175. echo "}"
  3176. }
  3177. cached_wget() {
  3178. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3179. url="$1"
  3180. if [ -e "$cache_file" ]; then
  3181. cat "$cache_file"
  3182. touch "$cache_file"
  3183. return 0
  3184. fi
  3185. wget -O- "${url}" |
  3186. tee "$cache_file"
  3187. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3188. rm "$cache_file"
  3189. die "Unable to fetch '$url'."
  3190. return 1
  3191. fi
  3192. }
  3193. export -f cached_wget
  3194. [ "$SOURCED" ] && return 0
  3195. trap_add "EXIT" clean_cache
  3196. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3197. if [ -r /etc/default/charm ]; then
  3198. . /etc/default/charm
  3199. fi
  3200. if [ -r "/etc/default/$exname" ]; then
  3201. . "/etc/default/$exname"
  3202. fi
  3203. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3204. ## userdir ? and global /etc/compose.yml ?
  3205. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3206. /etc/default/compose /etc/compose/local.conf; do
  3207. [ -e "$cfgfile" ] || continue
  3208. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3209. done
  3210. fi
  3211. _setup_state_dir
  3212. mkdir -p "$CACHEDIR" || exit 1
  3213. ##
  3214. ## Argument parsing
  3215. ##
  3216. wrap_opts=()
  3217. services=()
  3218. remainder_args=()
  3219. compose_opts=()
  3220. compose_contents=()
  3221. action_opts=()
  3222. services_args=()
  3223. pos_arg_ct=0
  3224. no_hooks=
  3225. no_init=
  3226. action=
  3227. stage="main" ## switches from 'main', to 'action', 'remainder'
  3228. is_docker_compose_action=
  3229. rebuild_relations_to_service=()
  3230. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3231. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  3232. while read-0 arg; do
  3233. case "$stage" in
  3234. "main")
  3235. case "$arg" in
  3236. --help|-h)
  3237. no_init=true ; no_hooks=true ; no_relations=true
  3238. display_help
  3239. exit 0
  3240. ;;
  3241. --verbose|-v)
  3242. export VERBOSE=true
  3243. compose_opts+=("--verbose")
  3244. ;;
  3245. --quiet|-q)
  3246. export QUIET=true
  3247. export wrap_opts+=("-q")
  3248. ;;
  3249. --version|-V)
  3250. print_version
  3251. docker-compose --version
  3252. docker --version
  3253. exit 0
  3254. ;;
  3255. -f|--file)
  3256. read-0 value
  3257. [ -e "$value" ] || die "File $value doesn't exists"
  3258. export COMPOSE_YML_FILE="$value"
  3259. shift
  3260. ;;
  3261. -p|--project-name)
  3262. read-0 value
  3263. export DEFAULT_PROJECT_NAME="$value"
  3264. compose_opts+=("--project-name $value")
  3265. shift
  3266. ;;
  3267. --no-relations)
  3268. export no_relations=true
  3269. ;;
  3270. --no-hooks)
  3271. export no_hooks=true
  3272. ;;
  3273. --no-init)
  3274. export no_init=true
  3275. ;;
  3276. --rebuild-relations-to-service|-R)
  3277. read-0 value
  3278. rebuild_relations_to_service+=("$value")
  3279. shift
  3280. ;;
  3281. --debug)
  3282. export DEBUG=true
  3283. export VERBOSE=true
  3284. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3285. ;;
  3286. --add-compose-content|-Y)
  3287. read-0 value
  3288. compose_contents+=("$value")
  3289. shift
  3290. ;;
  3291. --dirs)
  3292. echo "CACHEDIR: $CACHEDIR"
  3293. echo "VARDIR: $VARDIR"
  3294. exit 0
  3295. ;;
  3296. --dry-compose-run)
  3297. export DRY_COMPOSE_RUN=true
  3298. ;;
  3299. --*|-*)
  3300. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3301. read-0 value
  3302. compose_opts+=("$arg" "$value")
  3303. shift;
  3304. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3305. compose_opts+=("$arg")
  3306. else
  3307. err "Unknown option '$arg'. Please check help:"
  3308. display_help >&2
  3309. exit 1
  3310. fi
  3311. ;;
  3312. *)
  3313. action="$arg"
  3314. stage="action"
  3315. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3316. is_docker_compose_action=true
  3317. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3318. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3319. if [ "$DC_MATCH_MULTI" ]; then
  3320. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3321. fi
  3322. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3323. pos_args=("${pos_args[@]:1}")
  3324. # echo "USAGE: $DC_USAGE"
  3325. # echo "pos_args: ${pos_args[@]}"
  3326. # echo "MULTI: $DC_MATCH_MULTI"
  3327. # echo "SINGLE: $DC_MATCH_SINGLE"
  3328. # exit 1
  3329. else
  3330. stage="remainder"
  3331. fi
  3332. ;;
  3333. esac
  3334. ;;
  3335. "action") ## Only for docker-compose actions
  3336. case "$arg" in
  3337. --help|-h)
  3338. no_init=true ; no_hooks=true ; no_relations=true
  3339. action_opts+=("$arg")
  3340. ;;
  3341. --*|-*)
  3342. if [ "$is_docker_compose_action" ]; then
  3343. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3344. read-0 value
  3345. action_opts+=("$arg" "$value")
  3346. shift
  3347. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3348. action_opts+=("$arg")
  3349. else
  3350. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3351. docker-compose "$action" --help |
  3352. filter_docker_compose_help_message >&2
  3353. exit 1
  3354. fi
  3355. fi
  3356. ;;
  3357. *)
  3358. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3359. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3360. services_args+=("$arg")
  3361. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3362. services_args=("$arg") || exit 1
  3363. stage="remainder"
  3364. else
  3365. action_posargs+=("$arg")
  3366. ((pos_arg_ct++))
  3367. fi
  3368. ;;
  3369. esac
  3370. ;;
  3371. "remainder")
  3372. remainder_args+=("$arg")
  3373. while read-0 arg; do
  3374. remainder_args+=("$arg")
  3375. done
  3376. break 3
  3377. ;;
  3378. esac
  3379. shift
  3380. done < <(cla.normalize "$@")
  3381. export compose_contents
  3382. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3383. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3384. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3385. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3386. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3387. aexport remainder_args
  3388. ##
  3389. ## Actual code
  3390. ##
  3391. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3392. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3393. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3394. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3395. ##
  3396. ## Get services in command line.
  3397. ##
  3398. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3399. action_service=${remainder_args[0]}
  3400. if [ -z "$action_service" ]; then
  3401. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3402. display_commands_help
  3403. exit 1
  3404. fi
  3405. remainder_args=("${remainder_args[@]:1}")
  3406. if has_service_action "$action_service" "$action" >/dev/null; then
  3407. is_service_action=true
  3408. {
  3409. read-0 action_type
  3410. case "$action_type" in
  3411. "relation")
  3412. read-0 _ target_service _target_charm relation_name
  3413. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3414. ;;
  3415. "direct")
  3416. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3417. ;;
  3418. esac
  3419. } < <(has_service_action "$action_service" "$action")
  3420. services_args=("$action_service")
  3421. else
  3422. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3423. fi
  3424. else
  3425. case "$action" in
  3426. ps|up)
  3427. if [ "${#services_args[@]}" == 0 ]; then
  3428. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3429. fi
  3430. ;;
  3431. config)
  3432. services_args=("${action_posargs[@]}")
  3433. ;;
  3434. esac
  3435. fi
  3436. NO_CONSTRAINT_CHECK=True
  3437. case "$action" in
  3438. up)
  3439. NO_CONSTRAINT_CHECK=
  3440. ;;
  3441. esac
  3442. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3443. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3444. services=($(get_master_services "${services_args[@]}")) || exit 1
  3445. if [ "$action" == "up" ]; then
  3446. declare -A seen
  3447. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3448. mservice=$(get_master_service_for_service "$service")
  3449. [ "${seen[$mservice]}" ] && continue
  3450. type="$(get_service_type "$mservice")" || exit 1
  3451. ## remove run-once
  3452. [ "$type" == "run-once" ] && continue
  3453. seen[$mservice]=1
  3454. action_posargs+=("$mservice")
  3455. done
  3456. else
  3457. action_posargs+=("${services[@]}")
  3458. fi
  3459. fi
  3460. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3461. err "Fails to compile base 'docker-compose.yml'"
  3462. exit 1
  3463. }
  3464. ##
  3465. ## Pre-action
  3466. ##
  3467. full_init=
  3468. case "$action" in
  3469. up|run)
  3470. full_init=true
  3471. post_hook=true
  3472. ;;
  3473. ""|down|restart|logs|config|ps)
  3474. full_init=
  3475. ;;
  3476. *)
  3477. if [ "$is_service_action" ]; then
  3478. full_init=true
  3479. fi
  3480. ;;
  3481. esac
  3482. if [ "$full_init" ]; then
  3483. ## init in order
  3484. if [ -z "$no_init" ]; then
  3485. Section setup host resources
  3486. setup_host_resources "${services_args[@]}" || exit 1
  3487. Section initialisation
  3488. run_service_hook init "${services_args[@]}" || exit 1
  3489. fi
  3490. ## Get relations
  3491. if [ -z "$no_relations" ]; then
  3492. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3493. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3494. rebuild_relations_to_service=($rebuild_relations_to_service)
  3495. project=$(get_default_project_name) || return 1
  3496. for service in "${rebuild_relations_to_service[@]}"; do
  3497. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3498. [ -d "$dir" ] && {
  3499. debug rm -rf "$dir"
  3500. rm -rf "$dir"
  3501. }
  3502. done
  3503. done
  3504. fi
  3505. run_service_relations "${services_args[@]}" || exit 1
  3506. fi
  3507. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3508. fi
  3509. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3510. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3511. metadata=$(charm.metadata "$charm") || exit 1
  3512. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3513. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3514. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3515. fi
  3516. fi
  3517. export SERVICE_PACK="${services_args[*]}"
  3518. ##
  3519. ## Docker-compose
  3520. ##
  3521. case "$action" in
  3522. up|start|stop|build|run)
  3523. ## force daemon mode for up
  3524. if [[ "$action" == "up" ]]; then
  3525. if ! array_member action_opts -d; then
  3526. action_opts+=("-d")
  3527. fi
  3528. if ! array_member action_opts --remove-orphans; then
  3529. action_opts+=("--remove-orphans")
  3530. fi
  3531. fi
  3532. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3533. ;;
  3534. logs)
  3535. if ! array_member action_opts --tail; then ## force daemon mode for up
  3536. action_opts+=("--tail" "10")
  3537. fi
  3538. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3539. ;;
  3540. "")
  3541. launch_docker_compose "${compose_opts[@]}"
  3542. ;;
  3543. graph)
  3544. graph $SERVICE_PACK
  3545. ;;
  3546. config)
  3547. ## removing the services
  3548. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3549. ## forcing docker-compose config to output the config file to stdout and not stderr
  3550. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3551. echo "$out"
  3552. exit 1
  3553. }
  3554. echo "$out"
  3555. warn "Runtime configuration modification (from relations) are not included here."
  3556. ;;
  3557. down)
  3558. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3559. debug "Adding a default argument of '--remove-orphans'"
  3560. action_opts+=("--remove-orphans")
  3561. fi
  3562. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3563. ;;
  3564. *)
  3565. if [ "$is_service_action" ]; then
  3566. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  3567. else
  3568. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3569. fi
  3570. ;;
  3571. esac || exit 1
  3572. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  3573. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3574. fi
  3575. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3576. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3577. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  3578. fi
  3579. fi
  3580. clean_unused_docker_compose || return 1