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.

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