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.

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