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.

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