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.

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