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.

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