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.

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