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.

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