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.

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