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.

4640 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. auto=${auto:-pair}
  2188. case "$auto" in
  2189. "pair"|"summon")
  2190. service_list=()
  2191. array_read-0 service_list < <(array_keys_to_stdin services)
  2192. providers=()
  2193. providers_def=()
  2194. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  2195. if [ "${#providers[@]}" == 1 ]; then
  2196. ts="${providers[0]}"
  2197. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  2198. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2199. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2200. "${providers_def[0]}" "$relation_def" \
  2201. >> "${cache_file}.wip"
  2202. ## Adding service
  2203. [ "${services[$ts]}" ] && continue
  2204. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2205. services[$ts]=1
  2206. changed=1
  2207. continue
  2208. elif [ "${#providers[@]}" -gt 1 ]; then
  2209. msg=""
  2210. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  2211. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2212. "(> 1 provider)."
  2213. continue
  2214. else
  2215. if [ "$auto" == "summon" ]; then
  2216. summon+=("$service" "$relation_name" "$relation_def")
  2217. fi
  2218. fi
  2219. ;;
  2220. null|disable|disabled)
  2221. :
  2222. ;;
  2223. *)
  2224. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  2225. return 1
  2226. ;;
  2227. esac
  2228. constraint=$(echo "$relation_def" | shyaml get-value constraint 2>/dev/null)
  2229. constraint=${constraint:-optional}
  2230. case "$constraint" in
  2231. "required")
  2232. required+=("$service" "$relation_name" "$relation_def")
  2233. ;;
  2234. "recommended")
  2235. recommended+=("$service" "$relation_name" "$relation_def")
  2236. ;;
  2237. "optional")
  2238. optional+=("$service" "$relation_name" "$relation_def")
  2239. ;;
  2240. *)
  2241. err "Invalid ${WHITE}constraint${NORMAL} value '$constraint'."
  2242. return 1
  2243. ;;
  2244. esac
  2245. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2246. done
  2247. services_uses=("${new_services_uses[@]}")
  2248. if [ "$changed" ]; then
  2249. continue
  2250. fi
  2251. ## situation is stable
  2252. if [ "${#summon[@]}" != 0 ]; then
  2253. declare -A summon_requeued=()
  2254. while [ "${#summon[@]}" != 0 ]; do
  2255. service="${summon[0]}"
  2256. relation_name="${summon[1]}"
  2257. relation_def="${summon[2]}"
  2258. summon=("${summon[@]:3}")
  2259. providers=()
  2260. providers_def=()
  2261. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2262. if [ "${#providers[@]}" == 0 ]; then
  2263. err "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2264. return 1
  2265. fi
  2266. if [ "${#providers[@]}" -gt 1 ]; then
  2267. if [ -z "${summon_requeued[$service/$relation_name]}" ]; then
  2268. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2269. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2270. "(> 1 provider). Requeing."
  2271. summon+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2272. summon_requeued["$service/$relation_name"]=1
  2273. continue
  2274. else
  2275. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2276. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2277. "(> 1 provider). Choosing first."
  2278. fi
  2279. fi
  2280. ts="${providers[0]}"
  2281. ## YYYvlab: should be seen even in no debug mode no ?
  2282. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2283. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2284. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2285. "${providers_def[0]}" "$relation_def" \
  2286. >> "${cache_file}.wip"
  2287. ## Adding service
  2288. [ "${services[$ts]}" ] && continue
  2289. array_read-0 services_uses < <(_get_services_uses "$ts")
  2290. services[$ts]=1
  2291. changed=1
  2292. continue 2
  2293. done
  2294. continue
  2295. fi
  2296. [ "$NO_CONSTRAINT_CHECK" ] && break
  2297. if [ "${#required[@]}" != 0 ]; then
  2298. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2299. err "Required relations not satisfied"
  2300. return 1
  2301. fi
  2302. if [ "${#recommended[@]}" != 0 ]; then
  2303. ## make recommendation
  2304. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2305. fi
  2306. if [ -z "$QUIET" ]; then
  2307. if [ "${#optional[@]}" != 0 ]; then
  2308. ## inform about options
  2309. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2310. fi
  2311. fi
  2312. # if [ "${#required[@]}" != 0 ]; then
  2313. # err "Required relations not satisfied"
  2314. # return 1
  2315. # fi
  2316. if [ "${#recommended[@]}" != 0 ]; then
  2317. warn "Recommended relations not satisfied"
  2318. fi
  2319. break
  2320. done
  2321. if [ "$?" != 0 ]; then
  2322. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2323. return 1
  2324. fi
  2325. ##
  2326. ## Sort relations thanks to uses =metadata.yml= relations.
  2327. ##
  2328. mv "${cache_file}.wip"{,.in} &&
  2329. rm -f "${cache_file}.wip.final" &&
  2330. touch "${cache_file}.wip.final" || {
  2331. err "Unexpected error when mangling cache files."
  2332. return 1
  2333. }
  2334. declare -A relation_done=()
  2335. while true; do
  2336. had_remaining_relation=
  2337. had_new_relation=
  2338. while read-0 p s rn ts rc td; do
  2339. if [ -z "$p" ] || [ "$p" == "," ]; then
  2340. relation_done["$s:$rn"]=1
  2341. # printf " .. %-30s %-30s %-30s\n" "--" "$s" "$rn" >&2
  2342. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.final"
  2343. had_new_relation=1
  2344. else
  2345. # printf " !! %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2346. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2347. had_remaining_relation=1
  2348. fi
  2349. done < "${cache_file}.wip.in"
  2350. [ -z "$had_remaining_relation" ] && break
  2351. mv "${cache_file}.wip."{out,in}
  2352. while read-0 p s rn ts rc td; do
  2353. for rel in "${!relation_done[@]}"; do
  2354. p="${p//,$rel,/,}"
  2355. done
  2356. # printf " CC %-30s %-30s %-30s\n" "$p" "$s" "$rn" >&2
  2357. if [ -z "$had_new_relation" ]; then
  2358. err "${DARKYELLOW}$s${NORMAL} --${DARKBLUE}$rn${NORMAL}--> ${DARKYELLOW}$ts${NORMAL} missing required ${WHITE}after${NORMAL} relations:"
  2359. for rel in ${p//,/ }; do
  2360. rel_s=${rel%%:*}
  2361. rel_r=${rel##*:}
  2362. echo " - ${DARKYELLOW}$rel_s${NORMAL} --${DARKBLUE}$rel_r${NORMAL}--> ${DARKGRAY}*${NORMAL}" >&2
  2363. done
  2364. else
  2365. printf "%s\0" "$p" "$s" "$rn" "$ts" "$rc" "$td" >> "${cache_file}.wip.out"
  2366. fi
  2367. done < "${cache_file}.wip.in"
  2368. if [ -z "$had_new_relation" ]; then
  2369. rm -f "${cache_file}"{,.wip{,new,in,out,final}} ## no cache
  2370. return 1
  2371. fi
  2372. mv "${cache_file}.wip."{out,in}
  2373. done
  2374. export ALL_RELATIONS="$cache_file"
  2375. mv "${cache_file}"{.wip.final,} || return 1
  2376. cat "$cache_file"
  2377. }
  2378. export -f get_all_relations
  2379. _display_solves() {
  2380. local array_name="$1" by_relation msg
  2381. ## inform about options
  2382. msg=""
  2383. declare -A by_relation
  2384. while read-0 service relation_name relation_def; do
  2385. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2386. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2387. if [ -z "$solves" ]; then
  2388. continue
  2389. fi
  2390. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2391. if [ "$auto" == "pair" ]; then
  2392. requirement="add provider in cluster to auto-pair"
  2393. else
  2394. requirement="add explicit relation"
  2395. fi
  2396. while read-0 name def; do
  2397. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2398. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2399. done < <(array_values_to_stdin "$array_name")
  2400. while read-0 relation_name message; do
  2401. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2402. "$relation_name" "$message" )"
  2403. done < <(array_kv_to_stdin by_relation)
  2404. if [ "$msg" ]; then
  2405. printf "%s\n" "${msg:1}"
  2406. fi
  2407. }
  2408. get_compose_relation_def() {
  2409. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2410. while read-0 relation_name target_service relation_config tech_dep; do
  2411. [ "$relation_name" == "$relation" ] || continue
  2412. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2413. done < <(get_compose_relations "$service") || return 1
  2414. }
  2415. export -f get_compose_relation_def
  2416. run_service_relations () {
  2417. local service services loaded subservices subservice
  2418. PROJECT_NAME=$(get_default_project_name) || return 1
  2419. export PROJECT_NAME
  2420. declare -A loaded
  2421. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2422. for service in $subservices; do
  2423. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2424. for subservice in $(get_service_deps "$service") "$service"; do
  2425. [ "${loaded[$subservice]}" ] && continue
  2426. export BASE_SERVICE_NAME=$service
  2427. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2428. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2429. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2430. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2431. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2432. while read-0 relation_name target_service relation_config tech_dep; do
  2433. export relation_config
  2434. export TARGET_SERVICE_NAME=$target_service
  2435. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2436. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2437. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2438. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2439. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2440. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2441. EOF
  2442. done < <(get_service_relations "$subservice") || return 1
  2443. loaded[$subservice]=1
  2444. done
  2445. done
  2446. }
  2447. export -f run_service_relations
  2448. _run_service_action_direct() {
  2449. local service="$1" action="$2" charm _dummy project_name
  2450. shift; shift
  2451. read-0 charm action_script_path || true ## against 'set -e' that could be setup in parent scripts
  2452. if read-0 _dummy || [ "$_dummy" ]; then
  2453. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2454. return 1
  2455. fi
  2456. project_name=$(get_default_project_name) || return 1
  2457. export PROJECT_NAME="$project_name"
  2458. export state_tmpdir
  2459. (
  2460. set +e ## Prevents unwanted leaks from parent shell
  2461. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2462. export METADATA_CONFIG=$(charm.metadata "$charm")
  2463. export SERVICE_NAME=$service
  2464. export ACTION_NAME=$action
  2465. export ACTION_SCRIPT_PATH="$action_script_path"
  2466. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2467. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2468. export SERVICE_DATASTORE="$DATASTORE/$service"
  2469. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2470. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2471. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2472. ) 0<&6 ## inject general stdin
  2473. }
  2474. export -f _run_service_action_direct
  2475. _run_service_action_relation() {
  2476. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2477. shift; shift
  2478. read-0 charm target_service target_charm relation_name relation_config action_script_path || true
  2479. if read-0 _dummy || [ "$_dummy" ]; then
  2480. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2481. return 1
  2482. fi
  2483. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2484. export state_tmpdir
  2485. (
  2486. set +e ## Prevents unwanted leaks from parent shell
  2487. export METADATA_CONFIG=$(charm.metadata "$charm")
  2488. export SERVICE_NAME=$service
  2489. export RELATION_TARGET_SERVICE="$target_service"
  2490. export RELATION_TARGET_CHARM="$target_charm"
  2491. export RELATION_BASE_SERVICE="$service"
  2492. export RELATION_BASE_CHARM="$charm"
  2493. export ACTION_NAME=$action
  2494. export ACTION_SCRIPT_PATH="$action_script_path"
  2495. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2496. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2497. export SERVICE_DATASTORE="$DATASTORE/$service"
  2498. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2499. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2500. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2501. ) 0<&6 ## inject general stdin
  2502. }
  2503. export -f _run_service_action_relation
  2504. get_relation_data_dir() {
  2505. local service="$1" target_service="$2" relation_name="$3" \
  2506. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2507. if [ -e "$cache_file" ]; then
  2508. # debug "$FUNCNAME: cache hit ($*)"
  2509. cat "$cache_file"
  2510. return 0
  2511. fi
  2512. local project relation_dir
  2513. project=${PROJECT_NAME}
  2514. if [ -z "$project" ]; then
  2515. project=$(get_default_project_name) || return 1
  2516. fi
  2517. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2518. if ! [ -d "$relation_dir" ]; then
  2519. mkdir -p "$relation_dir" || return 1
  2520. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2521. fi
  2522. echo "$relation_dir" | tee "$cache_file"
  2523. }
  2524. export -f get_relation_data_dir
  2525. get_relation_data_file() {
  2526. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2527. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2528. relation_data_file="$relation_dir/data"
  2529. new=
  2530. if [ -e "$relation_data_file" ]; then
  2531. ## Has reference changed ?
  2532. new_md5=$(e "$relation_config" | md5_compat)
  2533. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2534. new=true
  2535. fi
  2536. else
  2537. new=true
  2538. fi
  2539. if [ "$new" ]; then
  2540. e "$relation_config" > "$relation_data_file"
  2541. chmod go-rwx "$relation_data_file" ## protecting this file
  2542. e "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2543. fi
  2544. echo "$relation_data_file"
  2545. }
  2546. export -f get_relation_data_file
  2547. has_service_action () {
  2548. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2549. charm target_charm relation_name target_service relation_config _tech_dep \
  2550. path
  2551. if [ -e "$cache_file" ]; then
  2552. # debug "$FUNCNAME: cache hit ($*)"
  2553. cat "$cache_file"
  2554. return 0
  2555. fi
  2556. charm=$(get_service_charm "$service") || return 1
  2557. ## Action directly provided ?
  2558. if path=$(charm.has_direct_action "$charm" "$action"); then
  2559. p0 "direct" "$charm" "$path" | tee "$cache_file"
  2560. return 0
  2561. fi
  2562. ## Action provided by relation ?
  2563. while read-0 relation_name target_service relation_config _tech_dep; do
  2564. target_charm=$(get_service_charm "$target_service") || return 1
  2565. if path=$(charm.has_relation_action "$target_charm" "$relation_name" "$action"); then
  2566. p0 "relation" "$charm" "$target_service" "$target_charm" "$relation_name" "$relation_config" "$path" | tee "$cache_file"
  2567. return 0
  2568. fi
  2569. done < <(get_service_relations "$service")
  2570. return 1
  2571. # master=$(get_top_master_service_for_service "$service")
  2572. # [ "$master" == "$charm" ] && return 1
  2573. # has_service_action "$master" "$action"
  2574. }
  2575. export -f has_service_action
  2576. run_service_action () {
  2577. local service="$1" action="$2" errlvl
  2578. shift ; shift
  2579. exec 6<&0 ## saving stdin
  2580. {
  2581. if ! read-0 action_type; then
  2582. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2583. info " Add an executable script to 'actions/$action' to implement action."
  2584. return 1
  2585. fi
  2586. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2587. errlvl="$?"
  2588. } < <(has_service_action "$service" "$action")
  2589. exec 0<&6 6<&- ## restoring stdin
  2590. return "$errlvl"
  2591. }
  2592. export -f run_service_action
  2593. get_compose_relation_config() {
  2594. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2595. if [ -e "$cache_file" ]; then
  2596. # debug "$FUNCNAME: cache hit ($*)"
  2597. cat "$cache_file"
  2598. return 0
  2599. fi
  2600. compose_service_def=$(get_compose_service_def "$service") || return 1
  2601. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2602. }
  2603. export -f get_compose_relation_config
  2604. # ## Return key-values-0
  2605. # get_compose_relation_config_for_service() {
  2606. # local service=$1 relation_name=$2 relation_config
  2607. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2608. # if ! relation_config=$(
  2609. # echo "$compose_service_relations" |
  2610. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2611. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2612. # "relation config in compose configuration."
  2613. # return 1
  2614. # fi
  2615. # if [ -z "$relation_config" ]; then
  2616. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2617. # return 1
  2618. # fi
  2619. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2620. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2621. # return 1
  2622. # fi
  2623. # }
  2624. # export -f get_compose_relation_config_for_service
  2625. _get_container_relation() {
  2626. local metadata=$1 found relation_name relation_def
  2627. found=
  2628. while read-0 relation_name relation_def; do
  2629. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2630. found="$relation_name"
  2631. break
  2632. }
  2633. done < <(_get_charm_metadata_uses "$metadata")
  2634. if [ -z "$found" ]; then
  2635. err "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2636. "${WHITE}scope${NORMAL} set to 'container'."
  2637. return 1
  2638. fi
  2639. printf "%s" "$found"
  2640. }
  2641. _get_master_service_for_service_cached () {
  2642. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2643. charm requires master_charm target_charm target_service service_def found
  2644. if [ -e "$cache_file" ]; then
  2645. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2646. cat "$cache_file" &&
  2647. touch "$cache_file" || return 1
  2648. return 0
  2649. fi
  2650. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2651. ## just return service name
  2652. echo "$service" | tee "$cache_file"
  2653. return 0
  2654. fi
  2655. ## Action provided by relation ?
  2656. container_relation=$(_get_container_relation "$metadata") || return 1
  2657. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2658. if [ -z "$target_service" ]; then
  2659. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2660. "${DARKYELLOW}$service$NORMAL compose definition."
  2661. err ${FUNCNAME[@]}
  2662. return 1
  2663. fi
  2664. echo "$target_service" | tee "$cache_file"
  2665. }
  2666. export -f _get_master_service_for_service_cached
  2667. get_master_service_for_service() {
  2668. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2669. charm metadata result
  2670. if [ -e "$cache_file" ]; then
  2671. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2672. cat "$cache_file" || return 1
  2673. return 0
  2674. fi
  2675. charm=$(get_service_charm "$service") || return 1
  2676. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2677. metadata=""
  2678. warn "No charm $DARKPINK$charm$NORMAL found."
  2679. }
  2680. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2681. echo "$result" | tee "$cache_file" || return 1
  2682. }
  2683. export -f get_master_service_for_service
  2684. get_top_master_service_for_service() {
  2685. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2686. current_service
  2687. if [ -e "$cache_file" ]; then
  2688. # debug "$FUNCNAME: cache hit ($*)"
  2689. cat "$cache_file"
  2690. return 0
  2691. fi
  2692. current_service="$service"
  2693. while true; do
  2694. master_service=$(get_master_service_for_service "$current_service") || return 1
  2695. [ "$master_service" == "$current_service" ] && break
  2696. current_service="$master_service"
  2697. done
  2698. echo "$current_service" | tee "$cache_file"
  2699. return 0
  2700. }
  2701. export -f get_top_master_service_for_service
  2702. ##
  2703. ## The result is a mixin that is not always a complete valid
  2704. ## docker-compose entry (thinking of subordinates). The result
  2705. ## will be merge with master charms.
  2706. _get_docker_compose_mixin_from_metadata_cached() {
  2707. local service="$1" charm="$2" metadata="$3" \
  2708. has_build_dir="$4" \
  2709. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2710. metadata_file metadata volumes docker_compose subordinate image mixin mixins
  2711. if [ -e "$cache_file" ]; then
  2712. #debug "$FUNCNAME: STATIC cache hit $1"
  2713. cat "$cache_file" &&
  2714. touch "$cache_file" || return 1
  2715. return 0
  2716. fi
  2717. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2718. if [ "$metadata" ]; then
  2719. ## resources to volumes
  2720. volumes=$(
  2721. for resource_type in data config; do
  2722. while read-0 resource; do
  2723. eval "echo \" - \$HOST_${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2724. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2725. done
  2726. while read-0 resource; do
  2727. if [[ "$resource" == /*:/*:* ]]; then
  2728. echo " - $resource"
  2729. elif [[ "$resource" == /*:/* ]]; then
  2730. echo " - $resource:rw"
  2731. elif [[ "$resource" == /*:* ]]; then
  2732. echo " - ${resource%%:*}:$resource"
  2733. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2734. echo " - $resource:$resource:rw"
  2735. else
  2736. die "Invalid host-resource specified in 'metadata.yml'."
  2737. fi
  2738. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2739. while read-0 resource; do
  2740. dest="$(charm.get_dir "$charm")/resources$resource"
  2741. if ! [ -e "$dest" ]; then
  2742. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2743. fi
  2744. echo " - $dest:$resource:ro"
  2745. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2746. ) || return 1
  2747. if [ "$volumes" ]; then
  2748. mixins+=("volumes:"$'\n'"$volumes")
  2749. fi
  2750. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2751. if [ "$type" != "run-once" ]; then
  2752. mixins+=("restart: unless-stopped")
  2753. fi
  2754. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2755. if [ "$docker_compose" ]; then
  2756. mixins+=("$docker_compose")
  2757. fi
  2758. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2759. subordinate=true
  2760. fi
  2761. fi
  2762. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2763. [ "$image" == "None" ] && image=""
  2764. if [ -n "$image" ]; then
  2765. if [ -n "$subordinate" ]; then
  2766. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2767. return 1
  2768. fi
  2769. mixins+=("image: $image")
  2770. elif [ "$has_build_dir" ]; then
  2771. if [ "$subordinate" ]; then
  2772. err "Subordinate charm can not have a 'build' sub directory."
  2773. return 1
  2774. fi
  2775. mixins+=("build: $(charm.get_dir "$charm")/build")
  2776. fi
  2777. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2778. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2779. return 1
  2780. }
  2781. echo "$mixin" | tee "$cache_file"
  2782. }
  2783. export -f _get_docker_compose_mixin_from_metadata_cached
  2784. get_docker_compose_mixin_from_metadata() {
  2785. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2786. if [ -e "$cache_file" ]; then
  2787. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2788. cat "$cache_file"
  2789. return 0
  2790. fi
  2791. charm=$(get_service_charm "$service") || return 1
  2792. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2793. has_build_dir=
  2794. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2795. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2796. echo "$mixin" | tee "$cache_file"
  2797. }
  2798. export -f get_docker_compose_mixin_from_metadata
  2799. _save() {
  2800. local name="$1"
  2801. cat - | tee -a "$docker_compose_dir/.data/$name"
  2802. }
  2803. export -f _save
  2804. get_default_project_name() {
  2805. if [ -n "$DEFAULT_PROJECT_NAME" ]; then
  2806. echo "$DEFAULT_PROJECT_NAME"
  2807. return 0
  2808. fi
  2809. local normalized_path compose_yml_location name
  2810. compose_yml_location="$(get_compose_yml_location)" || return 1
  2811. if [ -n "$compose_yml_location" ]; then
  2812. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2813. name="${normalized_path%/*}" ## dirname
  2814. name="${name##*/}" ## basename
  2815. name="${name%%-deploy}" ## remove any '-deploy'
  2816. name="${name,,}" ## lowercase
  2817. e "$name"
  2818. return 0
  2819. fi
  2820. fi
  2821. echo "orphan"
  2822. return 0
  2823. }
  2824. export -f get_default_project_name
  2825. get_running_compose_containers() {
  2826. ## XXXvlab: docker bug: there will be a final newline anyway
  2827. docker ps --filter label="compose.service" --format='{{.ID}}'
  2828. }
  2829. export -f get_running_compose_containers
  2830. get_healthy_container_ip_for_service () {
  2831. local service="$1" port="$2" timeout=${3:-60}
  2832. local containers container container_network container_ip
  2833. containers="$(get_running_containers_for_service "$service")"
  2834. if [ -z "$containers" ]; then
  2835. err "No containers running for service $DARKYELLOW$service$NORMAL."
  2836. return 1
  2837. fi
  2838. ## XXXvlab: taking first container is probably not a good idea
  2839. container="$(echo "$containers" | head -n 1)"
  2840. ## XXXvlab: taking first ip is probably not a good idea
  2841. read-0 container_network container_ip < <(get_container_network_ip "$container")
  2842. if [ -z "$container_ip" ]; then
  2843. err "Can't get container's IP. You should check health of" \
  2844. "${DARKYELLOW}$service${NORMAL}'s container."
  2845. return 1
  2846. fi
  2847. wait_for_tcp_port "$container_network" "$container_ip:$port" "$timeout" || {
  2848. err "TCP port of ${DARKYELLOW}$service${NORMAL}'s container doesn't seem open"
  2849. echo " Please check that container is healthy. Here are last logs:" >&2
  2850. docker logs "$container" --tail=10 | prefix " ${GRAY}|${NORMAL} " >&2
  2851. return 1
  2852. }
  2853. info "Host/Port ${container_ip}:${port} checked ${GREEN}open${NORMAL}."
  2854. echo "$container_network:$container_ip"
  2855. }
  2856. export -f get_healthy_container_ip_for_service
  2857. switch_to_relation_service() {
  2858. local relation="$1"
  2859. ## XXXvlab: can't get real config here
  2860. if ! read-0 ts _ _ < <(get_service_relation "$SERVICE_NAME" "$relation"); then
  2861. err "Couldn't find relation ${DARKCYAN}$relation${NORMAL}."
  2862. return 1
  2863. fi
  2864. export SERVICE_NAME="$ts"
  2865. export SERVICE_DATASTORE="$DATASTORE/$SERVICE_NAME"
  2866. DOCKER_BASE_IMAGE=$(service_base_docker_image "$SERVICE_NAME")
  2867. export DOCKER_BASE_IMAGE
  2868. target_charm=$(get_service_charm "$ts") || return 1
  2869. target_charm_path=$(charm.get_dir "$target_charm") || return 1
  2870. cd "$target_charm_path"
  2871. }
  2872. export -f switch_to_relation_service
  2873. get_volumes_for_container() {
  2874. local container="$1"
  2875. docker inspect \
  2876. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2877. "$container"
  2878. }
  2879. export -f get_volumes_for_container
  2880. is_volume_used() {
  2881. local volume="$1" container_id src dst
  2882. while read -r container_id; do
  2883. while read-0 src dst; do
  2884. [[ "$src/" == "$volume"/* ]] && return 0
  2885. done < <(get_volumes_for_container "$container_id")
  2886. done < <(get_running_compose_containers)
  2887. return 1
  2888. }
  2889. export -f is_volume_used
  2890. clean_unused_docker_compose() {
  2891. for f in /var/lib/compose/docker-compose/*; do
  2892. [ -e "$f" ] || continue
  2893. is_volume_used "$f" && continue
  2894. debug "Cleaning unused docker-compose ${f##*/}"
  2895. rm -rf "$f" || return 1
  2896. done
  2897. return 0
  2898. }
  2899. export -f clean_unused_docker_compose
  2900. stdin_get_hash() {
  2901. local sha
  2902. sha=$(sha256sum) || return 1
  2903. sha=${sha:0:64}
  2904. echo "$sha"
  2905. }
  2906. export -f stdin_get_hash
  2907. file_get_hash() {
  2908. stdin_get_hash < "$1" || return 1
  2909. }
  2910. export -f file_get_hash
  2911. docker_compose_store() {
  2912. local file="$1" sha
  2913. sha=$(file_get_hash "$file") || return 1
  2914. project=$(get_default_project_name) || return 1
  2915. dst="/var/lib/compose/docker-compose/$sha/$project"
  2916. mkdir -p "$dst" || return 1
  2917. cat <<EOF > "$dst/.env" || return 1
  2918. DOCKER_COMPOSE_PATH=$dst
  2919. COMPOSE_HTTP_TIMEOUT=7200
  2920. EOF
  2921. cp "$file" "$dst/docker-compose.yml" || return 1
  2922. mkdir -p "$dst/bin" || return 1
  2923. cat <<EOF > "$dst/bin/dc" || return 1
  2924. #!/bin/bash
  2925. $(declare -f read-0)
  2926. docker_run_opts=()
  2927. while read-0 opt; do
  2928. if [[ "\$opt" == "!env:"* ]]; then
  2929. opt="\${opt##!env:}"
  2930. var="\${opt%%=*}"
  2931. value="\${opt#*=}"
  2932. export "\$var"="\$value"
  2933. else
  2934. docker_run_opts+=("\$opt")
  2935. fi
  2936. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2937. docker_run_opts+=(
  2938. "-w" "$dst"
  2939. "--entrypoint" "/usr/local/bin/docker-compose"
  2940. )
  2941. [ -t 1 ] && {
  2942. docker_run_opts+=("-ti")
  2943. }
  2944. exec docker run --rm "\${docker_run_opts[@]}" "\${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2945. EOF
  2946. chmod +x "$dst/bin/dc" || return 1
  2947. printf "%s" "$sha"
  2948. }
  2949. export -f docker_compose_store
  2950. launch_docker_compose() {
  2951. local charm docker_compose_tmpdir docker_compose_dir
  2952. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2953. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2954. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2955. ## docker-compose will name network from the parent dir name
  2956. project=$(get_default_project_name)
  2957. mkdir -p "$docker_compose_tmpdir/$project"
  2958. docker_compose_dir="$docker_compose_tmpdir/$project"
  2959. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2960. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2961. # debug "Merging some config data in docker-compose.yml:"
  2962. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2963. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2964. fi
  2965. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2966. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2967. fi
  2968. ## XXXvlab: could be more specific and only link the needed charms
  2969. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2970. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2971. # if charm.exists "$charm"; then
  2972. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2973. # fi
  2974. # done
  2975. mkdir "$docker_compose_dir/.data"
  2976. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2977. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2978. fi
  2979. {
  2980. {
  2981. {
  2982. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2983. cd "/var/lib/compose/docker-compose/$sha/$project" || return 1
  2984. else
  2985. cd "$docker_compose_dir" || return 1
  2986. fi
  2987. if [ -f ".env" ]; then
  2988. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2989. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2990. fi
  2991. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2992. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2993. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2994. if [ "$DRY_COMPOSE_RUN" ]; then
  2995. echo docker-compose "$@"
  2996. else
  2997. docker-compose "$@"
  2998. fi
  2999. echo "$?" > "$docker_compose_dir/.data/errlvl"
  3000. } | _save stdout
  3001. } 3>&1 1>&2 2>&3 | _save stderr
  3002. } 3>&1 1>&2 2>&3
  3003. 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
  3004. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  3005. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  3006. fi
  3007. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  3008. if [ -z "$docker_compose_errlvl" ]; then
  3009. err "Something went wrong before you could gather docker-compose errorlevel."
  3010. return 1
  3011. fi
  3012. return "$docker_compose_errlvl"
  3013. }
  3014. export -f launch_docker_compose
  3015. get_compose_yml_location() {
  3016. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  3017. echo "$COMPOSE_YML_FILE"
  3018. return 0
  3019. fi
  3020. parent=$(while ! [ -f "./compose.yml" ]; do
  3021. [ "$PWD" == "/" ] && exit 0
  3022. cd ..
  3023. done; echo "$PWD"
  3024. )
  3025. if [ "$parent" ]; then
  3026. echo "$parent/compose.yml"
  3027. return 0
  3028. fi
  3029. ## XXXvlab: do we need this additional environment variable,
  3030. ## COMPOSE_YML_FILE is not sufficient ?
  3031. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  3032. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  3033. warn "No 'compose.yml' was found in current or parent dirs," \
  3034. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  3035. "(${DEFAULT_COMPOSE_FILE})"
  3036. return 0
  3037. fi
  3038. echo "$DEFAULT_COMPOSE_FILE"
  3039. return 0
  3040. fi
  3041. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  3042. return 0
  3043. }
  3044. export -f get_compose_yml_location
  3045. get_compose_yml_content() {
  3046. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  3047. if [ -e "$cache_file" ]; then
  3048. cat "$cache_file" &&
  3049. touch "$cache_file" || return 1
  3050. return 0
  3051. fi
  3052. if [ -z "$COMPOSE_YML_FILE" ]; then
  3053. COMPOSE_YML_FILE=$(get_compose_yml_location) || return 1
  3054. fi
  3055. if [ -e "$COMPOSE_YML_FILE" ]; then
  3056. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  3057. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  3058. err "Could not read '$COMPOSE_YML_FILE'."
  3059. return 1
  3060. }
  3061. else
  3062. debug "No compose file found. Using an empty one."
  3063. COMPOSE_YML_CONTENT=""
  3064. fi
  3065. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  3066. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  3067. if [ "$?" != 0 ]; then
  3068. outputed_something=
  3069. while IFS='' read -r line1 && IFS='' read -r line2; do
  3070. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  3071. outputed_something=true
  3072. echo "$line1 $GRAY($line2)$NORMAL"
  3073. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  3074. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  3075. prefix " $GRAY|$NORMAL "
  3076. [ "$outputed_something" ] || {
  3077. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  3078. echo "$output" | prefix " $GRAY|$NORMAL "
  3079. }
  3080. return 1
  3081. fi
  3082. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  3083. }
  3084. export -f get_compose_yml_content
  3085. get_default_target_services() {
  3086. local services=("$@")
  3087. if [ -z "${services[*]}" ]; then
  3088. if [ "$DEFAULT_SERVICES" ]; then
  3089. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  3090. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  3091. services="$DEFAULT_SERVICES"
  3092. else
  3093. err "No service provided."
  3094. return 1
  3095. fi
  3096. fi
  3097. echo "${services[*]}"
  3098. }
  3099. export -f get_default_target_services
  3100. get_master_services() {
  3101. local loaded master_service service
  3102. declare -A loaded
  3103. for service in "$@"; do
  3104. master_service=$(get_top_master_service_for_service "$service") || return 1
  3105. if [ "${loaded[$master_service]}" ]; then
  3106. continue
  3107. fi
  3108. echo "$master_service"
  3109. loaded["$master_service"]=1
  3110. done | nspc
  3111. return "${PIPESTATUS[0]}"
  3112. }
  3113. export -f get_master_services
  3114. get_current_docker_container_id() {
  3115. local line
  3116. line=$(cat "/proc/self/cpuset") || return 1
  3117. [[ "$line" == *docker* ]] || return 1
  3118. echo "${line##*/}"
  3119. }
  3120. export -f get_current_docker_container_id
  3121. ## if we are in a docker compose, we might want to know what is the
  3122. ## real host path of some local paths.
  3123. get_host_path() {
  3124. local path="$1"
  3125. path=$(realpath "$path") || return 1
  3126. container_id=$(get_current_docker_container_id) || {
  3127. print "%s" "$path"
  3128. return 0
  3129. }
  3130. biggest_dst=
  3131. current_src=
  3132. while read-0 src dst; do
  3133. [[ "$path" == "$dst"* ]] || continue
  3134. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  3135. biggest_dst="$dst"
  3136. current_src="$src"
  3137. fi
  3138. done < <(get_volumes_for_container "$container_id")
  3139. if [ "$current_src" ]; then
  3140. printf "%s" "$current_src"
  3141. else
  3142. return 1
  3143. fi
  3144. }
  3145. export -f get_host_path
  3146. _setup_state_dir() {
  3147. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  3148. #debug "Creating temporary state directory in '$state_tmpdir'."
  3149. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  3150. # rm -rf \"$state_tmpdir\""
  3151. trap_add EXIT "rm -rf \"$state_tmpdir\""
  3152. }
  3153. get_docker_compose_help_msg() {
  3154. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3155. docker_compose_help_msg
  3156. if [ -e "$cache_file" ]; then
  3157. cat "$cache_file" &&
  3158. touch "$cache_file" || return 1
  3159. return 0
  3160. fi
  3161. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  3162. echo "$docker_compose_help_msg" |
  3163. tee "$cache_file" || return 1
  3164. }
  3165. get_docker_compose_usage() {
  3166. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3167. docker_compose_help_msg
  3168. if [ -e "$cache_file" ]; then
  3169. cat "$cache_file" &&
  3170. touch "$cache_file" || return 1
  3171. return 0
  3172. fi
  3173. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  3174. echo "$docker_compose_help_msg" |
  3175. grep -m 1 "^Usage:" -A 10000 |
  3176. egrep -m 1 "^\$" -B 10000 |
  3177. nspc |
  3178. sed -r 's/^Usage: //g' |
  3179. tee "$cache_file" || return 1
  3180. }
  3181. get_docker_compose_opts_help() {
  3182. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3183. docker_compose_help_msg
  3184. if [ -e "$cache_file" ]; then
  3185. cat "$cache_file" &&
  3186. touch "$cache_file" || return 1
  3187. return 0
  3188. fi
  3189. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3190. echo "$docker_compose_opts_help" |
  3191. grep '^Options:' -A 20000 |
  3192. tail -n +2 |
  3193. { cat ; echo; } |
  3194. egrep -m 1 "^\S*\$" -B 10000 |
  3195. head -n -1 |
  3196. tee "$cache_file" || return 1
  3197. }
  3198. get_docker_compose_commands_help() {
  3199. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3200. docker_compose_help_msg
  3201. if [ -e "$cache_file" ]; then
  3202. cat "$cache_file" &&
  3203. touch "$cache_file" || return 1
  3204. return 0
  3205. fi
  3206. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  3207. echo "$docker_compose_opts_help" |
  3208. grep '^Commands:' -A 20000 |
  3209. tail -n +2 |
  3210. { cat ; echo; } |
  3211. egrep -m 1 "^\S*\$" -B 10000 |
  3212. head -n -1 |
  3213. tee "$cache_file" || return 1
  3214. }
  3215. get_docker_compose_opts_list() {
  3216. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$({ p0 "$1"; cat "$(which docker-compose)"; } | md5_compat)" \
  3217. docker_compose_help_msg
  3218. if [ -e "$cache_file" ]; then
  3219. cat "$cache_file" &&
  3220. touch "$cache_file" || return 1
  3221. return 0
  3222. fi
  3223. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  3224. echo "$docker_compose_opts_help" |
  3225. egrep "^\s+-" |
  3226. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  3227. tee "$cache_file" || return 1
  3228. }
  3229. options_parser() {
  3230. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  3231. printf "\0"
  3232. }
  3233. remove_options_in_option_help_msg() {
  3234. {
  3235. read-0 null
  3236. if [ "$null" ]; then
  3237. err "options parsing error, should start with an option line."
  3238. return 1
  3239. fi
  3240. while read-0 opt full_txt;do
  3241. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  3242. single_opts="$(printf "%s " $opt | single_opts_filter)"
  3243. for to_remove in "$@"; do
  3244. str_matches "$to_remove" $multi_opts $single_opts && {
  3245. continue 2
  3246. }
  3247. done
  3248. echo -n "$full_txt"
  3249. done
  3250. } < <(options_parser)
  3251. }
  3252. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  3253. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  3254. multi_opts_filter() {
  3255. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3256. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  3257. tr ',' "\n" | nspc
  3258. }
  3259. single_opts_filter() {
  3260. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  3261. tr ',' "\n" | nspc
  3262. }
  3263. get_docker_compose_multi_opts_list() {
  3264. local action="$1" opts_list
  3265. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3266. echo "$opts_list" | multi_opts_filter
  3267. }
  3268. get_docker_compose_single_opts_list() {
  3269. local action="$1" opts_list
  3270. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  3271. echo "$opts_list" | single_opts_filter
  3272. }
  3273. display_commands_help() {
  3274. local charm_actions
  3275. echo
  3276. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  3277. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  3278. charm_actions_help=$(get_docker_charm_action_help) || return 1
  3279. if [ "$charm_actions_help" ]; then
  3280. echo
  3281. echo "${WHITE}Charm actions${NORMAL}:"
  3282. printf "%s\n" "$charm_actions_help" | \
  3283. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  3284. fi
  3285. }
  3286. get_docker_charm_action() {
  3287. local services service charm relation_name target_service relation_config \
  3288. target_charm
  3289. services=($(get_compose_yml_content | yq -r 'keys().[]' 2>/dev/null)) || return 1
  3290. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3291. services=($(get_all_services)) || return 1
  3292. for service in "${services[@]}"; do
  3293. printf "%s:\n" "$service"
  3294. charm=$(get_service_charm "$service") || return 1
  3295. for action in $(charm.ls_direct_actions "$charm"); do
  3296. printf " %s:\n" "$action"
  3297. printf " type: %s\n" "direct"
  3298. done
  3299. while read-0 relation_name target_service _relation_config _tech_dep; do
  3300. target_charm=$(get_service_charm "$target_service") || return 1
  3301. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3302. printf " %s:\n" "$action"
  3303. printf " type: %s\n" "indirect"
  3304. printf " inherited: %s\n" "$target_charm"
  3305. done
  3306. done < <(get_service_relations "$service")
  3307. done
  3308. }
  3309. export -f get_docker_charm_action
  3310. get_docker_charm_action_help() {
  3311. local services service charm relation_name target_service relation_config \
  3312. target_charm
  3313. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  3314. NO_CONSTRAINT_CHECK=1 get_all_relations "${services[@]}" >/dev/null || return 1
  3315. for service in "${services[@]}"; do
  3316. out=$(
  3317. charm=$(get_service_charm "$service") || return 1
  3318. for action in $(charm.ls_direct_actions "$charm"); do
  3319. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  3320. done
  3321. while read-0 relation_name target_service _relation_config _tech_dep; do
  3322. target_charm=$(get_service_charm "$target_service") || return 1
  3323. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  3324. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  3325. done
  3326. done < <(get_service_relations "$service")
  3327. )
  3328. if [ "$out" ]; then
  3329. echo " for ${DARKYELLOW}$service${NORMAL}:"
  3330. printf "%s\n" "$out"
  3331. fi
  3332. done
  3333. }
  3334. display_help() {
  3335. print_help
  3336. echo "${WHITE}Usage${NORMAL}:"
  3337. echo " $usage"
  3338. echo "${WHITE}Options${NORMAL}:"
  3339. echo " -h, --help Print this message and quit"
  3340. echo " (ignoring any other options)"
  3341. echo " -V, --version Print current version and quit"
  3342. echo " (ignoring any other options)"
  3343. echo " --dirs Display data dirs and quit"
  3344. echo " (ignoring any other options)"
  3345. echo " --get-project-name Display project name and quit"
  3346. echo " (ignoring any other options)"
  3347. echo " --get-available-actions Display all available actions and quit"
  3348. echo " (ignoring any other options)"
  3349. echo " -v, --verbose Be more verbose"
  3350. echo " -q, --quiet Be quiet"
  3351. echo " -d, --debug Print full debugging information (sets also verbose)"
  3352. echo " --dry-compose-run If docker-compose will be run, only print out what"
  3353. echo " command line will be used."
  3354. echo " --no-relations Do not run any relation script"
  3355. echo " --no-hooks Do not run any hook script"
  3356. echo " --no-init Do not run any init script"
  3357. echo " --no-post-deploy Do not run any post-deploy script"
  3358. echo " --no-pre-deploy Do not run any pre-deploy script"
  3359. echo " --without-relation RELATION "
  3360. echo " Do not run given relation"
  3361. echo " -R, --rebuild-relations-to-service SERVICE"
  3362. echo " Will rebuild all relations to given service"
  3363. echo " --add-compose-content, -Y YAML"
  3364. echo " Will merge some direct YAML with the current compose"
  3365. echo " -c, --color Force color mode (default is to detect if in tty mode)"
  3366. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  3367. filter_docker_compose_help_message
  3368. display_commands_help
  3369. }
  3370. _graph_service() {
  3371. local service="$1" base="$1"
  3372. charm=$(get_service_charm "$service") || return 1
  3373. metadata=$(charm.metadata "$charm") || return 1
  3374. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  3375. if [ "$subordinate" == "True" ]; then
  3376. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  3377. master_charm=
  3378. while read-0 relation_name relation; do
  3379. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  3380. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  3381. if [ -z "$interface" ]; then
  3382. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  3383. return 1
  3384. fi
  3385. ## Action provided by relation ?
  3386. target_service=
  3387. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  3388. [ "$interface" == "$relation_name" ] && {
  3389. target_service="$candidate_target_service"
  3390. break
  3391. }
  3392. done < <(get_service_relations "$service")
  3393. if [ -z "$target_service" ]; then
  3394. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3395. "${DARKYELLOW}$service$NORMAL compose definition."
  3396. return 1
  3397. fi
  3398. master_service="$target_service"
  3399. master_charm=$(get_service_charm "$target_service") || return 1
  3400. break
  3401. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3402. fi
  3403. _graph_node_service "$service" "$base" "$charm"
  3404. _graph_edge_service "$service" "$subordinate" "$master_service"
  3405. }
  3406. _graph_node_service() {
  3407. local service="$1" base="$2" charm="$3"
  3408. cat <<EOF
  3409. "$(_graph_node_service_label ${service})" [
  3410. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  3411. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  3412. color = $([ "$base" ] && echo "blue" || echo "black")
  3413. fillcolor = "white"
  3414. fontname = "Courier New"
  3415. shape = "Mrecord"
  3416. label =<$(_graph_node_service_content "$service")>
  3417. ];
  3418. EOF
  3419. }
  3420. _graph_edge_service() {
  3421. local service="$1" subordinate="$2" master_service="$3"
  3422. while read-0 relation_name target_service relation_config tech_dep; do
  3423. cat <<EOF
  3424. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3425. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3426. fontsize = 16
  3427. fontcolor = "black"
  3428. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3429. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3430. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3431. arrowtail = odot
  3432. # arrowhead = dotlicurve
  3433. taillabel = "$relation_name" ];
  3434. EOF
  3435. done < <(get_service_relations "$service") || return 1
  3436. }
  3437. _graph_node_service_label() {
  3438. local service="$1"
  3439. echo "service_$service"
  3440. }
  3441. _graph_node_service_content() {
  3442. local service="$1"
  3443. charm=$(get_service_charm "$service") || return 1
  3444. cat <<EOF
  3445. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3446. <tr>
  3447. <td bgcolor="black" align="center" colspan="2">
  3448. <font color="white">$service</font>
  3449. </td>
  3450. </tr>
  3451. $(if [ "$charm" != "$service" ]; then
  3452. cat <<EOF2
  3453. <tr>
  3454. <td align="left" port="r0">charm: $charm</td>
  3455. </tr>
  3456. EOF2
  3457. fi)
  3458. </table>
  3459. EOF
  3460. }
  3461. cla_contains () {
  3462. local e
  3463. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3464. return 1
  3465. }
  3466. filter_docker_compose_help_message() {
  3467. cat - |
  3468. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3469. s/docker-compose.yml/compose.yml/g;
  3470. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3471. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3472. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3473. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3474. }
  3475. graph() {
  3476. local services=("$@")
  3477. declare -A entries
  3478. cat <<EOF
  3479. digraph g {
  3480. graph [
  3481. fontsize=30
  3482. labelloc="t"
  3483. label=""
  3484. splines=true
  3485. overlap=false
  3486. #rankdir = "LR"
  3487. ];
  3488. ratio = auto;
  3489. EOF
  3490. for target_service in "$@"; do
  3491. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3492. for service in $services; do
  3493. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3494. if cla_contains "$service" "${services[@]}"; then
  3495. base=true
  3496. else
  3497. base=
  3498. fi
  3499. _graph_service "$service" "$base"
  3500. done
  3501. done
  3502. echo "}"
  3503. }
  3504. cached_wget() {
  3505. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(p0 "$@" | md5_compat)" \
  3506. url="$1"
  3507. if [ -e "$cache_file" ]; then
  3508. cat "$cache_file"
  3509. touch "$cache_file"
  3510. return 0
  3511. fi
  3512. wget -O- "${url}" |
  3513. tee "$cache_file"
  3514. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3515. rm "$cache_file"
  3516. die "Unable to fetch '$url'."
  3517. return 1
  3518. fi
  3519. }
  3520. export -f cached_wget
  3521. [ "$SOURCED" ] && return 0
  3522. trap_add "EXIT" clean_cache
  3523. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3524. if [ -r /etc/default/charm ]; then
  3525. . /etc/default/charm
  3526. fi
  3527. if [ -r "/etc/default/$exname" ]; then
  3528. . "/etc/default/$exname"
  3529. fi
  3530. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3531. ## userdir ? and global /etc/compose.yml ?
  3532. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3533. /etc/default/compose /etc/compose/local.conf; do
  3534. [ -e "$cfgfile" ] || continue
  3535. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3536. done
  3537. fi
  3538. _setup_state_dir
  3539. mkdir -p "$CACHEDIR" || exit 1
  3540. log () { cat; }
  3541. export -f log
  3542. ##
  3543. ## Argument parsing
  3544. ##
  3545. wrap_opts=()
  3546. services=()
  3547. remainder_args=()
  3548. compose_opts=()
  3549. compose_contents=()
  3550. action_opts=()
  3551. services_args=()
  3552. pos_arg_ct=0
  3553. no_hooks=
  3554. no_init=
  3555. action=
  3556. stage="main" ## switches from 'main', to 'action', 'remainder'
  3557. is_docker_compose_action=
  3558. rebuild_relations_to_service=()
  3559. color=
  3560. declare -A without_relations
  3561. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3562. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || exit 1
  3563. while read-0 arg; do
  3564. case "$stage" in
  3565. "main")
  3566. case "$arg" in
  3567. --help|-h)
  3568. no_init=true ; no_hooks=true ; no_relations=true
  3569. display_help
  3570. exit 0
  3571. ;;
  3572. --verbose|-v)
  3573. export VERBOSE=true
  3574. compose_opts+=("--verbose")
  3575. ;;
  3576. --quiet|-q)
  3577. export QUIET=true
  3578. export wrap_opts+=("-q")
  3579. log () { cat >&2; }
  3580. export -f log
  3581. ;;
  3582. --version|-V)
  3583. print_version
  3584. docker-compose --version
  3585. docker --version
  3586. exit 0
  3587. ;;
  3588. -f|--file)
  3589. read-0 value
  3590. [ -e "$value" ] || die "File $value doesn't exists"
  3591. export COMPOSE_YML_FILE="$value"
  3592. shift
  3593. ;;
  3594. -p|--project-name)
  3595. read-0 value
  3596. export DEFAULT_PROJECT_NAME="$value"
  3597. compose_opts+=("--project-name $value")
  3598. shift
  3599. ;;
  3600. --color|-c)
  3601. if [ "$color" == "0" ]; then
  3602. err "Conflicting option --color with previous --no-ansi."
  3603. exit 1
  3604. fi
  3605. color=1
  3606. ansi_color yes
  3607. ;;
  3608. --no-ansi)
  3609. if [ "$color" == "1" ]; then
  3610. err "Conflicting option --no-ansi with previous --color."
  3611. exit 1
  3612. fi
  3613. color=0
  3614. ansi_color no
  3615. compose_opts+=("--no-ansi")
  3616. ;;
  3617. --no-relations)
  3618. export no_relations=true
  3619. ;;
  3620. --without-relation)
  3621. read-0 value
  3622. without_relations["$value"]=1
  3623. shift
  3624. ;;
  3625. --no-hooks)
  3626. export no_hooks=true
  3627. ;;
  3628. --no-init)
  3629. export no_init=true
  3630. ;;
  3631. --no-post-deploy)
  3632. export no_post_deploy=true
  3633. ;;
  3634. --no-pre-deploy)
  3635. export no_pre_deploy=true
  3636. ;;
  3637. --rebuild-relations-to-service|-R)
  3638. read-0 value
  3639. rebuild_relations_to_service+=("$value")
  3640. shift
  3641. ;;
  3642. --debug|-d)
  3643. export DEBUG=true
  3644. export VERBOSE=true
  3645. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3646. ;;
  3647. --add-compose-content|-Y)
  3648. read-0 value
  3649. compose_contents+=("$value")
  3650. shift
  3651. ;;
  3652. --dirs)
  3653. echo "CACHEDIR: $CACHEDIR"
  3654. echo "VARDIR: $VARDIR"
  3655. exit 0
  3656. ;;
  3657. --get-project-name)
  3658. project=$(get_default_project_name) || exit 1
  3659. echo "$project"
  3660. exit 0
  3661. ;;
  3662. --get-available-actions)
  3663. get_docker_charm_action
  3664. exit $?
  3665. ;;
  3666. --dry-compose-run)
  3667. export DRY_COMPOSE_RUN=true
  3668. ;;
  3669. --*|-*)
  3670. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3671. read-0 value
  3672. compose_opts+=("$arg" "$value")
  3673. shift;
  3674. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3675. compose_opts+=("$arg")
  3676. else
  3677. err "Unknown option '$arg'. Please check help:"
  3678. display_help >&2
  3679. exit 1
  3680. fi
  3681. ;;
  3682. *)
  3683. action="$arg"
  3684. stage="action"
  3685. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3686. is_docker_compose_action=true
  3687. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3688. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3689. if [ "$DC_MATCH_MULTI" ]; then
  3690. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3691. fi
  3692. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3693. pos_args=("${pos_args[@]:1}")
  3694. # echo "USAGE: $DC_USAGE"
  3695. # echo "pos_args: ${pos_args[@]}"
  3696. # echo "MULTI: $DC_MATCH_MULTI"
  3697. # echo "SINGLE: $DC_MATCH_SINGLE"
  3698. # exit 1
  3699. else
  3700. stage="remainder"
  3701. fi
  3702. ;;
  3703. esac
  3704. ;;
  3705. "action") ## Only for docker-compose actions
  3706. case "$arg" in
  3707. --help|-h)
  3708. no_init=true ; no_hooks=true ; no_relations=true
  3709. action_opts+=("$arg")
  3710. ;;
  3711. --*|-*)
  3712. if [ "$is_docker_compose_action" ]; then
  3713. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3714. read-0 value
  3715. action_opts+=("$arg" "$value")
  3716. shift
  3717. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3718. action_opts+=("$arg")
  3719. else
  3720. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3721. docker-compose "$action" --help |
  3722. filter_docker_compose_help_message >&2
  3723. exit 1
  3724. fi
  3725. fi
  3726. ;;
  3727. *)
  3728. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3729. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3730. services_args+=("$arg")
  3731. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3732. services_args=("$arg") || exit 1
  3733. stage="remainder"
  3734. else
  3735. action_posargs+=("$arg")
  3736. ((pos_arg_ct++))
  3737. fi
  3738. ;;
  3739. esac
  3740. ;;
  3741. "remainder")
  3742. remainder_args+=("$arg")
  3743. while read-0 arg; do
  3744. remainder_args+=("$arg")
  3745. done
  3746. break 3
  3747. ;;
  3748. esac
  3749. shift
  3750. done < <(cla.normalize "$@")
  3751. export compose_contents
  3752. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3753. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3754. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3755. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3756. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3757. aexport remainder_args
  3758. ##
  3759. ## Actual code
  3760. ##
  3761. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3762. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3763. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3764. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3765. ##
  3766. ## Get services in command line.
  3767. ##
  3768. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3769. action_service=${remainder_args[0]}
  3770. if [ -z "$action_service" ]; then
  3771. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3772. display_commands_help
  3773. exit 1
  3774. fi
  3775. ## Required by has_service_action
  3776. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3777. NO_CONSTRAINT_CHECK=1 get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3778. remainder_args=("${remainder_args[@]:1}")
  3779. if has_service_action "$action_service" "$action" >/dev/null; then
  3780. is_service_action=true
  3781. {
  3782. read-0 action_type
  3783. case "$action_type" in
  3784. "relation")
  3785. read-0 _ target_service _target_charm relation_name _ action_script_path
  3786. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3787. ;;
  3788. "direct")
  3789. read-0 _ action_script_path
  3790. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3791. ;;
  3792. esac
  3793. } < <(has_service_action "$action_service" "$action")
  3794. services_args=("$action_service")
  3795. get_all_relations "${services_args[@]}" >/dev/null || {
  3796. echo " Hint: if this is unexpected, you can try to delete caches, and re-run the command." >&2
  3797. exit 1
  3798. }
  3799. ## Divert logging to stdout to stderr
  3800. log () { cat >&2; }
  3801. export -f log
  3802. else
  3803. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3804. fi
  3805. else
  3806. case "$action" in
  3807. ps|up)
  3808. if [ "${#services_args[@]}" == 0 ]; then
  3809. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3810. fi
  3811. ;;
  3812. config)
  3813. services_args=("${action_posargs[@]}")
  3814. ;;
  3815. esac
  3816. fi
  3817. NO_CONSTRAINT_CHECK=True
  3818. case "$action" in
  3819. up)
  3820. NO_CONSTRAINT_CHECK=
  3821. ;;
  3822. esac
  3823. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3824. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3825. services=($(get_master_services "${services_args[@]}")) || exit 1
  3826. if [ "$action" == "up" ]; then
  3827. declare -A seen
  3828. for service in $(get_ordered_service_dependencies "${services_args[@]}"); do
  3829. mservice=$(get_master_service_for_service "$service") || exit 1
  3830. [ "${seen[$mservice]}" ] && continue
  3831. type="$(get_service_type "$mservice")" || exit 1
  3832. ## remove run-once
  3833. [ "$type" == "run-once" ] && continue
  3834. [ "$type" == "stub" ] && continue
  3835. seen[$mservice]=1
  3836. action_posargs+=("$mservice")
  3837. done
  3838. else
  3839. action_posargs+=("${services[@]}")
  3840. fi
  3841. ## Get rid of subordinates
  3842. action_posargs=($(get_master_services "${action_posargs[@]}")) || exit 1
  3843. fi
  3844. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3845. err "Fails to compile base 'docker-compose.yml'"
  3846. exit 1
  3847. }
  3848. ##
  3849. ## Pre-action
  3850. ##
  3851. full_init=
  3852. case "$action" in
  3853. up|run)
  3854. full_init=true
  3855. post_hook=true
  3856. ;;
  3857. ""|down|restart|logs|config|ps)
  3858. full_init=
  3859. ;;
  3860. *)
  3861. if [ "$is_service_action" ]; then
  3862. full_init=true
  3863. keywords=($(egrep "^#*\s*compose:" "$action_script_path" | cut -f 2- -d:))
  3864. for keyword in "${keywords[@]}"; do
  3865. case "$keyword" in
  3866. no-hooks)
  3867. full_init=
  3868. ;;
  3869. hooks)
  3870. full_init=true
  3871. ;;
  3872. esac
  3873. done
  3874. fi
  3875. ;;
  3876. esac
  3877. if [ -n "$full_init" ]; then
  3878. ## init in order
  3879. if [[ -z "$no_init" && -z "$no_hooks" ]]; then
  3880. Section setup host resources
  3881. setup_host_resources "${services_args[@]}" || exit 1
  3882. Section initialisation
  3883. run_service_hook init "${services_args[@]}" || exit 1
  3884. fi
  3885. ## Get relations
  3886. if [[ -z "$no_relations" && -z "$no_hooks" ]]; then
  3887. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3888. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3889. rebuild_relations_to_service=($rebuild_relations_to_service)
  3890. project=$(get_default_project_name) || return 1
  3891. for service in "${rebuild_relations_to_service[@]}"; do
  3892. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3893. [ -d "$dir" ] && {
  3894. debug rm -rf "$dir"
  3895. rm -rf "$dir"
  3896. }
  3897. done
  3898. done
  3899. fi
  3900. run_service_relations "${services_args[@]}" || exit 1
  3901. fi
  3902. if [[ -z "$no_pre_deploy" && -z "$no_hooks" ]]; then
  3903. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3904. fi
  3905. fi | log
  3906. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3907. exit 1
  3908. fi
  3909. if [ "$action" == "run" ] && [ "${#services_args}" != 0 ]; then
  3910. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3911. metadata=$(charm.metadata "$charm") || exit 1
  3912. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3913. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3914. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3915. fi
  3916. fi
  3917. export SERVICE_PACK="${services_args[*]}"
  3918. ##
  3919. ## Docker-compose
  3920. ##
  3921. errlvl="0"
  3922. case "$action" in
  3923. up|start|stop|build|run)
  3924. ## force daemon mode for up
  3925. if [[ "$action" == "up" ]]; then
  3926. if ! array_member action_opts -d; then
  3927. action_opts+=("-d")
  3928. fi
  3929. if ! array_member action_opts --remove-orphans; then
  3930. action_opts+=("--remove-orphans")
  3931. fi
  3932. fi
  3933. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3934. ;;
  3935. logs)
  3936. if ! array_member action_opts --tail; then ## force daemon mode for up
  3937. action_opts+=("--tail" "10")
  3938. fi
  3939. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3940. ;;
  3941. "")
  3942. launch_docker_compose "${compose_opts[@]}"
  3943. ;;
  3944. graph)
  3945. graph $SERVICE_PACK
  3946. ;;
  3947. config)
  3948. ## removing the services
  3949. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3950. ## forcing docker-compose config to output the config file to stdout and not stderr
  3951. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3952. echo "$out"
  3953. exit 1
  3954. }
  3955. echo "$out"
  3956. warn "Runtime configuration modification (from relations) are not included here."
  3957. ;;
  3958. down)
  3959. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3960. debug "Adding a default argument of '--remove-orphans'"
  3961. action_opts+=("--remove-orphans")
  3962. fi
  3963. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3964. ;;
  3965. *)
  3966. if [ "$is_service_action" ]; then
  3967. run_service_action "$action_service" "$action" "${remainder_args[@]}"
  3968. errlvl="$?"
  3969. errlvl "$errlvl"
  3970. else
  3971. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3972. fi
  3973. ;;
  3974. esac || exit 1
  3975. if [ "$post_hook" -a "${#services_args[@]}" != 0 -a -z "$no_hooks" -a -z "$no_post_deploy" ]; then
  3976. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3977. fi
  3978. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3979. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3980. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  3981. fi
  3982. fi
  3983. clean_unused_docker_compose || exit 1
  3984. exit "$errlvl"