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.

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