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.

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