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.

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