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.

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