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.

4115 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. _rec_get_depth() {
  1150. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1151. [ "${depths[$elt]}" ] && return 0
  1152. if [ -e "$cache_file" ]; then
  1153. # debug "$FUNCNAME: cache hit ($*)"
  1154. depths[$elt]=$(cat "$cache_file")
  1155. return 0
  1156. fi
  1157. visited[$elt]=1
  1158. #debug "Setting visited[$elt]"
  1159. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1160. deps=$(get_service_deps "$elt") || {
  1161. debug "Failed get_service_deps $elt"
  1162. return 1
  1163. }
  1164. # debug "$elt deps are:" $deps
  1165. max=0
  1166. for dep in $deps; do
  1167. [ "${visited[$dep]}" ] && {
  1168. #debug "Already computing $dep"
  1169. continue
  1170. }
  1171. _rec_get_depth "$dep" || return 1
  1172. #debug "Requesting depth[$dep]"
  1173. if (( ${depths[$dep]} > max )); then
  1174. max="${depths[$dep]}"
  1175. fi
  1176. done
  1177. # debug "Setting depth[$elt] to $((max + 1))"
  1178. depths[$elt]=$((max + 1))
  1179. echo "${depths[$elt]}" > $cache_file
  1180. }
  1181. export -f _rec_get_depth
  1182. get_ordered_service_dependencies() {
  1183. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1184. if [ -e "$cache_file" ]; then
  1185. # debug "$FUNCNAME: cache hit ($*)"
  1186. cat "$cache_file"
  1187. return 0
  1188. fi
  1189. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  1190. if [ -z "${services[*]}" ]; then
  1191. return 0
  1192. # print_syntax_error "$FUNCNAME: no arguments"
  1193. # return 1
  1194. fi
  1195. declare -A depths
  1196. declare -A visited
  1197. heads=("${services[@]}")
  1198. while [ "${#heads[@]}" != 0 ]; do
  1199. array_pop heads head
  1200. _rec_get_depth "$head" || return 1
  1201. done
  1202. i=0
  1203. while [ "${#depths[@]}" != 0 ]; do
  1204. for key in "${!depths[@]}"; do
  1205. value="${depths[$key]}"
  1206. if [ "$value" == "$i" ]; then
  1207. echo "$key"
  1208. unset depths[$key]
  1209. fi
  1210. done
  1211. i=$((i + 1))
  1212. done | tee "$cache_file"
  1213. }
  1214. export -f get_ordered_service_dependencies
  1215. run_service_hook () {
  1216. local action="$1" service subservice subservices loaded
  1217. shift
  1218. declare -A loaded
  1219. for service in "$@"; do
  1220. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1221. for subservice in $subservices; do
  1222. if [ "${loaded[$subservice]}" ]; then
  1223. ## Prevent double inclusion of same service if this
  1224. ## service is deps of two or more of your
  1225. ## requirements.
  1226. continue
  1227. fi
  1228. charm=$(get_service_charm "$subservice") || return 1
  1229. charm.has_hook "$charm" "$action" >/dev/null || continue
  1230. PROJECT_NAME=$(get_default_project_name) || return 1
  1231. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1232. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1233. DOCKER_BASE_IMAGE=$(service_base_docker_image "$MASTER_BASE_SERVICE_NAME") || return 1
  1234. Wrap "${wrap_opts[@]}" -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1235. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1236. export SERVICE_NAME=$subservice
  1237. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1238. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1239. export CHARM_NAME="$charm"
  1240. export PROJECT_NAME="$PROJECT_NAME"
  1241. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1242. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1243. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1244. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1245. charm.run_hook "$charm" "$action"
  1246. EOF
  1247. loaded[$subservice]=1
  1248. done
  1249. done
  1250. return 0
  1251. }
  1252. host_resource_get() {
  1253. local location="$1" cfg="$2"
  1254. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1255. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1256. return 1
  1257. }
  1258. if fn.exists host_resource_get_$type; then
  1259. host_resource_get_$type "$location" "$cfg"
  1260. else
  1261. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1262. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1263. "$DARKYELLOW$subservice$NORMAL config."
  1264. return 1
  1265. fi
  1266. }
  1267. export -f host_resource_get
  1268. host_resource_get_git() {
  1269. local location="$1" cfg="$2" branch parent url
  1270. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1271. branch=${branch:-master}
  1272. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1273. parent="$(dirname "$location")"
  1274. (
  1275. mkdir -p "$parent" && cd "$parent" &&
  1276. git clone -b "$branch" "$url" "$(basename "$location")"
  1277. ) || return 1
  1278. }
  1279. export -f host_resource_get_git
  1280. host_resource_get_git-sub() {
  1281. local location="$1" cfg="$2" branch parent url
  1282. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1283. branch=${branch:-master}
  1284. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1285. parent="$(dirname "$location")"
  1286. (
  1287. mkdir -p "$parent" && cd "$parent" &&
  1288. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1289. ) || return 1
  1290. }
  1291. export -f host_resource_get_git-sub
  1292. setup_host_resource () {
  1293. local subservice="$1" service_def location get cfg
  1294. service_def=$(get_compose_service_def "$subservice") || return 1
  1295. while read-0 location cfg; do
  1296. ## XXXvlab: will it be a git resources always ?
  1297. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1298. err "Hum, location '$location' does not seem to be a git directory."
  1299. return 1
  1300. fi
  1301. if [ -d "$location" ]; then
  1302. info "host resource '$location' already set up."
  1303. continue
  1304. fi
  1305. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1306. if [ -z "$get" ]; then
  1307. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1308. "specified for $DARKYELLOW$subservice$NORMAL."
  1309. return 1
  1310. fi
  1311. host_resource_get "$location" "$get" || return 1
  1312. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1313. }
  1314. export -f setup_host_resource
  1315. setup_host_resources () {
  1316. local service subservices subservice loaded
  1317. declare -A loaded
  1318. for service in "$@"; do
  1319. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1320. for subservice in $subservices; do
  1321. if [ "${loaded[$subservice]}" ]; then
  1322. ## Prevent double inclusion of same service if this
  1323. ## service is deps of two or more of your
  1324. ## requirements.
  1325. continue
  1326. fi
  1327. setup_host_resource "$service"
  1328. loaded[$subservice]=1
  1329. done
  1330. done
  1331. return 0
  1332. }
  1333. export -f setup_host_resources
  1334. ## Works on stdin
  1335. cfg-get-value () {
  1336. local key="$1" out
  1337. if [ -z "$key" ]; then
  1338. yaml_get_interpret || return 1
  1339. return 0
  1340. fi
  1341. if ! out=$(shyaml -y get-value "$key" 2>/dev/null); then
  1342. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1343. return 1
  1344. fi
  1345. echo "$out" | yaml_get_interpret
  1346. }
  1347. export -f cfg-get-value
  1348. relation-get () {
  1349. cfg-get-value "$1" < "$RELATION_DATA_FILE"
  1350. }
  1351. export -f relation-get
  1352. expand_vars() {
  1353. local unlikely_prefix="UNLIKELY_PREFIX"
  1354. content=$(cat -)
  1355. ## find first identifier not in content
  1356. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1357. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1358. size_prefix="${#unlikely_prefix}"
  1359. first_matching=$(echo "$remaining_lines" |
  1360. grep -v "^$unlikely_prefix$" |
  1361. uniq -w "$((size_prefix + 1))" -c |
  1362. sort -rn |
  1363. head -n 1)
  1364. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1365. first_matching="${first_matching#* }"
  1366. next_char=${first_matching:$size_prefix:1}
  1367. if [ "$next_char" != "0" ]; then
  1368. unlikely_prefix+="0"
  1369. else
  1370. unlikely_prefix+="1"
  1371. fi
  1372. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1373. done
  1374. eval "cat <<$unlikely_prefix
  1375. $content
  1376. $unlikely_prefix"
  1377. }
  1378. export -f expand_vars
  1379. yaml_get_interpret() {
  1380. local content tag
  1381. content=$(cat -)
  1382. tag=$(echo "$content" | shyaml -y get-value) || return 1
  1383. tag="${tag%% *}"
  1384. content=$(echo "$content" | shyaml get-value) || return 1
  1385. if ! [ "${tag:0:1}" == "!" ]; then
  1386. echo "$content" || return 1
  1387. return 0
  1388. fi
  1389. case "$tag" in
  1390. "!bash-stdout")
  1391. echo "$content" | bash || {
  1392. err "shell code didn't end with errorlevel 0"
  1393. return 1
  1394. }
  1395. ;;
  1396. "!var-expand")
  1397. echo "$content" | expand_vars || {
  1398. err "shell expansion failed"
  1399. return 1
  1400. }
  1401. ;;
  1402. *)
  1403. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1404. return 1
  1405. ;;
  1406. esac
  1407. }
  1408. export -f yaml_get_interpret
  1409. options-get () {
  1410. local key="$1" out
  1411. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1412. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1413. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1414. return 1
  1415. fi
  1416. echo "$out" | yaml_get_interpret
  1417. }
  1418. export -f options-get
  1419. relation-base-compose-get () {
  1420. local key="$1" out
  1421. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1422. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1423. return 1
  1424. fi
  1425. echo "$out" | yaml_get_interpret
  1426. }
  1427. export -f relation-base-compose-get
  1428. relation-target-compose-get () {
  1429. local key="$1" out
  1430. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1431. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1432. return 1
  1433. fi
  1434. echo "$out" | yaml_get_interpret
  1435. }
  1436. export -f relation-target-compose-get
  1437. relation-set () {
  1438. local key="$1" value="$2"
  1439. if [ -z "$RELATION_DATA_FILE" ]; then
  1440. err "$FUNCNAME: relation does not seems to be correctly setup."
  1441. return 1
  1442. fi
  1443. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1444. err "$FUNCNAME: can't read relation's data." >&2
  1445. return 1
  1446. fi
  1447. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1448. }
  1449. export -f relation-set
  1450. _config_merge() {
  1451. local config_filename="$1" mixin="$2"
  1452. touch "$config_filename" &&
  1453. merge_yaml "$config_filename" "$mixin" > "$config_filename.tmp" || return 1
  1454. mv "$config_filename.tmp" "$config_filename"
  1455. }
  1456. export -f _config_merge
  1457. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1458. config-add() {
  1459. local metadata="$1"
  1460. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1461. }
  1462. export -f config-add
  1463. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1464. init-config-add() {
  1465. local metadata="$1"
  1466. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1467. <(yaml_key_val_str "services" "$metadata")
  1468. }
  1469. export -f init-config-add
  1470. docker_get_uid() {
  1471. local service="$1" user="$2" uid
  1472. uid=$(cached_cmd_on_base_image "$service" "id -u \"$user\"") || {
  1473. debug "Failed to query for '$user' uid in ${DARKYELLOW}$service${NORMAL} base image."
  1474. return 1
  1475. }
  1476. info "uid from ${DARKYELLOW}$service${NORMAL} for user '$user' is '$uid'"
  1477. echo "$uid"
  1478. }
  1479. export -f docker_get_uid
  1480. logstdout() {
  1481. local name="$1"
  1482. sed -r 's%^%'"${name}"'> %g'
  1483. }
  1484. export -f logstdout
  1485. logstderr() {
  1486. local name="$1"
  1487. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1488. }
  1489. export -f logstderr
  1490. _run_service_relation () {
  1491. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1492. charm=$(get_service_charm "$service") || return 1
  1493. target_charm=$(get_service_charm "$target_service") || return 1
  1494. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1495. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1496. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1497. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1498. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1499. export BASE_SERVICE_NAME=$service
  1500. export BASE_CHARM_NAME=$charm
  1501. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1502. export TARGET_SERVICE_NAME=$target_service
  1503. export TARGET_CHARM_NAME=$target_charm
  1504. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1505. export RELATION_DATA_FILE
  1506. target_errlvl=0
  1507. if [ -z "$target_script_name" ]; then
  1508. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1509. else
  1510. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1511. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1512. RELATION_CONFIG="$relation_dir/config_provider"
  1513. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1514. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1515. {
  1516. (
  1517. SERVICE_NAME=$target_service
  1518. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1519. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1520. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1521. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1522. echo "$?" > "$relation_dir/target_errlvl"
  1523. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1524. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1525. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1526. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1527. "failed before outputing an errorlevel."
  1528. ((target_errlvl |= "1" ))
  1529. }
  1530. if [ -e "$RELATION_CONFIG" ]; then
  1531. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1532. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1533. rm "$RELATION_CONFIG"
  1534. ((target_errlvl |= "$?"))
  1535. fi
  1536. fi
  1537. if [ "$target_errlvl" == 0 ]; then
  1538. errlvl=0
  1539. if [ "$base_script_name" ]; then
  1540. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1541. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1542. RELATION_CONFIG="$relation_dir/config_providee"
  1543. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1544. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1545. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1546. {
  1547. (
  1548. SERVICE_NAME=$service
  1549. SERVICE_DATASTORE="$DATASTORE/$service"
  1550. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1551. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1552. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1553. echo "$?" > "$relation_dir/errlvl"
  1554. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1555. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1556. errlvl="$(cat "$relation_dir/errlvl")" || {
  1557. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1558. "failed before outputing an errorlevel."
  1559. ((errlvl |= "1" ))
  1560. }
  1561. if [ -e "$RELATION_CONFIG" ]; then
  1562. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1563. rm "$RELATION_CONFIG"
  1564. ((errlvl |= "$?" ))
  1565. fi
  1566. if [ "$errlvl" != 0 ]; then
  1567. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1568. fi
  1569. else
  1570. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1571. fi
  1572. else
  1573. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1574. fi
  1575. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1576. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1577. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1578. return 0
  1579. else
  1580. return 1
  1581. fi
  1582. }
  1583. export -f _run_service_relation
  1584. _get_compose_relations_cached () {
  1585. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1586. relation_name relation_def target_service
  1587. if [ -e "$cache_file" ]; then
  1588. #debug "$FUNCNAME: STATIC cache hit $1"
  1589. cat "$cache_file" &&
  1590. touch "$cache_file" || return 1
  1591. return 0
  1592. fi
  1593. (
  1594. set -o pipefail
  1595. if [ "$compose_service_def" ]; then
  1596. while read-0 relation_name relation_def; do
  1597. ## XXXvlab: could we use braces here instead of parenthesis ?
  1598. (
  1599. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1600. "str")
  1601. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  1602. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1603. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1604. ;;
  1605. "sequence")
  1606. while read-0 target_service; do
  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. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1610. ;;
  1611. "struct")
  1612. while read-0 target_service relation_config; do
  1613. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1614. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  1615. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1616. ;;
  1617. esac
  1618. ) </dev/null >> "$cache_file" || return 1
  1619. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1620. fi
  1621. )
  1622. if [ "$?" != 0 ]; then
  1623. err "Error while looking for compose relations."
  1624. rm -f "$cache_file" ## no cache
  1625. return 1
  1626. fi
  1627. [ -e "$cache_file" ] && cat "$cache_file"
  1628. return 0
  1629. }
  1630. export -f _get_compose_relations_cached
  1631. get_compose_relations () {
  1632. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1633. compose_def
  1634. if [ -e "$cache_file" ]; then
  1635. #debug "$FUNCNAME: SESSION cache hit $1"
  1636. cat "$cache_file"
  1637. return 0
  1638. fi
  1639. compose_def="$(get_compose_service_def "$service")" || return 1
  1640. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1641. if [ "$?" != 0 ]; then
  1642. rm -f "$cache_file" ## no cache
  1643. return 1
  1644. fi
  1645. cat "$cache_file"
  1646. }
  1647. export -f get_compose_relations
  1648. get_service_relations () {
  1649. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1650. s rn ts rc td
  1651. if [ -e "$cache_file" ]; then
  1652. #debug "$FUNCNAME: SESSION cache hit $1"
  1653. cat "$cache_file"
  1654. return 0
  1655. fi
  1656. if [ -z "$ALL_RELATIONS" ]; then
  1657. err "Can't access global \$ALL_RELATIONS"
  1658. return 1
  1659. fi
  1660. while read-0 s rn ts rc td; do
  1661. [[ "$s" == "$service" ]] || continue
  1662. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  1663. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  1664. if [ "$?" != 0 ]; then
  1665. rm -f "$cache_file" ## no cache
  1666. return 1
  1667. fi
  1668. cat "$cache_file"
  1669. }
  1670. export -f get_service_relations
  1671. get_service_relation() {
  1672. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1673. rn ts rc td
  1674. if [ -e "$cache_file" ]; then
  1675. #debug "$FUNCNAME: SESSION cache hit $1"
  1676. cat "$cache_file"
  1677. return 0
  1678. fi
  1679. while read-0 rn ts rc td; do
  1680. [ "$relation" == "$rn" ] && {
  1681. printf "%s\0" "$ts" "$rc" "$td"
  1682. break
  1683. }
  1684. done < <(get_service_relations "$service") > "$cache_file"
  1685. if [ "$?" != 0 ]; then
  1686. rm -f "$cache_file" ## no cache
  1687. return 1
  1688. fi
  1689. cat "$cache_file"
  1690. }
  1691. export -f get_service_relation
  1692. _get_charm_metadata_uses() {
  1693. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  1694. if [ -e "$cache_file" ]; then
  1695. #debug "$FUNCNAME: SESSION cache hit $1"
  1696. cat "$cache_file" || return 1
  1697. return 0
  1698. fi
  1699. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  1700. }
  1701. export -f _get_charm_metadata_uses
  1702. _get_service_metadata() {
  1703. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1704. charm
  1705. if [ -e "$cache_file" ]; then
  1706. #debug "$FUNCNAME: SESSION cache hit $1"
  1707. cat "$cache_file"
  1708. return 0
  1709. fi
  1710. charm="$(get_service_charm "$service")" || return 1
  1711. charm.metadata "$charm" > "$cache_file"
  1712. if [ "$?" != 0 ]; then
  1713. rm -f "$cache_file" ## no cache
  1714. return 1
  1715. fi
  1716. cat "$cache_file"
  1717. }
  1718. export -f _get_service_metadata
  1719. _get_service_uses() {
  1720. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1721. metadata
  1722. if [ -e "$cache_file" ]; then
  1723. #debug "$FUNCNAME: SESSION cache hit $1"
  1724. cat "$cache_file"
  1725. return 0
  1726. fi
  1727. metadata="$(_get_service_metadata "$service")" || return 1
  1728. _get_charm_metadata_uses "$metadata" > "$cache_file"
  1729. if [ "$?" != 0 ]; then
  1730. rm -f "$cache_file" ## no cache
  1731. return 1
  1732. fi
  1733. cat "$cache_file"
  1734. }
  1735. export -f _get_service_uses
  1736. _get_services_uses() {
  1737. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1738. service rn rd
  1739. if [ -e "$cache_file" ]; then
  1740. #debug "$FUNCNAME: SESSION cache hit $1"
  1741. cat "$cache_file"
  1742. return 0
  1743. fi
  1744. for service in "$@"; do
  1745. _get_service_uses "$service" | while read-0 rn rd; do
  1746. printf "%s\0" "$service" "$rn" "$rd"
  1747. done
  1748. [ "${PIPESTATUS[0]}" == 0 ] || {
  1749. return 1
  1750. }
  1751. done > "${cache_file}.wip"
  1752. mv "${cache_file}"{.wip,} &&
  1753. cat "$cache_file" || return 1
  1754. }
  1755. export -f _get_services_uses
  1756. _get_provides_provides() {
  1757. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1758. service rn rd
  1759. if [ -e "$cache_file" ]; then
  1760. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  1761. cat "$cache_file"
  1762. return 0
  1763. fi
  1764. type=$(printf "%s" "$provides" | shyaml get-type)
  1765. case "$type" in
  1766. sequence)
  1767. while read-0 prov; do
  1768. printf "%s\0" "$prov" ""
  1769. done < <(echo "$provides" | shyaml get-values-0)
  1770. ;;
  1771. struct)
  1772. printf "%s" "$provides" | shyaml key-values-0
  1773. ;;
  1774. str)
  1775. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  1776. ;;
  1777. *)
  1778. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  1779. return 1
  1780. esac | tee "$cache_file"
  1781. return "${PIPESTATUS[0]}"
  1782. }
  1783. _get_metadata_provides() {
  1784. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1785. service rn rd
  1786. if [ -e "$cache_file" ]; then
  1787. #debug "$FUNCNAME: CACHEDIR cache hit"
  1788. cat "$cache_file"
  1789. return 0
  1790. fi
  1791. provides=$(printf "%s" "$metadata" | shyaml get-value -y -q provides "")
  1792. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  1793. _get_provides_provides "$provides" | tee "$cache_file"
  1794. return "${PIPESTATUS[0]}"
  1795. }
  1796. _get_services_provides() {
  1797. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1798. service rn rd
  1799. if [ -e "$cache_file" ]; then
  1800. #debug "$FUNCNAME: SESSION cache hit $1"
  1801. cat "$cache_file"
  1802. return 0
  1803. fi
  1804. ## YYY: replace the inner loop by a cached function
  1805. for service in "$@"; do
  1806. metadata="$(_get_service_metadata "$service")" || return 1
  1807. while read-0 rn rd; do
  1808. printf "%s\0" "$service" "$rn" "$rd"
  1809. done < <(_get_metadata_provides "$metadata")
  1810. done > "$cache_file"
  1811. if [ "$?" != 0 ]; then
  1812. rm -f "$cache_file" ## no cache
  1813. return 1
  1814. fi
  1815. cat "$cache_file"
  1816. }
  1817. export -f _get_services_provides
  1818. _get_charm_provides() {
  1819. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(charm.store_metadata_hash)"
  1820. if [ -e "$cache_file" ]; then
  1821. #debug "$FUNCNAME: SESSION cache hit"
  1822. cat "$cache_file"
  1823. return 0
  1824. fi
  1825. start="$SECONDS"
  1826. debug "Getting charm provider list..."
  1827. while read-0 charm _ realpath metadata; do
  1828. metadata="$(charm.metadata "$charm")" || continue
  1829. # echo "reading $charm" >&2
  1830. while read-0 rn rd; do
  1831. printf "%s\0" "$charm" "$rn" "$rd"
  1832. done < <(_get_metadata_provides "$metadata")
  1833. done < <(charm.ls) | tee "$cache_file"
  1834. errlvl="${PIPESTATUS[0]}"
  1835. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  1836. return "$errlvl"
  1837. }
  1838. _get_charm_providing() {
  1839. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1840. relation="$1"
  1841. if [ -e "$cache_file" ]; then
  1842. #debug "$FUNCNAME: SESSION cache hit $1"
  1843. cat "$cache_file"
  1844. return 0
  1845. fi
  1846. while read-0 charm relation_name relation_def; do
  1847. [ "$relation_name" == "$relation" ] || continue
  1848. printf "%s\0" "$charm" "$relation_def"
  1849. done < <(_get_charm_provides) > "$cache_file"
  1850. if [ "$?" != 0 ]; then
  1851. rm -f "$cache_file" ## no cache
  1852. return 1
  1853. fi
  1854. cat "$cache_file"
  1855. }
  1856. _get_services_providing() {
  1857. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1858. relation="$1"
  1859. shift ## services is "$@"
  1860. if [ -e "$cache_file" ]; then
  1861. #debug "$FUNCNAME: SESSION cache hit $1"
  1862. cat "$cache_file"
  1863. return 0
  1864. fi
  1865. while read-0 service relation_name relation_def; do
  1866. [ "$relation_name" == "$relation" ] || continue
  1867. printf "%s\0" "$service" "$relation_def"
  1868. done < <(_get_services_provides "$@") > "$cache_file"
  1869. if [ "$?" != 0 ]; then
  1870. rm -f "$cache_file" ## no cache
  1871. return 1
  1872. fi
  1873. cat "$cache_file"
  1874. }
  1875. export -f _get_services_provides
  1876. _out_new_relation_from_defs() {
  1877. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  1878. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1879. ## YYYvlab: should be seen even in no debug mode no ?
  1880. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1881. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1882. td=${td:-True}
  1883. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  1884. printf "%s\0" "$service" "$relation_name" "$ts" "$rc" "$td"
  1885. }
  1886. get_all_relations () {
  1887. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1888. services
  1889. if [ -e "${cache_file}" ]; then
  1890. #debug "$FUNCNAME: SESSION cache hit $1"
  1891. cat "${cache_file}"
  1892. return 0
  1893. fi
  1894. declare -A services
  1895. services_uses=()
  1896. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1897. _get_services_uses "$@" || return 1
  1898. array_read-0 services_uses < <(_get_services_uses "$@")
  1899. services_provides=()
  1900. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1901. _get_services_provides "$@" || return 1
  1902. array_read-0 services_provides < <(_get_services_provides "$@")
  1903. for service in "$@"; do
  1904. services[$service]=1
  1905. done
  1906. all_services=("$@")
  1907. while [ "${#all_services[@]}" != 0 ]; do
  1908. array_pop all_services service
  1909. while read-0 relation_name ts relation_config tech_dep; do
  1910. printf "%s\0" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  1911. ## adding target services ?
  1912. [ "${services[$ts]}" ] && continue
  1913. array_read-0 services_uses < <(_get_services_uses "$ts")
  1914. all_services+=("$ts")
  1915. services[$ts]=1
  1916. done < <(get_compose_relations "$service")
  1917. done > "${cache_file}.wip"
  1918. while true; do
  1919. changed=
  1920. new_services_uses=()
  1921. summon=()
  1922. required=()
  1923. recommended=()
  1924. optional=()
  1925. while [ "${#services_uses[@]}" != 0 ]; do
  1926. service="${services_uses[0]}"
  1927. relation_name="${services_uses[1]}"
  1928. relation_def="${services_uses[2]}"
  1929. services_uses=("${services_uses[@]:3}")
  1930. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1931. ## is this "use" declaration satisfied ?
  1932. found=
  1933. while read-0 s rn ts rc td; do
  1934. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  1935. if [ "$default_options" ]; then
  1936. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  1937. fi
  1938. found="$ts"
  1939. fi
  1940. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td"
  1941. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  1942. mv "${cache_file}.wip.new" "${cache_file}.wip"
  1943. if [ "$found" ]; then ## this "use" declaration was satisfied
  1944. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation " \
  1945. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  1946. continue
  1947. fi
  1948. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  1949. case "$auto" in
  1950. "pair")
  1951. service_list=()
  1952. array_read-0 service_list < <(array_keys_to_stdin services)
  1953. providers=()
  1954. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  1955. if [ "${#providers[@]}" == 1 ]; then
  1956. ts="${providers[0]}"
  1957. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  1958. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  1959. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  1960. "${providers_def[0]}" "$relation_def" \
  1961. >> "${cache_file}.wip"
  1962. ## Adding service
  1963. [ "${services[$ts]}" ] && continue
  1964. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  1965. services[$ts]=1
  1966. changed=1
  1967. continue
  1968. elif [ "${#providers[@]}" -gt 1 ]; then
  1969. msg=""
  1970. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  1971. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  1972. "(> 1 provider)."
  1973. continue
  1974. else
  1975. : ## Do nothing
  1976. fi
  1977. ;;
  1978. "summon")
  1979. summon+=("$service" "$relation_name" "$relation_def")
  1980. ;;
  1981. ""|null|disable|disabled)
  1982. :
  1983. ;;
  1984. *)
  1985. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  1986. return 1
  1987. ;;
  1988. esac
  1989. constraint=$(echo "$relation_def" | shyaml get-value constraint auto-pair 2>/dev/null)
  1990. case "$constraint" in
  1991. "required")
  1992. required+=("$service" "$relation_name" "$relation_def")
  1993. ;;
  1994. "recommended")
  1995. recommended+=("$service" "$relation_name" "$relation_def")
  1996. ;;
  1997. "optional")
  1998. optional+=("$service" "$relation_name" "$relation_def")
  1999. ;;
  2000. *)
  2001. err "Invalid ${WHITE}constraint${NORMAL} value '$contraint'."
  2002. return 1
  2003. ;;
  2004. esac
  2005. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  2006. done
  2007. services_uses=("${new_services_uses[@]}")
  2008. if [ "$changed" ]; then
  2009. continue
  2010. fi
  2011. ## situation is stable
  2012. if [ "${#summon[@]}" != 0 ]; then
  2013. while [ "${#summon[@]}" != 0 ]; do
  2014. service="${summon[0]}"
  2015. relation_name="${summon[1]}"
  2016. relation_def="${summon[2]}"
  2017. summon=("${summon[@]:3}")
  2018. providers=()
  2019. providers_def=()
  2020. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  2021. if [ "${#providers[@]}" == 0 ]; then
  2022. die "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  2023. fi
  2024. if [ "${#providers[@]}" -gt 1 ]; then
  2025. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2026. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  2027. "(> 1 provider). Choosing first."
  2028. fi
  2029. ts="${providers[0]}"
  2030. ## YYYvlab: should be seen even in no debug mode no ?
  2031. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  2032. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  2033. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  2034. "${providers_def[0]}" "$relation_def" \
  2035. >> "${cache_file}.wip"
  2036. ## Adding service
  2037. [ "${services[$ts]}" ] && continue
  2038. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  2039. services[$ts]=1
  2040. changed=1
  2041. done
  2042. continue
  2043. fi
  2044. [ "$NO_CONSTRAINT_CHECK" ] && break
  2045. if [ "${#required[@]}" != 0 ]; then
  2046. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  2047. err "Required relations not satisfied"
  2048. return 1
  2049. fi
  2050. if [ "${#recommended[@]}" != 0 ]; then
  2051. ## make recommendation
  2052. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  2053. fi
  2054. if [ "${#optional[@]}" != 0 ]; then
  2055. ## inform about options
  2056. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  2057. fi
  2058. # if [ "${#required[@]}" != 0 ]; then
  2059. # err "Required relations not satisfied"
  2060. # return 1
  2061. # fi
  2062. if [ "${#recommended[@]}" != 0 ]; then
  2063. warn "Recommended relations not satisfied"
  2064. fi
  2065. break
  2066. done
  2067. if [ "$?" != 0 ]; then
  2068. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2069. return 1
  2070. fi
  2071. export ALL_RELATIONS="$cache_file"
  2072. mv "${cache_file}"{.wip,}
  2073. cat "$cache_file"
  2074. }
  2075. export -f get_all_relations
  2076. _display_solves() {
  2077. local array_name="$1" by_relation msg
  2078. ## inform about options
  2079. msg=""
  2080. declare -A by_relation
  2081. while read-0 service relation_name relation_def; do
  2082. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2083. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2084. if [ -z "$solves" ]; then
  2085. continue
  2086. fi
  2087. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2088. if [ "$auto" == "pair" ]; then
  2089. requirement="add provider in cluster to auto-pair"
  2090. else
  2091. requirement="add explicit relation"
  2092. fi
  2093. while read-0 name def; do
  2094. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2095. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2096. done < <(array_values_to_stdin "$array_name")
  2097. while read-0 relation_name message; do
  2098. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2099. "$relation_name" "$message" )"
  2100. done < <(array_kv_to_stdin by_relation)
  2101. if [ "$msg" ]; then
  2102. printf "%s\n" "${msg:1}"
  2103. fi
  2104. }
  2105. get_compose_relation_def() {
  2106. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2107. while read-0 relation_name target_service relation_config tech_dep; do
  2108. [ "$relation_name" == "$relation" ] || continue
  2109. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2110. done < <(get_compose_relations "$service") || return 1
  2111. }
  2112. export -f get_compose_relation_def
  2113. run_service_relations () {
  2114. local service services loaded subservices subservice
  2115. PROJECT_NAME=$(get_default_project_name) || return 1
  2116. export PROJECT_NAME
  2117. declare -A loaded
  2118. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2119. for service in $subservices; do
  2120. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2121. for subservice in $(get_service_deps "$service") "$service"; do
  2122. [ "${loaded[$subservice]}" ] && continue
  2123. export BASE_SERVICE_NAME=$service
  2124. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2125. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2126. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2127. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2128. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2129. while read-0 relation_name target_service relation_config tech_dep; do
  2130. export relation_config
  2131. export TARGET_SERVICE_NAME=$target_service
  2132. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2133. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2134. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2135. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2136. Wrap "${wrap_opts[@]}" -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2137. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2138. EOF
  2139. done < <(get_service_relations "$subservice") || return 1
  2140. loaded[$subservice]=1
  2141. done
  2142. done
  2143. }
  2144. export -f run_service_relations
  2145. _run_service_action_direct() {
  2146. local service="$1" action="$2" charm _dummy
  2147. shift; shift
  2148. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  2149. if read-0 _dummy || [ "$_dummy" ]; then
  2150. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2151. return 1
  2152. fi
  2153. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2154. export state_tmpdir
  2155. {
  2156. (
  2157. set +e ## Prevents unwanted leaks from parent shell
  2158. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2159. export METADATA_CONFIG=$(charm.metadata "$charm")
  2160. export SERVICE_NAME=$service
  2161. export ACTION_NAME=$action
  2162. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2163. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2164. export SERVICE_DATASTORE="$DATASTORE/$service"
  2165. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2166. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2167. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2168. echo "$?" > "$action_errlvl_file"
  2169. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2170. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2171. if ! [ -e "$action_errlvl_file" ]; then
  2172. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2173. "to output an errlvl"
  2174. return 1
  2175. fi
  2176. return "$(cat "$action_errlvl_file")"
  2177. }
  2178. export -f _run_service_action_direct
  2179. _run_service_action_relation() {
  2180. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2181. shift; shift
  2182. read-0 charm target_service target_charm relation_name relation_config || true
  2183. if read-0 _dummy || [ "$_dummy" ]; then
  2184. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2185. return 1
  2186. fi
  2187. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  2188. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2189. export state_tmpdir
  2190. {
  2191. (
  2192. set +e ## Prevents unwanted leaks from parent shell
  2193. export METADATA_CONFIG=$(charm.metadata "$charm")
  2194. export SERVICE_NAME=$service
  2195. export RELATION_TARGET_SERVICE="$target_service"
  2196. export RELATION_TARGET_CHARM="$target_charm"
  2197. export RELATION_BASE_SERVICE="$service"
  2198. export RELATION_BASE_CHARM="$charm"
  2199. export ACTION_NAME=$action
  2200. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2201. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2202. export SERVICE_DATASTORE="$DATASTORE/$service"
  2203. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2204. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2205. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2206. echo "$?" > "$action_errlvl_file"
  2207. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2208. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2209. if ! [ -e "$action_errlvl_file" ]; then
  2210. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2211. "to output an errlvl"
  2212. return 1
  2213. fi
  2214. return "$(cat "$action_errlvl_file")"
  2215. }
  2216. export -f _run_service_action_relation
  2217. get_relation_data_dir() {
  2218. local service="$1" target_service="$2" relation_name="$3" \
  2219. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2220. if [ -e "$cache_file" ]; then
  2221. # debug "$FUNCNAME: cache hit ($*)"
  2222. cat "$cache_file"
  2223. return 0
  2224. fi
  2225. project=$(get_default_project_name) || return 1
  2226. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2227. if ! [ -d "$relation_dir" ]; then
  2228. mkdir -p "$relation_dir" || return 1
  2229. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2230. fi
  2231. echo "$relation_dir" | tee "$cache_file"
  2232. }
  2233. export -f get_relation_data_dir
  2234. get_relation_data_file() {
  2235. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2236. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2237. relation_data_file="$relation_dir/data"
  2238. new=
  2239. if [ -e "$relation_data_file" ]; then
  2240. ## Has reference changed ?
  2241. new_md5=$(echo "$relation_config" | md5_compat)
  2242. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2243. new=true
  2244. fi
  2245. else
  2246. new=true
  2247. fi
  2248. if [ "$new" ]; then
  2249. echo "$relation_config" > "$relation_data_file"
  2250. chmod go-rwx "$relation_data_file" ## protecting this file
  2251. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2252. fi
  2253. echo "$relation_data_file"
  2254. }
  2255. export -f get_relation_data_file
  2256. has_service_action () {
  2257. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2258. charm target_charm relation_name target_service relation_config _tech_dep
  2259. if [ -e "$cache_file" ]; then
  2260. # debug "$FUNCNAME: cache hit ($*)"
  2261. cat "$cache_file"
  2262. return 0
  2263. fi
  2264. charm=$(get_service_charm "$service") || return 1
  2265. ## Action directly provided ?
  2266. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  2267. echo -en "direct\0$charm" | tee "$cache_file"
  2268. return 0
  2269. fi
  2270. ## Action provided by relation ?
  2271. while read-0 relation_name target_service relation_config _tech_dep; do
  2272. target_charm=$(get_service_charm "$target_service") || return 1
  2273. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  2274. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  2275. return 0
  2276. fi
  2277. done < <(get_service_relations "$service")
  2278. return 1
  2279. # master=$(get_top_master_service_for_service "$service")
  2280. # [ "$master" == "$charm" ] && return 1
  2281. # has_service_action "$master" "$action"
  2282. }
  2283. export -f has_service_action
  2284. run_service_action () {
  2285. local service="$1" action="$2"
  2286. shift ; shift
  2287. {
  2288. if ! read-0 action_type; then
  2289. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2290. info " Add an executable script to 'actions/$action' to implement action."
  2291. return 1
  2292. fi
  2293. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  2294. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2295. } < <(has_service_action "$service" "$action")
  2296. }
  2297. export -f run_service_action
  2298. get_compose_relation_config() {
  2299. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2300. if [ -e "$cache_file" ]; then
  2301. # debug "$FUNCNAME: cache hit ($*)"
  2302. cat "$cache_file"
  2303. return 0
  2304. fi
  2305. compose_service_def=$(get_compose_service_def "$service") || return 1
  2306. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2307. }
  2308. export -f get_compose_relation_config
  2309. # ## Return key-values-0
  2310. # get_compose_relation_config_for_service() {
  2311. # local service=$1 relation_name=$2 relation_config
  2312. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2313. # if ! relation_config=$(
  2314. # echo "$compose_service_relations" |
  2315. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2316. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2317. # "relation config in compose configuration."
  2318. # return 1
  2319. # fi
  2320. # if [ -z "$relation_config" ]; then
  2321. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2322. # return 1
  2323. # fi
  2324. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2325. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2326. # return 1
  2327. # fi
  2328. # }
  2329. # export -f get_compose_relation_config_for_service
  2330. _get_container_relation() {
  2331. local metadata=$1 found relation_name relation_def
  2332. found=
  2333. while read-0 relation_name relation_def; do
  2334. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2335. found="$relation_name"
  2336. break
  2337. }
  2338. done < <(_get_charm_metadata_uses "$metadata")
  2339. if [ -z "$found" ]; then
  2340. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2341. "${WHITE}scope${NORMAL} set to 'container'."
  2342. fi
  2343. printf "%s" "$found"
  2344. }
  2345. _get_master_service_for_service_cached () {
  2346. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2347. charm requires master_charm target_charm target_service service_def found
  2348. if [ -e "$cache_file" ]; then
  2349. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2350. cat "$cache_file" &&
  2351. touch "$cache_file" || return 1
  2352. return 0
  2353. fi
  2354. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2355. ## just return service name
  2356. echo "$service" | tee "$cache_file"
  2357. return 0
  2358. fi
  2359. ## Action provided by relation ?
  2360. container_relation=$(_get_container_relation "$metadata")
  2361. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2362. if [ -z "$target_service" ]; then
  2363. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2364. "${DARKYELLOW}$service$NORMAL compose definition."
  2365. err ${FUNCNAME[@]}
  2366. return 1
  2367. fi
  2368. echo "$target_service" | tee "$cache_file"
  2369. }
  2370. export -f _get_master_service_for_service_cached
  2371. get_master_service_for_service() {
  2372. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2373. charm metadata result
  2374. if [ -e "$cache_file" ]; then
  2375. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2376. cat "$cache_file" || return 1
  2377. return 0
  2378. fi
  2379. charm=$(get_service_charm "$service") || return 1
  2380. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2381. metadata=""
  2382. warn "No charm $DARKPINK$charm$NORMAL found."
  2383. }
  2384. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2385. echo "$result" | tee "$cache_file" || return 1
  2386. }
  2387. export -f get_master_service_for_service
  2388. get_top_master_service_for_service() {
  2389. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2390. current_service
  2391. if [ -e "$cache_file" ]; then
  2392. # debug "$FUNCNAME: cache hit ($*)"
  2393. cat "$cache_file"
  2394. return 0
  2395. fi
  2396. current_service="$service"
  2397. while true; do
  2398. master_service=$(get_master_service_for_service "$current_service") || return 1
  2399. [ "$master_service" == "$current_service" ] && break
  2400. current_service="$master_service"
  2401. done
  2402. echo "$current_service" | tee "$cache_file"
  2403. return 0
  2404. }
  2405. export -f get_top_master_service_for_service
  2406. ##
  2407. ## The result is a mixin that is not always a complete valid
  2408. ## docker-compose entry (thinking of subordinates). The result
  2409. ## will be merge with master charms.
  2410. _get_docker_compose_mixin_from_metadata_cached() {
  2411. local service="$1" charm="$2" metadata="$3" \
  2412. has_build_dir="$4" \
  2413. cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2414. metadata_file metadata volumes docker_compose subordinate image mixin mixins
  2415. if [ -e "$cache_file" ]; then
  2416. #debug "$FUNCNAME: STATIC cache hit $1"
  2417. cat "$cache_file" &&
  2418. touch "$cache_file" || return 1
  2419. return 0
  2420. fi
  2421. mixins=("$(echo -en "labels:\n- compose.charm=$charm")")
  2422. if [ "$metadata" ]; then
  2423. ## resources to volumes
  2424. volumes=$(
  2425. for resource_type in data config; do
  2426. while read-0 resource; do
  2427. eval "echo \" - \$${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2428. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2429. done
  2430. while read-0 resource; do
  2431. if [[ "$resource" == /*:/*:* ]]; then
  2432. echo " - $resource"
  2433. elif [[ "$resource" == /*:/* ]]; then
  2434. echo " - $resource:rw"
  2435. elif [[ "$resource" == /*:* ]]; then
  2436. echo " - ${resource%%:*}:$resource"
  2437. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2438. echo " - $resource:$resource:rw"
  2439. else
  2440. die "Invalid host-resource specified in 'metadata.yml'."
  2441. fi
  2442. done < <(printf "%s" "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2443. while read-0 resource; do
  2444. dest="$(charm.get_dir "$charm")/resources$resource"
  2445. if ! [ -e "$dest" ]; then
  2446. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2447. fi
  2448. echo " - $dest:$resource:ro"
  2449. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2450. ) || return 1
  2451. if [ "$volumes" ]; then
  2452. mixins+=("volumes:"$'\n'"$volumes")
  2453. fi
  2454. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2455. if [ "$type" != "run-once" ]; then
  2456. mixins+=("restart: unless-stopped")
  2457. fi
  2458. docker_compose=$(printf "%s" "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null) || true
  2459. if [ "$docker_compose" ]; then
  2460. mixins+=("$docker_compose")
  2461. fi
  2462. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2463. subordinate=true
  2464. fi
  2465. fi
  2466. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2467. [ "$image" == "None" ] && image=""
  2468. if [ "$image" ]; then
  2469. if [ "$subordinate" ]; then
  2470. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2471. return 1
  2472. fi
  2473. mixins+=("image: $image")
  2474. elif [ "$has_build_dir" ]; then
  2475. if [ "$subordinate" ]; then
  2476. err "Subordinate charm can not have a 'build' sub directory."
  2477. return 1
  2478. fi
  2479. mixins+=("build: $(charm.get_dir "$charm")/build")
  2480. fi
  2481. mixin=$(merge_yaml_str "${mixins[@]}") || {
  2482. err "Failed to merge mixins from ${DARKPINK}${charm}${NORMAL} metadata."
  2483. return 1
  2484. }
  2485. echo "$mixin" | tee "$cache_file"
  2486. }
  2487. export -f _get_docker_compose_mixin_from_metadata_cached
  2488. get_docker_compose_mixin_from_metadata() {
  2489. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2490. if [ -e "$cache_file" ]; then
  2491. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2492. cat "$cache_file"
  2493. return 0
  2494. fi
  2495. charm=$(get_service_charm "$service") || return 1
  2496. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2497. has_build_dir=
  2498. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2499. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2500. echo "$mixin" | tee "$cache_file"
  2501. }
  2502. export -f get_docker_compose_mixin_from_metadata
  2503. _save() {
  2504. local name="$1"
  2505. cat - | tee -a "$docker_compose_dir/.data/$name"
  2506. }
  2507. export -f _save
  2508. get_default_project_name() {
  2509. if [ "$DEFAULT_PROJECT_NAME" ]; then
  2510. echo "$DEFAULT_PROJECT_NAME"
  2511. return 0
  2512. fi
  2513. compose_yml_location="$(get_compose_yml_location)" || return 1
  2514. if [ "$compose_yml_location" ]; then
  2515. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2516. name="$(basename "$(dirname "$normalized_path")")"
  2517. echo "${name%%-deploy}"
  2518. return 0
  2519. fi
  2520. fi
  2521. echo "orphan"
  2522. return 0
  2523. }
  2524. export -f get_default_project_name
  2525. get_running_compose_containers() {
  2526. ## XXXvlab: docker bug: there will be a final newline anyway
  2527. docker ps --filter label="compose.service" --format='{{.ID}}'
  2528. }
  2529. export -f get_running_compose_containers
  2530. get_volumes_for_container() {
  2531. local container="$1"
  2532. docker inspect \
  2533. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2534. "$container"
  2535. }
  2536. export -f get_volumes_for_container
  2537. is_volume_used() {
  2538. local volume="$1" container_id src dst
  2539. while read container_id; do
  2540. while read-0 src dst; do
  2541. [[ "$src" == "$volume"/* ]] && return 0
  2542. done < <(get_volumes_for_container "$container_id")
  2543. done < <(get_running_compose_containers)
  2544. return 1
  2545. }
  2546. export -f is_volume_used
  2547. clean_unused_docker_compose() {
  2548. for f in /var/lib/compose/docker-compose/*; do
  2549. [ -e "$f" ] || continue
  2550. is_volume_used "$f" && continue
  2551. debug "Cleaning unused docker-compose ${f##*/}"
  2552. rm -rf "$f" || return 1
  2553. done
  2554. }
  2555. export -f clean_unused_docker_compose
  2556. stdin_get_hash() {
  2557. local sha
  2558. sha=$(sha256sum) || return 1
  2559. sha=${sha:0:64}
  2560. echo "$sha"
  2561. }
  2562. export -f stdin_get_hash
  2563. file_get_hash() {
  2564. stdin_get_hash < "$1" || return 1
  2565. }
  2566. export -f file_get_hash
  2567. docker_compose_store() {
  2568. local file="$1" sha
  2569. sha=$(file_get_hash "$file") || return 1
  2570. project=$(get_default_project_name) || return 1
  2571. dst="/var/lib/compose/docker-compose/$sha/$project"
  2572. mkdir -p "$dst" || return 1
  2573. cat <<EOF > "$dst/.env" || return 1
  2574. DOCKER_COMPOSE_PATH=$dst
  2575. EOF
  2576. cp "$file" "$dst/docker-compose.yml" || return 1
  2577. mkdir -p "$dst/bin" || return 1
  2578. cat <<EOF > "$dst/bin/dc" || return 1
  2579. #!/bin/bash
  2580. $(declare -f read-0)
  2581. docker_run_opts=()
  2582. while read-0 opt; do
  2583. docker_run_opts+=("\$opt")
  2584. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2585. docker_run_opts+=(
  2586. "-w" "$dst"
  2587. "--entrypoint" "/usr/local/bin/docker-compose"
  2588. )
  2589. [ -t 1 ] && {
  2590. docker_run_opts+=("-ti")
  2591. }
  2592. exec docker run --rm "\${docker_run_opts[@]}" "${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2593. EOF
  2594. chmod +x "$dst/bin/dc" || return 1
  2595. printf "%s" "$sha"
  2596. }
  2597. launch_docker_compose() {
  2598. local charm docker_compose_tmpdir docker_compose_dir
  2599. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2600. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2601. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2602. ## docker-compose will name network from the parent dir name
  2603. project=$(get_default_project_name)
  2604. mkdir -p "$docker_compose_tmpdir/$project"
  2605. docker_compose_dir="$docker_compose_tmpdir/$project"
  2606. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2607. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2608. # debug "Merging some config data in docker-compose.yml:"
  2609. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2610. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2611. fi
  2612. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2613. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2614. fi
  2615. ## XXXvlab: could be more specific and only link the needed charms
  2616. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2617. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2618. # if charm.exists "$charm"; then
  2619. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2620. # fi
  2621. # done
  2622. mkdir "$docker_compose_dir/.data"
  2623. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2624. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2625. fi
  2626. {
  2627. {
  2628. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2629. cd "/var/lib/compose/docker-compose/$sha/$project"
  2630. else
  2631. cd "$docker_compose_dir"
  2632. fi
  2633. if [ -f ".env" ]; then
  2634. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2635. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2636. fi
  2637. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2638. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2639. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2640. if [ "$DRY_COMPOSE_RUN" ]; then
  2641. echo docker-compose "$@"
  2642. else
  2643. docker-compose "$@"
  2644. fi
  2645. echo "$?" > "$docker_compose_dir/.data/errlvl"
  2646. } | _save stdout
  2647. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  2648. 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
  2649. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  2650. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  2651. fi
  2652. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  2653. if [ -z "$docker_compose_errlvl" ]; then
  2654. err "Something went wrong before you could gather docker-compose errorlevel."
  2655. return 1
  2656. fi
  2657. return "$docker_compose_errlvl"
  2658. }
  2659. export -f launch_docker_compose
  2660. get_compose_yml_location() {
  2661. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  2662. echo "$COMPOSE_YML_FILE"
  2663. return 0
  2664. fi
  2665. parent=$(while ! [ -f "./compose.yml" ]; do
  2666. [ "$PWD" == "/" ] && exit 0
  2667. cd ..
  2668. done; echo "$PWD"
  2669. )
  2670. if [ "$parent" ]; then
  2671. echo "$parent/compose.yml"
  2672. return 0
  2673. fi
  2674. ## XXXvlab: do we need this additional environment variable,
  2675. ## COMPOSE_YML_FILE is not sufficient ?
  2676. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  2677. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  2678. warn "No 'compose.yml' was found in current or parent dirs," \
  2679. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  2680. "(${DEFAULT_COMPOSE_FILE})"
  2681. return 0
  2682. fi
  2683. echo "$DEFAULT_COMPOSE_FILE"
  2684. return 0
  2685. fi
  2686. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  2687. return 0
  2688. }
  2689. export -f get_compose_yml_location
  2690. get_compose_yml_content() {
  2691. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  2692. if [ -e "$cache_file" ]; then
  2693. cat "$cache_file" &&
  2694. touch "$cache_file" || return 1
  2695. return 0
  2696. fi
  2697. if [ -z "$COMPOSE_YML_FILE" ]; then
  2698. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2699. fi
  2700. if [ -e "$COMPOSE_YML_FILE" ]; then
  2701. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2702. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  2703. err "Could not read '$COMPOSE_YML_FILE'."
  2704. return 1
  2705. }
  2706. else
  2707. debug "No compose file found. Using an empty one."
  2708. COMPOSE_YML_CONTENT=""
  2709. fi
  2710. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  2711. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  2712. if [ "$?" != 0 ]; then
  2713. outputed_something=
  2714. while IFS='' read -r line1 && IFS='' read -r line2; do
  2715. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2716. outputed_something=true
  2717. echo "$line1 $GRAY($line2)$NORMAL"
  2718. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2719. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2720. prefix " $GRAY|$NORMAL "
  2721. [ "$outputed_something" ] || {
  2722. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2723. echo "$output" | prefix " $GRAY|$NORMAL "
  2724. }
  2725. return 1
  2726. fi
  2727. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  2728. }
  2729. export -f get_compose_yml_content
  2730. get_default_target_services() {
  2731. local services=("$@")
  2732. if [ -z "${services[*]}" ]; then
  2733. if [ "$DEFAULT_SERVICES" ]; then
  2734. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  2735. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  2736. services="$DEFAULT_SERVICES"
  2737. else
  2738. err "No service provided."
  2739. return 1
  2740. fi
  2741. fi
  2742. echo "${services[*]}"
  2743. }
  2744. export -f get_default_target_services
  2745. get_master_services() {
  2746. local loaded master_service service
  2747. declare -A loaded
  2748. for service in "$@"; do
  2749. master_service=$(get_top_master_service_for_service "$service") || return 1
  2750. if [ "${loaded[$master_service]}" ]; then
  2751. continue
  2752. fi
  2753. echo "$master_service"
  2754. loaded["$master_service"]=1
  2755. done | xargs printf "%s "
  2756. return "${PIPESTATUS[0]}"
  2757. }
  2758. export -f get_master_services
  2759. get_current_docker_container_id() {
  2760. local line
  2761. line=$(cat "/proc/self/cpuset") || return 1
  2762. [[ "$line" == *docker* ]] || return 1
  2763. echo "${line##*/}"
  2764. }
  2765. export -f get_current_docker_container_id
  2766. ## if we are in a docker compose, we might want to know what is the
  2767. ## real host path of some local paths.
  2768. get_host_path() {
  2769. local path="$1"
  2770. path=$(realpath "$path") || return 1
  2771. container_id=$(get_current_docker_container_id) || {
  2772. print "%s" "$path"
  2773. return 0
  2774. }
  2775. biggest_dst=
  2776. current_src=
  2777. while read-0 src dst; do
  2778. [[ "$path" == "$dst"* ]] || continue
  2779. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  2780. biggest_dst="$dst"
  2781. current_src="$src"
  2782. fi
  2783. done < <(get_volumes_for_container "$container_id")
  2784. if [ "$current_src" ]; then
  2785. printf "%s" "$current_src"
  2786. else
  2787. return 1
  2788. fi
  2789. }
  2790. export -f get_host_path
  2791. _setup_state_dir() {
  2792. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2793. #debug "Creating temporary state directory in '$state_tmpdir'."
  2794. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  2795. # rm -rf \"$state_tmpdir\""
  2796. trap_add EXIT "rm -rf \"$state_tmpdir\""
  2797. }
  2798. get_docker_compose_help_msg() {
  2799. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2800. docker_compose_help_msg
  2801. if [ -e "$cache_file" ]; then
  2802. cat "$cache_file" &&
  2803. touch "$cache_file" || return 1
  2804. return 0
  2805. fi
  2806. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  2807. echo "$docker_compose_help_msg" |
  2808. tee "$cache_file" || return 1
  2809. }
  2810. get_docker_compose_usage() {
  2811. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2812. docker_compose_help_msg
  2813. if [ -e "$cache_file" ]; then
  2814. cat "$cache_file" &&
  2815. touch "$cache_file" || return 1
  2816. return 0
  2817. fi
  2818. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  2819. echo "$docker_compose_help_msg" |
  2820. grep -m 1 "^Usage:" -A 10000 |
  2821. egrep -m 1 "^\$" -B 10000 |
  2822. xargs printf "%s " |
  2823. sed -r 's/^Usage: //g' |
  2824. tee "$cache_file" || return 1
  2825. }
  2826. get_docker_compose_opts_help() {
  2827. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2828. docker_compose_help_msg
  2829. if [ -e "$cache_file" ]; then
  2830. cat "$cache_file" &&
  2831. touch "$cache_file" || return 1
  2832. return 0
  2833. fi
  2834. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2835. echo "$docker_compose_opts_help" |
  2836. grep '^Options:' -A 20000 |
  2837. tail -n +2 |
  2838. { cat ; echo; } |
  2839. egrep -m 1 "^\S*\$" -B 10000 |
  2840. head -n -1 |
  2841. tee "$cache_file" || return 1
  2842. }
  2843. get_docker_compose_commands_help() {
  2844. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2845. docker_compose_help_msg
  2846. if [ -e "$cache_file" ]; then
  2847. cat "$cache_file" &&
  2848. touch "$cache_file" || return 1
  2849. return 0
  2850. fi
  2851. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2852. echo "$docker_compose_opts_help" |
  2853. grep '^Commands:' -A 20000 |
  2854. tail -n +2 |
  2855. { cat ; echo; } |
  2856. egrep -m 1 "^\S*\$" -B 10000 |
  2857. head -n -1 |
  2858. tee "$cache_file" || return 1
  2859. }
  2860. get_docker_compose_opts_list() {
  2861. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2862. docker_compose_help_msg
  2863. if [ -e "$cache_file" ]; then
  2864. cat "$cache_file" &&
  2865. touch "$cache_file" || return 1
  2866. return 0
  2867. fi
  2868. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2869. echo "$docker_compose_opts_help" |
  2870. egrep "^\s+-" |
  2871. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2872. tee "$cache_file" || return 1
  2873. }
  2874. options_parser() {
  2875. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2876. printf "\0"
  2877. }
  2878. remove_options_in_option_help_msg() {
  2879. {
  2880. read-0 null
  2881. if [ "$null" ]; then
  2882. err "options parsing error, should start with an option line."
  2883. return 1
  2884. fi
  2885. while read-0 opt full_txt;do
  2886. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2887. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2888. for to_remove in "$@"; do
  2889. str_matches "$to_remove" $multi_opts $single_opts && {
  2890. continue 2
  2891. }
  2892. done
  2893. echo -n "$full_txt"
  2894. done
  2895. } < <(options_parser)
  2896. }
  2897. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2898. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2899. multi_opts_filter() {
  2900. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2901. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2902. tr ',' "\n" | xargs printf "%s "
  2903. }
  2904. single_opts_filter() {
  2905. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2906. tr ',' "\n" | xargs printf "%s "
  2907. }
  2908. get_docker_compose_multi_opts_list() {
  2909. local action="$1" opts_list
  2910. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2911. echo "$opts_list" | multi_opts_filter
  2912. }
  2913. get_docker_compose_single_opts_list() {
  2914. local action="$1" opts_list
  2915. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2916. echo "$opts_list" | single_opts_filter
  2917. }
  2918. display_commands_help() {
  2919. local charm_actions
  2920. echo
  2921. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2922. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2923. charm_actions_help=$(get_docker_charm_action_help) || return 1
  2924. if [ "$charm_actions_help" ]; then
  2925. echo
  2926. echo "${WHITE}Charm actions${NORMAL}:"
  2927. printf "%s\n" "$charm_actions_help" | \
  2928. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  2929. fi
  2930. }
  2931. get_docker_charm_action_help() {
  2932. local services service charm relation_name target_service relation_config \
  2933. target_charm
  2934. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  2935. for service in "${services[@]}"; do
  2936. out=$(
  2937. charm=$(get_service_charm "$service") || return 1
  2938. for action in $(charm.ls_direct_actions "$charm"); do
  2939. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  2940. done
  2941. while read-0 relation_name target_service _relation_config _tech_dep; do
  2942. target_charm=$(get_service_charm "$target_service") || return 1
  2943. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  2944. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  2945. done
  2946. done < <(get_compose_relations "$service")
  2947. )
  2948. if [ "$out" ]; then
  2949. echo " for ${DARKYELLOW}$service${NORMAL}:"
  2950. printf "%s\n" "$out"
  2951. fi
  2952. done
  2953. }
  2954. display_help() {
  2955. print_help
  2956. echo "${WHITE}Options${NORMAL}:"
  2957. echo " -h, --help Print this message and quit"
  2958. echo " (ignoring any other options)"
  2959. echo " -V, --version Print current version and quit"
  2960. echo " (ignoring any other options)"
  2961. echo " --dirs Display data dirs and quit"
  2962. echo " (ignoring any other options)"
  2963. echo " -v, --verbose Be more verbose"
  2964. echo " -q, --quiet Be quiet"
  2965. echo " -d, --debug Print full debugging information (sets also verbose)"
  2966. echo " --dry-compose-run If docker-compose will be run, only print out what"
  2967. echo " command line will be used."
  2968. echo " --rebuild-relations-to-service, -R SERVICE"
  2969. echo " Will rebuild all relations to given service"
  2970. echo " --add-compose-content, -Y YAML"
  2971. echo " Will merge some direct YAML with the current compose"
  2972. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  2973. filter_docker_compose_help_message
  2974. display_commands_help
  2975. }
  2976. _graph_service() {
  2977. local service="$1" base="$1"
  2978. charm=$(get_service_charm "$service") || return 1
  2979. metadata=$(charm.metadata "$charm") || return 1
  2980. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  2981. if [ "$subordinate" == "True" ]; then
  2982. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  2983. master_charm=
  2984. while read-0 relation_name relation; do
  2985. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  2986. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  2987. if [ -z "$interface" ]; then
  2988. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  2989. return 1
  2990. fi
  2991. ## Action provided by relation ?
  2992. target_service=
  2993. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  2994. [ "$interface" == "$relation_name" ] && {
  2995. target_service="$candidate_target_service"
  2996. break
  2997. }
  2998. done < <(get_service_relations "$service")
  2999. if [ -z "$target_service" ]; then
  3000. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  3001. "${DARKYELLOW}$service$NORMAL compose definition."
  3002. return 1
  3003. fi
  3004. master_service="$target_service"
  3005. master_charm=$(get_service_charm "$target_service") || return 1
  3006. break
  3007. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  3008. fi
  3009. _graph_node_service "$service" "$base" "$charm"
  3010. _graph_edge_service "$service" "$subordinate" "$master_service"
  3011. }
  3012. _graph_node_service() {
  3013. local service="$1" base="$2" charm="$3"
  3014. cat <<EOF
  3015. "$(_graph_node_service_label ${service})" [
  3016. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  3017. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  3018. color = $([ "$base" ] && echo "blue" || echo "black")
  3019. fillcolor = "white"
  3020. fontname = "Courier New"
  3021. shape = "Mrecord"
  3022. label =<$(_graph_node_service_content "$service")>
  3023. ];
  3024. EOF
  3025. }
  3026. _graph_edge_service() {
  3027. local service="$1" subordinate="$2" master_service="$3"
  3028. while read-0 relation_name target_service relation_config tech_dep; do
  3029. cat <<EOF
  3030. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  3031. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  3032. fontsize = 16
  3033. fontcolor = "black"
  3034. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  3035. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  3036. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  3037. arrowtail = odot
  3038. # arrowhead = dotlicurve
  3039. taillabel = "$relation_name" ];
  3040. EOF
  3041. done < <(get_service_relations "$service") || return 1
  3042. }
  3043. _graph_node_service_label() {
  3044. local service="$1"
  3045. echo "service_$service"
  3046. }
  3047. _graph_node_service_content() {
  3048. local service="$1"
  3049. charm=$(get_service_charm "$service") || return 1
  3050. cat <<EOF
  3051. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  3052. <tr>
  3053. <td bgcolor="black" align="center" colspan="2">
  3054. <font color="white">$service</font>
  3055. </td>
  3056. </tr>
  3057. $(if [ "$charm" != "$service" ]; then
  3058. cat <<EOF2
  3059. <tr>
  3060. <td align="left" port="r0">charm: $charm</td>
  3061. </tr>
  3062. EOF2
  3063. fi)
  3064. </table>
  3065. EOF
  3066. }
  3067. cla_contains () {
  3068. local e
  3069. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3070. return 1
  3071. }
  3072. filter_docker_compose_help_message() {
  3073. cat - |
  3074. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3075. s/docker-compose.yml/compose.yml/g;
  3076. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3077. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3078. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3079. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3080. }
  3081. graph() {
  3082. local services=("$@")
  3083. declare -A entries
  3084. cat <<EOF
  3085. digraph g {
  3086. graph [
  3087. fontsize=30
  3088. labelloc="t"
  3089. label=""
  3090. splines=true
  3091. overlap=false
  3092. #rankdir = "LR"
  3093. ];
  3094. ratio = auto;
  3095. EOF
  3096. for target_service in "$@"; do
  3097. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3098. for service in $services; do
  3099. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3100. if cla_contains "$service" "${services[@]}"; then
  3101. base=true
  3102. else
  3103. base=
  3104. fi
  3105. _graph_service "$service" "$base"
  3106. done
  3107. done
  3108. echo "}"
  3109. }
  3110. cached_wget() {
  3111. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3112. url="$1"
  3113. if [ -e "$cache_file" ]; then
  3114. cat "$cache_file"
  3115. touch "$cache_file"
  3116. return 0
  3117. fi
  3118. wget -O- "${url}" |
  3119. tee "$cache_file"
  3120. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3121. rm "$cache_file"
  3122. die "Unable to fetch '$url'."
  3123. return 1
  3124. fi
  3125. }
  3126. export -f cached_wget
  3127. [ "$SOURCED" ] && return 0
  3128. trap_add "EXIT" clean_cache
  3129. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3130. if [ -r /etc/default/charm ]; then
  3131. . /etc/default/charm
  3132. fi
  3133. if [ -r "/etc/default/$exname" ]; then
  3134. . "/etc/default/$exname"
  3135. fi
  3136. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3137. ## userdir ? and global /etc/compose.yml ?
  3138. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3139. /etc/default/compose /etc/compose/local.conf; do
  3140. [ -e "$cfgfile" ] || continue
  3141. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3142. done
  3143. fi
  3144. _setup_state_dir
  3145. mkdir -p "$CACHEDIR" || exit 1
  3146. ##
  3147. ## Argument parsing
  3148. ##
  3149. wrap_opts=()
  3150. services=()
  3151. remainder_args=()
  3152. compose_opts=()
  3153. compose_contents=()
  3154. action_opts=()
  3155. services_args=()
  3156. pos_arg_ct=0
  3157. no_hooks=
  3158. no_init=
  3159. action=
  3160. stage="main" ## switches from 'main', to 'action', 'remainder'
  3161. is_docker_compose_action=
  3162. rebuild_relations_to_service=()
  3163. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3164. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  3165. while read-0 arg; do
  3166. case "$stage" in
  3167. "main")
  3168. case "$arg" in
  3169. --help|-h)
  3170. no_init=true ; no_hooks=true ; no_relations=true
  3171. display_help
  3172. exit 0
  3173. ;;
  3174. --verbose|-v)
  3175. export VERBOSE=true
  3176. compose_opts+=("--verbose")
  3177. ;;
  3178. --quiet|-q)
  3179. export QUIET=true
  3180. export wrap_opts+=("-q")
  3181. ;;
  3182. --version|-V)
  3183. print_version
  3184. docker-compose --version
  3185. docker --version
  3186. exit 0
  3187. ;;
  3188. -f|--file)
  3189. read-0 value
  3190. [ -e "$value" ] || die "File $value doesn't exists"
  3191. export COMPOSE_YML_FILE="$value"
  3192. shift
  3193. ;;
  3194. -p|--project-name)
  3195. read-0 value
  3196. export DEFAULT_PROJECT_NAME="$value"
  3197. compose_opts+=("--project-name $value")
  3198. shift
  3199. ;;
  3200. --no-relations)
  3201. export no_relations=true
  3202. ;;
  3203. --no-hooks)
  3204. export no_hooks=true
  3205. ;;
  3206. --no-init)
  3207. export no_init=true
  3208. ;;
  3209. --rebuild-relations-to-service|-R)
  3210. read-0 value
  3211. rebuild_relations_to_service+=("$value")
  3212. shift
  3213. ;;
  3214. --debug)
  3215. export DEBUG=true
  3216. export VERBOSE=true
  3217. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3218. ;;
  3219. --add-compose-content|-Y)
  3220. read-0 value
  3221. compose_contents+=("$value")
  3222. shift
  3223. ;;
  3224. --dirs)
  3225. echo "CACHEDIR: $CACHEDIR"
  3226. echo "VARDIR: $VARDIR"
  3227. exit 0
  3228. ;;
  3229. --dry-compose-run)
  3230. export DRY_COMPOSE_RUN=true
  3231. ;;
  3232. --*|-*)
  3233. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3234. read-0 value
  3235. compose_opts+=("$arg" "$value")
  3236. shift;
  3237. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3238. compose_opts+=("$arg")
  3239. else
  3240. err "Unknown option '$arg'. Please check help:"
  3241. display_help >&2
  3242. exit 1
  3243. fi
  3244. ;;
  3245. *)
  3246. action="$arg"
  3247. stage="action"
  3248. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3249. is_docker_compose_action=true
  3250. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3251. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3252. if [ "$DC_MATCH_MULTI" ]; then
  3253. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3254. fi
  3255. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3256. pos_args=("${pos_args[@]:1}")
  3257. # echo "USAGE: $DC_USAGE"
  3258. # echo "pos_args: ${pos_args[@]}"
  3259. # echo "MULTI: $DC_MATCH_MULTI"
  3260. # echo "SINGLE: $DC_MATCH_SINGLE"
  3261. # exit 1
  3262. else
  3263. stage="remainder"
  3264. fi
  3265. ;;
  3266. esac
  3267. ;;
  3268. "action") ## Only for docker-compose actions
  3269. case "$arg" in
  3270. --help|-h)
  3271. no_init=true ; no_hooks=true ; no_relations=true
  3272. action_opts+=("$arg")
  3273. ;;
  3274. --*|-*)
  3275. if [ "$is_docker_compose_action" ]; then
  3276. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3277. read-0 value
  3278. action_opts+=("$arg" "$value")
  3279. shift
  3280. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3281. action_opts+=("$arg")
  3282. else
  3283. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3284. docker-compose "$action" --help |
  3285. filter_docker_compose_help_message >&2
  3286. exit 1
  3287. fi
  3288. fi
  3289. ;;
  3290. *)
  3291. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3292. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3293. services_args+=("$arg")
  3294. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3295. services_args=("$arg") || exit 1
  3296. stage="remainder"
  3297. else
  3298. action_posargs+=("$arg")
  3299. ((pos_arg_ct++))
  3300. fi
  3301. ;;
  3302. esac
  3303. ;;
  3304. "remainder")
  3305. remainder_args+=("$arg")
  3306. while read-0 arg; do
  3307. remainder_args+=("$arg")
  3308. done
  3309. break 3
  3310. ;;
  3311. esac
  3312. shift
  3313. done < <(cla.normalize "$@")
  3314. export compose_contents
  3315. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3316. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3317. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3318. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3319. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3320. aexport remainder_args
  3321. ##
  3322. ## Actual code
  3323. ##
  3324. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3325. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3326. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3327. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3328. ##
  3329. ## Get services in command line.
  3330. ##
  3331. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3332. action_service=${remainder_args[0]}
  3333. if [ -z "$action_service" ]; then
  3334. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3335. display_commands_help
  3336. exit 1
  3337. fi
  3338. remainder_args=("${remainder_args[@]:1}")
  3339. if has_service_action "$action_service" "$action" >/dev/null; then
  3340. is_service_action=true
  3341. {
  3342. read-0 action_type
  3343. case "$action_type" in
  3344. "relation")
  3345. read-0 _ target_service _target_charm relation_name
  3346. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3347. ;;
  3348. "direct")
  3349. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3350. ;;
  3351. esac
  3352. } < <(has_service_action "$action_service" "$action")
  3353. services_args=("$action_service")
  3354. else
  3355. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3356. fi
  3357. else
  3358. case "$action" in
  3359. ps|up)
  3360. if [ "${#services_args[@]}" == 0 ]; then
  3361. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3362. fi
  3363. ;;
  3364. config)
  3365. services_args=("${action_posargs[@]}")
  3366. ;;
  3367. esac
  3368. fi
  3369. NO_CONSTRAINT_CHECK=True
  3370. case "$action" in
  3371. up)
  3372. NO_CONSTRAINT_CHECK=
  3373. ;;
  3374. esac
  3375. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3376. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3377. services=($(get_master_services "${services_args[@]}")) || exit 1
  3378. if [ "$action" == "up" ]; then
  3379. ## remove run-once
  3380. for service in "${services_args[@]}"; do
  3381. type="$(get_service_type "$service")" || exit 1
  3382. if [ "$type" != "run-once" ]; then
  3383. action_posargs+=("$service")
  3384. fi
  3385. done
  3386. else
  3387. action_posargs+=("${services[@]}")
  3388. fi
  3389. fi
  3390. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3391. err "Fails to compile base 'docker-compose.yml'"
  3392. exit 1
  3393. }
  3394. ##
  3395. ## Pre-action
  3396. ##
  3397. full_init=
  3398. case "$action" in
  3399. up|run)
  3400. full_init=true
  3401. post_hook=true
  3402. ;;
  3403. ""|down|restart|logs|config|ps)
  3404. full_init=
  3405. ;;
  3406. *)
  3407. if [ "$is_service_action" ]; then
  3408. full_init=true
  3409. fi
  3410. ;;
  3411. esac
  3412. if [ "$full_init" ]; then
  3413. ## init in order
  3414. if [ -z "$no_init" ]; then
  3415. Section setup host resources
  3416. setup_host_resources "${services_args[@]}" || exit 1
  3417. Section initialisation
  3418. run_service_hook init "${services_args[@]}" || exit 1
  3419. fi
  3420. ## Get relations
  3421. if [ -z "$no_relations" ]; then
  3422. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3423. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3424. rebuild_relations_to_service=($rebuild_relations_to_service)
  3425. project=$(get_default_project_name) || return 1
  3426. for service in "${rebuild_relations_to_service[@]}"; do
  3427. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3428. [ -d "$dir" ] && {
  3429. debug rm -rf "$dir"
  3430. rm -rf "$dir"
  3431. }
  3432. done
  3433. done
  3434. fi
  3435. run_service_relations "${services_args[@]}" || exit 1
  3436. fi
  3437. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3438. fi
  3439. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3440. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3441. metadata=$(charm.metadata "$charm") || exit 1
  3442. SERVICE_TYPE="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3443. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3444. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3445. fi
  3446. fi
  3447. export SERVICE_PACK="${services_args[*]}"
  3448. ##
  3449. ## Docker-compose
  3450. ##
  3451. case "$action" in
  3452. up|start|stop|build|run)
  3453. ## force daemon mode for up
  3454. if [[ "$action" == "up" ]]; then
  3455. if ! array_member action_opts -d; then
  3456. action_opts+=("-d")
  3457. fi
  3458. if ! array_member action_opts --remove-orphans; then
  3459. action_opts+=("--remove-orphans")
  3460. fi
  3461. fi
  3462. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3463. ;;
  3464. logs)
  3465. if ! array_member action_opts --tail; then ## force daemon mode for up
  3466. action_opts+=("--tail" "10")
  3467. fi
  3468. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3469. ;;
  3470. "")
  3471. launch_docker_compose "${compose_opts[@]}"
  3472. ;;
  3473. graph)
  3474. graph $SERVICE_PACK
  3475. ;;
  3476. config)
  3477. ## removing the services
  3478. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3479. ## forcing docker-compose config to output the config file to stdout and not stderr
  3480. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3481. echo "$out"
  3482. exit 1
  3483. }
  3484. echo "$out"
  3485. warn "Runtime configuration modification (from relations) are not included here."
  3486. ;;
  3487. down)
  3488. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3489. debug "Adding a default argument of '--remove-orphans'"
  3490. action_opts+=("--remove-orphans")
  3491. fi
  3492. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3493. ;;
  3494. *)
  3495. if [ "$is_service_action" ]; then
  3496. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  3497. else
  3498. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3499. fi
  3500. ;;
  3501. esac || exit 1
  3502. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  3503. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3504. fi
  3505. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3506. if [ "$SERVICE_TYPE" == "run-once" ]; then
  3507. run_service_hook dc-post-run "${services_args[@]}" || exit 1
  3508. fi
  3509. fi
  3510. clean_unused_docker_compose || return 1