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.

2930 lines
99 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  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. #:-
  34. [ -e /etc/shlib ] && . /etc/shlib || {
  35. echo "Unsatisfied dependency. Please install 'kal-shlib-core'."
  36. exit 1
  37. }
  38. #:-
  39. include pretty
  40. include parse
  41. include charm
  42. include array
  43. include cla
  44. depends shyaml docker
  45. version=0.1
  46. usage="$exname [COMPOSE_OPTS] [ACTION [ACTION_OPTS]]"
  47. help="\
  48. $WHITE$exname$NORMAL jobs is to run various shell scripts to build
  49. a running orchestrated and configured docker containers. These shell
  50. scripts will have the opportunity to build a 'docker-compose.yml'.
  51. Once init script and relations scripts are executed, $WHITE$exname$NORMAL
  52. delegate the launching to ${WHITE}docker-compose${NORMAL} by providing it
  53. the final 'docker-compose.yml'.
  54. $WHITE$exname$NORMAL also leverage charms to offer some additional custom
  55. actions per charm, which are simply other scripts that can be
  56. run without launching ${WHITE}docker-compose${NORMAL}.
  57. In compose message, color coding is enforced as such:
  58. - ${DARKCYAN}action$NORMAL,
  59. - ${DARKBLUE}relation$NORMAL,
  60. - ${DARKPINK}charm${NORMAL},
  61. - ${DARKYELLOW}service${NORMAL},
  62. - ${WHITE}option-name${NORMAL}/${WHITE}command-name${NORMAL}/${WHITE}Section-Title${NORMAL}
  63. $WHITE$exname$NORMAL reads '/etc/compose.conf' for global variables, and
  64. '/etc/compose.local.conf' for local host adjustements.
  65. "
  66. ## XXXvlab: this doesn't seem to work when 'compose' is called in
  67. ## a hook of a charm.
  68. #[[ "${BASH_SOURCE[0]}" == "" ]] && SOURCED=true
  69. $(return >/dev/null 2>&1) && SOURCED=true
  70. if [ "$UID" == 0 ]; then
  71. CACHEDIR=${CACHEDIR:-/var/cache/compose}
  72. VARDIR=${VARDIR:-/var/lib/compose}
  73. else
  74. [ "$XDG_CONFIG_HOME" ] && CACHEDIR=${CACHEDIR:-$XDG_CONFIG_HOME/compose}
  75. [ "$XDG_DATA_HOME" ] && VARDIR=${VARDIR:-$XDG_DATA_HOME/compose}
  76. CACHEDIR=${CACHEDIR:-$HOME/.cache/compose}
  77. VARDIR=${VARDIR:-$HOME/.local/share/compose}
  78. fi
  79. export VARDIR CACHEDIR
  80. md5_compat() { md5sum | cut -c -32; }
  81. quick_cat_file() { quick_cat_stdin < "$1"; }
  82. quick_cat_stdin() { local IFS=''; while read -r line; do echo "$line"; done ; }
  83. export -f quick_cat_file quick_cat_stdin md5_compat
  84. clean_cache() {
  85. local i=0
  86. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  87. ((i++))
  88. rm -f "$f"
  89. done
  90. if (( i > 0 )); then
  91. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  92. fi
  93. }
  94. trap_add "EXIT" clean_cache
  95. usage="$exname SERVICE"'
  96. Deploy and manage a swarm of containers to provide services based on
  97. a ``compose.yml`` definition and charms from a ``charm-store``.
  98. '
  99. export DEFAULT_COMPOSE_FILE
  100. ##
  101. ## Merge YAML files
  102. ##
  103. export _merge_yaml_common_code="
  104. import sys
  105. import yaml
  106. try:
  107. # included in standard lib from Python 2.7
  108. from collections import OrderedDict
  109. except ImportError:
  110. # try importing the backported drop-in replacement
  111. # it's available on PyPI
  112. from ordereddict import OrderedDict
  113. ## Ensure that there are no collision with legacy OrderedDict
  114. ## that could be used for omap for instance.
  115. class MyOrderedDict(OrderedDict):
  116. pass
  117. yaml.add_representer(
  118. MyOrderedDict,
  119. lambda cls, data: cls.represent_dict(data.items()))
  120. yaml.add_constructor(
  121. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  122. lambda cls, node: MyOrderedDict(cls.construct_pairs(node)))
  123. def fc(filename):
  124. with open(filename) as f:
  125. return f.read()
  126. def merge(*args):
  127. # sys.stderr.write('%r\n' % (args, ))
  128. args = [arg for arg in args if arg is not None]
  129. if len(args) == 0:
  130. return None
  131. if len(args) == 1:
  132. return args[0]
  133. if all(isinstance(arg, (int, basestring, bool)) for arg in args):
  134. return args[-1]
  135. elif all(isinstance(arg, list) for arg in args):
  136. res = []
  137. for arg in args:
  138. for elt in arg:
  139. if elt in res:
  140. res.remove(elt)
  141. res.append(elt)
  142. return res
  143. elif all(isinstance(arg, dict) for arg in args):
  144. keys = set()
  145. for arg in args:
  146. keys |= set(arg.keys())
  147. dct = {}
  148. for key in keys:
  149. sub_args = []
  150. for arg in args:
  151. if key in arg:
  152. sub_args.append(arg)
  153. try:
  154. dct[key] = merge(*(a[key] for a in sub_args))
  155. except NotImplementedError as e:
  156. raise NotImplementedError(
  157. e.args[0],
  158. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  159. e.args[2])
  160. if dct[key] is None:
  161. del dct[key]
  162. return dct
  163. else:
  164. raise NotImplementedError(
  165. 'Unsupported types: %s'
  166. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  167. return None
  168. def merge_cli(*args):
  169. try:
  170. c = merge(*args)
  171. except NotImplementedError as e:
  172. sys.stderr.write('Merging Failed: %s.\n%s\n'
  173. ' Values are:\n %s\n'
  174. % (e.args[0],
  175. ' Conflicting key is %r.' % e.args[1] if e.args[1] else
  176. ' Conflict at base of structure.',
  177. '\\n '.join('v%d: %r' % (i, a)
  178. for i, a in enumerate(e.args[2]))))
  179. exit(1)
  180. if c is not None:
  181. print '%s' % yaml.dump(c, default_flow_style=False)
  182. "
  183. merge_yaml() {
  184. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  185. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  186. $_merge_yaml_common_code
  187. merge_cli(*(yaml.load(fc(f)) for f in sys.argv[1:]))
  188. EOF
  189. fi
  190. python "$state_tmpdir/merge_yaml.py" "$@"
  191. }
  192. export -f merge_yaml
  193. merge_yaml_str() {
  194. local entries="$@"
  195. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  196. cat <<EOF > "$state_tmpdir/merge_yaml_str.py"
  197. $_merge_yaml_common_code
  198. merge_cli(*(yaml.load(f) for f in sys.argv[1:]))
  199. EOF
  200. fi
  201. python "$state_tmpdir/merge_yaml_str.py" "$@"
  202. }
  203. export -f merge_yaml_str
  204. yaml_key_val_str() {
  205. local entries="$@"
  206. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  207. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  208. $_merge_yaml_common_code
  209. print '%s' % yaml.dump({
  210. yaml.load(sys.argv[1]):
  211. yaml.load(sys.argv[2])}, default_flow_style=False)
  212. EOF
  213. fi
  214. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  215. }
  216. export -f yaml_key_val_str
  217. ##
  218. ## Docker
  219. ##
  220. docker_has_image() {
  221. local image="$1"
  222. images=$(docker images -q "$image" 2>/dev/null) || {
  223. err "docker images call has failed unexpectedly."
  224. return 1
  225. }
  226. [ "$images" ]
  227. }
  228. export -f docker_has_image
  229. cmd_on_base_image() {
  230. local service="$1" base_image
  231. shift
  232. base_image=$(service_base_docker_image "$service") || return 1
  233. docker run -i --entrypoint /bin/bash "$base_image" -c "$*"
  234. }
  235. export -f cmd_on_base_image
  236. cached_cmd_on_base_image() {
  237. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  238. shift
  239. if [ -e "$cache_file" ]; then
  240. # debug "$FUNCNAME: cache hit ($*)"
  241. quick_cat_stdin < "$cache_file"
  242. return 0
  243. fi
  244. result=$(cmd_on_base_image "$service" "$@") || return 1
  245. echo "$result" | tee "$cache_file"
  246. }
  247. export -f cached_cmd_on_base_image
  248. image_exposed_ports_0() {
  249. local image="$1"
  250. docker inspect --format='{{range $p, $conf := .Config.ExposedPorts}}{{$p}}{{"\x00"}}{{end}}' "$image"
  251. }
  252. export -f image_exposed_ports_0
  253. ##
  254. ## Generic
  255. ##
  256. fn.exists() {
  257. declare -F "$1" >/dev/null
  258. }
  259. str_pattern_matches() {
  260. local str="$1"
  261. shift
  262. for pattern in "$@"; do
  263. eval "[[ \"$str\" == $pattern ]]" && return 0
  264. done
  265. return 1
  266. }
  267. str_matches() {
  268. local str="$1"
  269. shift
  270. for pattern in "$@"; do
  271. [[ "$str" == "$pattern" ]] && return 0
  272. done
  273. return 1
  274. }
  275. gen_password() {
  276. local l=( {a..z} {A..Z} {0..9} ) nl="${#l[@]}" size=${1:-16}
  277. while ((size--)); do
  278. echo -n "${l[$((RANDOM * nl / 32768))]}"
  279. done
  280. echo
  281. }
  282. export -f gen_password
  283. file_put() {
  284. local TARGET="$1"
  285. mkdir -p "$(dirname "$TARGET")" &&
  286. cat - > "$TARGET"
  287. }
  288. export -f file_put
  289. file_put_0() {
  290. local TARGET="$1"
  291. mkdir -p "$(dirname "$TARGET")" &&
  292. cat > "$TARGET"
  293. }
  294. export -f file_put_0
  295. fetch_file() {
  296. local src="$1"
  297. case "$src" in
  298. *"://"*)
  299. err "Unsupported target scheme."
  300. return 1
  301. ;;
  302. *)
  303. ## Try direct
  304. if ! [ -r "$src" ]; then
  305. err "File '$src' not found/readable."
  306. return 1
  307. fi
  308. cat "$src" || return 1
  309. ;;
  310. esac
  311. }
  312. export -f fetch_file
  313. ## receives stdin content to decompress on stdout
  314. ## stdout content should be tar format.
  315. uncompress_file() {
  316. local filename="$1"
  317. ## Warning, the content of the file is already as stdin, the filename
  318. ## is there to hint for correct decompression.
  319. case "$filename" in
  320. *".gz")
  321. gunzip
  322. ;;
  323. *".bz2")
  324. bunzip2
  325. ;;
  326. *)
  327. cat
  328. ;;
  329. esac
  330. }
  331. export -f uncompress_file
  332. get_file() {
  333. local src="$1"
  334. fetch_file "$src" | uncompress_file "$src"
  335. }
  336. export -f get_file
  337. ##
  338. ## Common database lib
  339. ##
  340. _clean_docker() {
  341. local _DB_NAME="$1" container_id="$2"
  342. (
  343. set +e
  344. debug "Removing container $_DB_NAME"
  345. docker stop "$container_id"
  346. docker rm "$_DB_NAME"
  347. docker network rm "${_DB_NAME}"
  348. rm -vf "/tmp/${_DB_NAME}.state"
  349. )
  350. }
  351. export -f _clean_docker
  352. get_service_base_image_dir_uid_gid() {
  353. local service="$1" dir="$2" uid_gid
  354. uid_gid=$(cached_cmd_on_base_image "$service" "stat -c '%u %g' '$dir'") || {
  355. debug "Failed to query '$dir' uid in ${DARKYELLOW}$service${NORMAL} base image."
  356. return 1
  357. }
  358. info "uid and gid from ${DARKYELLOW}$service${NORMAL}:$dir is '$uid_gid'"
  359. echo "$uid_gid"
  360. }
  361. export -f get_service_base_image_dir_uid_gid
  362. are_files_locked_in_dir() {
  363. local dir="$1" device hdev ldev
  364. device=$(stat -c %d "$dir") || {
  365. err "Can't stat %d."
  366. return 1
  367. }
  368. device=$(printf "%04x" $device)
  369. hdev=${device:0:2}
  370. ldev=${device:2:2}
  371. inodes=$(find "$dir" -printf ':%i:\n')
  372. found=
  373. while read -r inode; do
  374. debug "try inode:$inode"
  375. if [[ "$inodes" == *":$inode:"* ]]; then
  376. found=1
  377. break
  378. fi
  379. done < <(cat /proc/locks | grep " $hdev:$ldev:" | sed -r "s/^.*$hdev:$ldev:([0-9]+).*$/\1/g")
  380. [ "$found" ]
  381. }
  382. export -f are_files_locked_in_dir
  383. export _PID="$$"
  384. ensure_db_docker_running () {
  385. local _STATE_FILE
  386. _DB_NAME="db_${DB_NAME}_${_PID}"
  387. _STATE_FILE=/tmp/${_DB_NAME}.state
  388. if [ -e "$_STATE_FILE" ]; then
  389. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$(cat "$_STATE_FILE")"
  390. debug "Re-using previous docker/connection '$DOCKER_IP'."
  391. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  392. return 0
  393. fi
  394. if [ -e "/tmp/${_DB_NAME}.working" ]; then
  395. ## avoid recursive calls.
  396. if [ -z "$DOCKER_IP" ]; then
  397. err "Currently figuring up DOCKER_IP, please set it yourself before this call if needed."
  398. return 1
  399. else
  400. debug "ignoring recursive call of 'ensure_db_docker_running'."
  401. fi
  402. return 0
  403. fi
  404. touch "/tmp/${_DB_NAME}.working"
  405. docker rm "$_DB_NAME" 2>/dev/null || true
  406. host_db_working_dir="$DATASTORE/${SERVICE_NAME}$DB_DATADIR"
  407. if is_db_locked; then
  408. info "Some process is using '$host_db_working_dir'. Trying to find a docker that would do this..."
  409. found=
  410. for docker_id in $(docker ps -q); do
  411. has_volume_mounted=$(
  412. docker inspect \
  413. --format "{{range .Mounts}}{{if eq .Destination \"$DB_DATADIR\"}}{{.Source}}{{end}}{{end}}" \
  414. "$docker_id")
  415. if [ "$has_volume_mounted" == "$host_db_working_dir" ]; then
  416. found="$docker_id"
  417. break
  418. fi
  419. done
  420. if [ -z "$found" ]; then
  421. err "Please shutdown any other docker using this directory."
  422. return 1
  423. fi
  424. export container_id="$found"
  425. info "Found docker $docker_id is already running."
  426. else
  427. verb "Database is not locked."
  428. if ! docker_has_image "$DOCKER_BASE_IMAGE"; then
  429. docker pull "$DOCKER_BASE_IMAGE"
  430. fi
  431. docker_opts=
  432. if [ -f "$DB_PASSFILE" ]; then
  433. verb "Found and using '$DB_PASSFILE'."
  434. docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  435. fi
  436. debug docker network create "$_DB_NAME"
  437. if ! network_id=$(docker network create "$_DB_NAME"); then
  438. err "'docker network create' failed !"
  439. _clean_docker "$_DB_NAME" "$container_id"
  440. rm "/tmp/${_DB_NAME}.working"
  441. return 1
  442. fi
  443. debug docker run -d \
  444. --name "$_DB_NAME" \
  445. $docker_opts \
  446. --network "$_DB_NAME" \
  447. -v "$host_db_working_dir:$DB_DATADIR" \
  448. "$DOCKER_BASE_IMAGE"
  449. if ! container_id=$(
  450. docker run -d \
  451. --name "$_DB_NAME" \
  452. $docker_opts \
  453. --network "$_DB_NAME" \
  454. -v "$host_db_working_dir:$DB_DATADIR" \
  455. "$DOCKER_BASE_IMAGE"
  456. ); then
  457. err "'docker run' failed !"
  458. _clean_docker "$_DB_NAME" "$container_id"
  459. rm "/tmp/${_DB_NAME}.working"
  460. return 1
  461. fi
  462. trap_add EXIT,ERR "_clean_docker \"$_DB_NAME\" \"$container_id\""
  463. fi
  464. if docker_ip=$(wait_for_docker_ip "$container_id"); then
  465. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  466. echo "$docker_ip" > "$_STATE_FILE"
  467. debug "written '$_STATE_FILE'"
  468. rm "/tmp/${_DB_NAME}.working"
  469. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  470. return 0
  471. else
  472. errlvl="$?"
  473. err "Db not found (errlvl: $errlvl). Tail of docker logs follows:"
  474. docker logs --tail=5 "$container_id" 2>&1 | prefix " | " >&2
  475. rm "/tmp/${_DB_NAME}.working"
  476. return "$errlvl"
  477. fi
  478. }
  479. export -f ensure_db_docker_running
  480. ## Require to set $db_docker_opts if needed, and $DB_PASSFILE
  481. ##
  482. _dcmd() {
  483. local docker_opts command="$1"
  484. shift
  485. debug "Db> $command $@"
  486. if [ -f "$DB_PASSFILE" ]; then
  487. verb "Found and using '$DB_PASSFILE'."
  488. db_docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  489. fi
  490. ## XXXX was here: actualy, we need only connection between this version and the client version
  491. debug docker run -i --rm \
  492. $db_docker_opts \
  493. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  494. docker run -i --rm \
  495. $db_docker_opts \
  496. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  497. }
  498. export -f _dcmd
  499. ## Executes code through db
  500. dcmd() {
  501. local fun
  502. [ "$DB_NAME" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_NAME."
  503. [ "$DB_DATADIR" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_DATADIR."
  504. # [ "$DB_PASSFILE" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_PASSFILE."
  505. [ "$_PID" ] || print_syntax_error "$FUNCNAME: You must provide \$_PID."
  506. for fun in is_db_locked _set_db_params ddb; do
  507. [ "$(type -t "$fun")" == "function" ] ||
  508. print_syntax_error "$FUNCNAME: You must provide function '$fun'."
  509. done
  510. ensure_db_docker_running </dev/null || return 1
  511. _dcmd "$@"
  512. }
  513. export -f dcmd
  514. get_docker_ips() {
  515. local name="$1" ip format network_id
  516. if ! docker inspect --format='{{ .NetworkSettings.Networks }}' "$name" >/dev/null 2>&1; then
  517. echo "default:$(docker inspect --format='{{ .NetworkSettings.IPAdress }}' "$name" 2>/dev/null)"
  518. else
  519. format='{{range $name, $conf := .NetworkSettings.Networks}}{{$name}}{{"\x00"}}{{$conf.IPAddress}}{{"\x00"}}{{end}}'
  520. while read-0 network_id ip; do
  521. printf "%s:%s\n" "$network_id" "$ip"
  522. done < <(docker inspect --format="$format" "$name")
  523. fi
  524. }
  525. export -f get_docker_ips
  526. get_docker_ip() {
  527. local name="$1"
  528. get_docker_ips "$name"
  529. }
  530. export -f get_docker_ip
  531. wait_docker_ip() {
  532. local name="$1" timeout="${2:-15}" timeout_count=0 docker_ip=
  533. start=$SECONDS
  534. while [ -z "$docker_ip" ]; do
  535. sleep 0.5
  536. docker_ip=$(get_docker_ip "$name") && break
  537. elapsed=$((SECONDS - start))
  538. if ((elapsed > timeout)); then
  539. err "${RED}timeout error${NORMAL}(${timeout}s):" \
  540. "Could not find '$name' docker container's IP."
  541. return 1
  542. fi
  543. [ "$elapsed" == "$old_elapsed" ] ||
  544. verb "Waiting for docker $name... ($elapsed/$timeout)"
  545. old_elapsed="$elapsed"
  546. done
  547. verb "Found docker $name network and IP: $docker_ip"
  548. echo "$docker_ip"
  549. }
  550. export -f wait_docker_ip
  551. wait_for_tcp_port() {
  552. local host_port=$1 timeout=30 start=$SECONDS
  553. verb "Trying to connect to $host_port"
  554. while true; do
  555. timeout 1 bash -c "</dev/tcp/${host_port/://}" >/dev/null 2>&1 && break
  556. sleep 0.2
  557. if [ "$((SECONDS - start))" -gt "$timeout" ]; then
  558. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  559. "Could not connect to $host_port."
  560. return 1
  561. fi
  562. done
  563. return 0
  564. }
  565. export -f wait_for_tcp_port
  566. ## Warning: requires a ``ddb`` matching current database to be checked
  567. wait_for_docker_ip() {
  568. local name=$1 DOCKER_IP= DOCKER_NETWORK= docker_ips= docker_ip=
  569. docker_ip=$(wait_docker_ip "$name" 5) || return 1
  570. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  571. if ! str_is_ipv4 "$DOCKER_IP"; then
  572. err "internal 'wait_docker_ip' did not return a valid IP. Returned IP is '$DOCKER_IP'."
  573. return 1
  574. fi
  575. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  576. while read-0 port; do
  577. IFS="/" read port type <<<"$port"
  578. [ "$type" == "tcp" ] || continue
  579. wait_for_tcp_port "$DOCKER_IP:${port}" || return 17
  580. verb "Port $DOCKER_IP:${port} checked open."
  581. done < <(image_exposed_ports_0 "$container_id")
  582. ## Checking direct connection
  583. if ! echo "SELECT 1;" | ddb >/dev/null; then
  584. err "${RED}db connection error${NORMAL}:"\
  585. "Could not connect to db on $DOCKER_IP" \
  586. "container's IP. (IP up, TCP ports is(are) open)"
  587. return 18
  588. fi
  589. echo "${DOCKER_NETWORK}:${DOCKER_IP}"
  590. return 0
  591. }
  592. export -f wait_for_docker_ip
  593. docker_add_host_declaration() {
  594. local src_docker=$1 domain=$2 dst_docker=$3 dst_docker_ip= dst_docker_network
  595. dst_docker_ip=$(wait_docker_ip "$dst_docker") || exit 1
  596. IFS=: read dst_docker_ip dst_docker_network <<<"$dst_docker_ip"
  597. docker exec -i "$src_docker" bash <<EOF
  598. if cat /etc/hosts | grep -E "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$" > /dev/null 2>&1; then
  599. sed -ri "s/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$/$dst_docker_ip $domain/g" /etc/hosts
  600. else
  601. echo "$dst_docker_ip $domain" >> /etc/hosts
  602. fi
  603. EOF
  604. }
  605. export -f docker_add_host_declaration
  606. get_running_containers_for_service() {
  607. local service="$1"
  608. docker ps --filter label="compose.service=$service" --format="{{.ID}}"
  609. }
  610. export -f get_running_containers_for_service
  611. ##
  612. ## Internal Process
  613. ##
  614. get_docker_compose_links() {
  615. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  616. deps master_service master_target_service _relation_name \
  617. target_service _relation_config tech_dep
  618. if [ -z "$service" ]; then
  619. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  620. return 1
  621. fi
  622. if [ -e "$cache_file" ]; then
  623. # debug "$FUNCNAME: cache hit ($*)"
  624. cat "$cache_file"
  625. return 0
  626. fi
  627. master_service=$(get_top_master_service_for_service "$service") || return 1
  628. ## XXXvlab: yuck, this make the assumption that next function is cached,
  629. ## and leverage the fact that the result is stored in a file. All this only
  630. ## to catch a failure of ``get_compose_relations``, that would go out silently.
  631. get_compose_relations "$service" >/dev/null || return 1 ## fetch cache and fail if necessary
  632. deps=()
  633. while read-0 _relation_name target_service _relation_config tech_dep; do
  634. master_target_service="$(get_top_master_service_for_service "$target_service")" || return 1
  635. [ "$master_service" == "$master_target_service" ] && continue
  636. if [ "$tech_dep" == "reversed" ]; then
  637. deps+=("$(echo -en "$master_target_service:\n links:\n - $master_service")")
  638. elif [ "$tech_dep" == "True" ]; then
  639. deps+=("$(echo -en "$master_service:\n links:\n - $master_target_service")")
  640. fi
  641. ## XXXvlab: an attempt to add depends_on, but this doesn't work well actually
  642. ## as there's a circular dependency issue. We don't really want the full feature
  643. ## of depends_on, but just to add it as targets when doing an 'up'
  644. # deps+=("$(echo -en "$master_service:\n depends_on:\n - $master_target_service")")
  645. done < <(get_compose_relations "$service")
  646. merge_yaml_str "${deps[@]}" | tee "$cache_file" || return 1
  647. if [ "${PIPESTATUS[0]}" != 0 ]; then
  648. rm "$cache_file"
  649. return 1
  650. fi
  651. }
  652. _get_docker_compose_opts() {
  653. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  654. compose_def master_service docker_compose_opts
  655. if [ -z "$service" ]; then
  656. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  657. return 1
  658. fi
  659. if [ -e "$cache_file" ]; then
  660. # debug "$FUNCNAME: cache hit ($*)"
  661. cat "$cache_file"
  662. return 0
  663. fi
  664. compose_def="$(get_compose_service_def "$service")" || return 1
  665. master_service="$(get_top_master_service_for_service "$service")"
  666. docker_compose_opts=$(echo "$compose_def" | shyaml get-value "docker-compose" 2>/dev/null)
  667. if [ "$docker_compose_opts" ]; then
  668. yaml_key_val_str "$master_service" "$docker_compose_opts"
  669. fi | tee "$cache_file"
  670. if [ "${PIPESTATUS[0]}" != 0 ]; then
  671. rm "$cache_file"
  672. return 1
  673. fi
  674. }
  675. ##
  676. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  677. ## Some metadata.yml (of subordinates) will indeed modify other
  678. ## services than themselves.
  679. _get_docker_compose_service_mixin() {
  680. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  681. links_yaml base_mixin links_yaml docker_compose_options \
  682. charm charm_part
  683. if [ -z "$service" ]; then
  684. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  685. return 1
  686. fi
  687. if [ -e "$cache_file" ]; then
  688. # debug "$FUNCNAME: cache hit ($*)"
  689. cat "$cache_file"
  690. return 0
  691. fi
  692. master_service=$(get_top_master_service_for_service "$service") || {
  693. err "Failed to get top master service for service $DARKYELLOW$service$NORMAL"
  694. return 1
  695. }
  696. ## The compose part
  697. base_mixin="$master_service:
  698. labels:
  699. - compose.service=$service
  700. - compose.master-service=${master_service}
  701. - compose.project=$(get_default_project_name)"
  702. links_yaml=$(get_docker_compose_links "$service") || return 1
  703. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  704. ## the charm part
  705. charm_part=$(get_docker_compose_mixin_from_metadata "$service") || return 1
  706. ## Merge results
  707. if [ "$charm_part" ]; then
  708. charm_yaml="$(yaml_key_val_str "$master_service" "$charm_part")" || return 1
  709. merge_yaml_str "$base_mixin" "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  710. else
  711. merge_yaml_str "$base_mixin" "$links_yaml" "$docker_compose_options" || return 1
  712. fi | tee "$cache_file"
  713. if [ "${PIPESTATUS[0]}" != 0 ]; then
  714. rm "$cache_file"
  715. return 1
  716. fi
  717. }
  718. export -f _get_docker_compose_service_mixin
  719. ##
  720. ## Get full `docker-compose.yml` format for all listed services (and
  721. ## their deps)
  722. ##
  723. ## @export
  724. ## @cache: !system !nofail +stdout
  725. get_docker_compose () {
  726. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  727. entries services service start docker_compose_services
  728. if [ -e "$cache_file" ]; then
  729. # debug "$FUNCNAME: cache hit ($*)"
  730. cat "$cache_file"
  731. return 0
  732. fi
  733. ##
  734. ## Adding sub services configurations
  735. ##
  736. declare -A entries
  737. start_compilation=$SECONDS
  738. debug "Compiling 'docker-compose.yml' base for ${DARKYELLOW}$*$NORMAL..."
  739. for target_service in "$@"; do
  740. start=$SECONDS
  741. services=$(get_ordered_service_dependencies "$target_service") || {
  742. err "Failed to get dependencies for $DARKYELLOW$target_service$NORMAL"
  743. return 1
  744. }
  745. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" $services "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  746. for service in $services; do
  747. if [ "${entries[$service]}" ]; then
  748. ## Prevent double inclusion of same service if this
  749. ## service is deps of two or more of your
  750. ## requirements.
  751. continue
  752. fi
  753. ## mark the service as "loaded" as well as it's containers
  754. ## if this is a subordinate service
  755. start_service=$SECONDS
  756. entries[$service]=$(_get_docker_compose_service_mixin "$service") || {
  757. err "Failed to get service mixin for $DARKYELLOW$service$NORMAL"
  758. return 1
  759. }
  760. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  761. done
  762. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  763. done
  764. docker_compose_services=$(merge_yaml_str "${entries[@]}") || return 1
  765. base_v2="version: '2.0'
  766. networks:
  767. static:
  768. driver: bridge
  769. ipam:
  770. driver: default
  771. config:
  772. - subnet: 172.25.1.0/24
  773. "
  774. merge_yaml_str "$(yaml_key_val_str "services" "$docker_compose_services")" \
  775. "$base_v2" > "$cache_file" || return 1
  776. export _current_docker_compose="$(cat "$cache_file")"
  777. echo "$_current_docker_compose"
  778. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  779. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  780. # debug "$_current_docker_compose"
  781. }
  782. export -f get_docker_compose
  783. _get_compose_service_def_cached () {
  784. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  785. if [ -e "$cache_file" ]; then
  786. #debug "$FUNCNAME: STATIC cache hit"
  787. cat "$cache_file" &&
  788. touch "$cache_file" || return 1
  789. return 0
  790. fi
  791. value=$(echo "$docker_compose" | shyaml get-value "$service" 2>/dev/null)
  792. if ! echo "$value" | shyaml get-value "charm" >/dev/null 2>&1; then
  793. if charm.exists "$service"; then
  794. value=$(merge_yaml <(echo "charm: $service") <(echo "$value")) || return 1
  795. else
  796. err "No ${WHITE}charm${NORMAL} value for service $DARKYELLOW$service$NORMAL" \
  797. "in compose, nor same name charm found."
  798. return 1
  799. fi
  800. fi
  801. echo "$value" | tee "$cache_file" || return 1
  802. # if [ "${PIPESTATUS[0]}" != 0 ]; then
  803. # rm "$cache_file"
  804. # return 1
  805. # fi
  806. return 0
  807. # if [ "${PIPESTATUS[0]}" != 0 -o \! -s "$cache_file" ]; then
  808. # rm "$cache_file"
  809. # err "PAS OK $service: $value"
  810. # return 1
  811. # fi
  812. }
  813. export -f _get_compose_service_def_cached
  814. ## XXXvlab: a lot to be done to cache the results
  815. get_compose_service_def () {
  816. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  817. result
  818. if [ -e "$cache_file" ]; then
  819. #debug "$FUNCNAME: SESSION cache hit"
  820. cat "$cache_file" || return 1
  821. return 0
  822. fi
  823. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  824. docker_compose=$([ "$COMPOSE_YML_FILE" -a -e "$COMPOSE_YML_FILE" ] && cat "$COMPOSE_YML_FILE")
  825. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  826. echo "$result" | tee "$cache_file" || return 1
  827. }
  828. export -f get_compose_service_def
  829. _get_service_charm_cached () {
  830. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  831. if [ -e "$cache_file" ]; then
  832. # debug "$FUNCNAME: cache hit $1"
  833. cat "$cache_file" &&
  834. touch "$cache_file" || return 1
  835. return 0
  836. fi
  837. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  838. if [ -z "$charm" ]; then
  839. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  840. return 1
  841. fi
  842. echo "$charm" | tee "$cache_file" || return 1
  843. }
  844. export -f _get_service_charm_cached
  845. get_service_charm () {
  846. local service="$1"
  847. if [ -z "$service" ]; then
  848. echo ${FUNCNAME[@]} >&2
  849. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  850. return 1
  851. fi
  852. service_def=$(get_compose_service_def "$service") || return 1
  853. _get_service_charm_cached "$service" "$service_def"
  854. }
  855. export -f get_service_charm
  856. ## built above the docker-compose abstraction, so it relies on the
  857. ## full docker-compose.yml to be already built.
  858. get_service_def () {
  859. local service="$1" def
  860. if [ -z "$_current_docker_compose" ]; then
  861. print_syntax_error "$FUNCNAME is meant to be called after"\
  862. "\$_current_docker_compose has been calculated."
  863. fi
  864. def=$(echo "$_current_docker_compose" | shyaml get-value "services.$service" 2>/dev/null)
  865. if [ -z "$def" ]; then
  866. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  867. return 1
  868. fi
  869. echo "$def"
  870. }
  871. export -f get_service_def
  872. ## Return the base docker image name of a service
  873. service_base_docker_image() {
  874. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  875. master_service service_def service_image service_build service_dockerfile
  876. if [ -e "$cache_file" ]; then
  877. # debug "$FUNCNAME: cache hit ($*)"
  878. cat "$cache_file"
  879. return 0
  880. fi
  881. master_service="$(get_top_master_service_for_service "$service")" || {
  882. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  883. return 1
  884. }
  885. service_def="$(get_service_def "$master_service")" || {
  886. err "Could not get docker-compose service definition for $DARKYELLOW$master_service$NORMAL."
  887. return 1
  888. }
  889. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  890. if [ "$?" != 0 ]; then
  891. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  892. if [ "$?" != 0 ]; then
  893. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  894. echo "$service_def" >&2
  895. return 1
  896. fi
  897. service_dockerfile="${service_build}"/Dockerfile
  898. if ! [ -e "$service_dockerfile" ]; then
  899. err "No Dockerfile found in '$service_dockerfile' location."
  900. return 1
  901. fi
  902. grep '^FROM' "$service_dockerfile" | xargs printf "%s " | cut -f 2 -d " "
  903. else
  904. echo "$service_image"
  905. fi | tee "$cache_file"
  906. }
  907. export -f service_base_docker_image
  908. get_charm_relation_def () {
  909. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  910. relation_def metadata
  911. if [ -e "$cache_file" ]; then
  912. # debug "$FUNCNAME: cache hit ($*)"
  913. cat "$cache_file"
  914. return 0
  915. fi
  916. metadata="$(charm.metadata "$charm")" || return 1
  917. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  918. echo "$relation_def" | tee "$cache_file"
  919. }
  920. export -f get_charm_relation_def
  921. get_charm_tech_dep_orientation_for_relation() {
  922. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  923. relation_def value
  924. if [ -e "$cache_file" ]; then
  925. # debug "$FUNCNAME: cache hit ($*)"
  926. cat "$cache_file"
  927. return 0
  928. fi
  929. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  930. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  931. value=${value:-True}
  932. echo "$value" | tee "$cache_file"
  933. }
  934. export -f get_charm_tech_dep_orientation_for_relation
  935. ##
  936. ## Use compose file to get deps, and relation definition in metadata.yml
  937. ## for tech-dep attribute.
  938. get_service_deps() {
  939. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  940. if [ -e "$cache_file" ]; then
  941. # debug "$FUNCNAME: cache hit ($*)"
  942. cat "$cache_file"
  943. return 0
  944. fi
  945. (
  946. set -o pipefail
  947. get_compose_relations "$service" | \
  948. while read-0 relation_name target_service _relation_config tech_dep; do
  949. echo "$target_service"
  950. done | tee "$cache_file"
  951. ) || return 1
  952. }
  953. export -f get_service_deps
  954. _rec_get_depth() {
  955. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  956. [ "${depths[$elt]}" ] && return 0
  957. if [ -e "$cache_file" ]; then
  958. # debug "$FUNCNAME: cache hit ($*)"
  959. depths[$elt]=$(cat "$cache_file")
  960. return 0
  961. fi
  962. visited[$elt]=1
  963. #debug "Setting visited[$elt]"
  964. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  965. deps=$(get_service_deps "$elt") || {
  966. debug "Failed get_service_deps $elt"
  967. return 1
  968. }
  969. # debug "$elt deps are:" $deps
  970. max=0
  971. for dep in $deps; do
  972. [ "${visited[$dep]}" ] && {
  973. #debug "Already computing $dep"
  974. continue
  975. }
  976. _rec_get_depth "$dep" || return 1
  977. #debug "Requesting depth[$dep]"
  978. if (( ${depths[$dep]} > max )); then
  979. max="${depths[$dep]}"
  980. fi
  981. done
  982. # debug "Setting depth[$elt] to $((max + 1))"
  983. depths[$elt]=$((max + 1))
  984. echo "${depths[$elt]}" > $cache_file
  985. }
  986. export -f _rec_get_depth
  987. get_ordered_service_dependencies() {
  988. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  989. if [ -e "$cache_file" ]; then
  990. # debug "$FUNCNAME: cache hit ($*)"
  991. cat "$cache_file"
  992. return 0
  993. fi
  994. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  995. if [ -z "${services[*]}" ]; then
  996. return 0
  997. # print_syntax_error "$FUNCNAME: no arguments"
  998. # return 1
  999. fi
  1000. declare -A depths
  1001. declare -A visited
  1002. heads=("${services[@]}")
  1003. while [ "${#heads[@]}" != 0 ]; do
  1004. array_pop heads head
  1005. _rec_get_depth "$head" || return 1
  1006. done
  1007. i=0
  1008. while [ "${#depths[@]}" != 0 ]; do
  1009. for key in "${!depths[@]}"; do
  1010. value="${depths[$key]}"
  1011. if [ "$value" == "$i" ]; then
  1012. echo "$key"
  1013. unset depths[$key]
  1014. fi
  1015. done
  1016. i=$((i + 1))
  1017. done | tee "$cache_file"
  1018. }
  1019. export -f get_ordered_service_dependencies
  1020. run_service_hook () {
  1021. local action="$1" service subservice subservices loaded
  1022. shift
  1023. declare -A loaded
  1024. for service in "$@"; do
  1025. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1026. for subservice in $subservices; do
  1027. if [ "${loaded[$subservice]}" ]; then
  1028. ## Prevent double inclusion of same service if this
  1029. ## service is deps of two or more of your
  1030. ## requirements.
  1031. continue
  1032. fi
  1033. charm=$(get_service_charm "$subservice") || return 1
  1034. charm.has_hook "$charm" "$action" >/dev/null || continue
  1035. PROJECT_NAME=$(get_default_project_name) || return 1
  1036. export MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1037. export MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1038. Wrap -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1039. export SERVICE_NAME=$subservice
  1040. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1041. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1042. export CHARM_NAME="$charm"
  1043. export PROJECT_NAME=$PROJECT_NAME
  1044. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$MASTER_BASE_SERVICE_NAME")
  1045. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1046. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1047. charm.run_hook "$charm" "$action"
  1048. EOF
  1049. loaded[$subservice]=1
  1050. done
  1051. done
  1052. return 0
  1053. }
  1054. host_resource_get() {
  1055. local location="$1" cfg="$2"
  1056. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1057. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1058. return 1
  1059. }
  1060. if fn.exists host_resource_get_$type; then
  1061. host_resource_get_$type "$location" "$cfg"
  1062. else
  1063. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1064. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1065. "$DARKYELLOW$subservice$NORMAL config."
  1066. return 1
  1067. fi
  1068. }
  1069. export -f host_resource_get
  1070. host_resource_get_git() {
  1071. local location="$1" cfg="$2" branch parent url
  1072. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1073. branch=${branch:-master}
  1074. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1075. parent="$(dirname "$location")"
  1076. (
  1077. mkdir -p "$parent" && cd "$parent" &&
  1078. git clone -b "$branch" "$url" "$(basename "$location")"
  1079. ) || return 1
  1080. }
  1081. export -f host_resource_get_git
  1082. host_resource_get_git-sub() {
  1083. local location="$1" cfg="$2" branch parent url
  1084. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1085. branch=${branch:-master}
  1086. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1087. parent="$(dirname "$location")"
  1088. (
  1089. mkdir -p "$parent" && cd "$parent" &&
  1090. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1091. ) || return 1
  1092. }
  1093. export -f host_resource_get_git-sub
  1094. setup_host_resource () {
  1095. local subservice="$1" service_def location get cfg
  1096. service_def=$(get_compose_service_def "$subservice") || return 1
  1097. while read-0 location cfg; do
  1098. ## XXXvlab: will it be a git resources always ?
  1099. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1100. err "Hum, location '$location' does not seem to be a git directory."
  1101. return 1
  1102. fi
  1103. if [ -d "$location" ]; then
  1104. info "host resource '$location' already set up."
  1105. continue
  1106. fi
  1107. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1108. if [ -z "$get" ]; then
  1109. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1110. "specified for $DARKYELLOW$subservice$NORMAL."
  1111. return 1
  1112. fi
  1113. host_resource_get "$location" "$get" || return 1
  1114. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1115. }
  1116. export -f setup_host_resource
  1117. setup_host_resources () {
  1118. local service subservices subservice loaded
  1119. declare -A loaded
  1120. for service in "$@"; do
  1121. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1122. for subservice in $subservices; do
  1123. if [ "${loaded[$subservice]}" ]; then
  1124. ## Prevent double inclusion of same service if this
  1125. ## service is deps of two or more of your
  1126. ## requirements.
  1127. continue
  1128. fi
  1129. setup_host_resource "$service"
  1130. loaded[$subservice]=1
  1131. done
  1132. done
  1133. return 0
  1134. }
  1135. export -f setup_host_resources
  1136. relation-get () {
  1137. local key="$1"
  1138. cat "$RELATION_DATA_FILE" | shyaml get-value "$key" 2>/dev/null
  1139. if [ "$?" != 0 ]; then
  1140. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1141. return 1
  1142. fi
  1143. }
  1144. export -f relation-get
  1145. relation-base-compose-get () {
  1146. local key="$1"
  1147. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1148. if [ "$?" != 0 ]; then
  1149. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1150. return 1
  1151. fi
  1152. }
  1153. export -f relation-base-compose-get
  1154. relation-target-compose-get () {
  1155. local key="$1"
  1156. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1157. if [ "$?" != 0 ]; then
  1158. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1159. return 1
  1160. fi
  1161. }
  1162. export -f relation-target-compose-get
  1163. relation-set () {
  1164. local key="$1" value="$2"
  1165. if [ -z "$RELATION_DATA_FILE" ]; then
  1166. err "$FUNCNAME: relation does not seems to be correctly setup."
  1167. return 1
  1168. fi
  1169. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1170. err "$FUNCNAME: can't read relation's data." >&2
  1171. return 1
  1172. fi
  1173. _config_merge "$RELATION_DATA_FILE" <(echo "$key: $value")
  1174. }
  1175. export -f relation-set
  1176. _config_merge() {
  1177. local config_filename="$1" merge_to_file="$2"
  1178. touch "$config_filename" &&
  1179. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  1180. mv "$config_filename.tmp" "$config_filename"
  1181. }
  1182. export -f _config_merge
  1183. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1184. config-add() {
  1185. local metadata="$1"
  1186. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1187. }
  1188. export -f config-add
  1189. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1190. init-config-add() {
  1191. local metadata="$1"
  1192. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1193. <(yaml_key_val_str "services" "$metadata")
  1194. }
  1195. export -f init-config-add
  1196. logstdout() {
  1197. local name="$1"
  1198. sed -r 's%^%'"${name}"'> %g'
  1199. }
  1200. export -f logstdout
  1201. logstderr() {
  1202. local name="$1"
  1203. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1204. }
  1205. export -f logstderr
  1206. _run_service_relation () {
  1207. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1208. charm=$(get_service_charm "$service") || return 1
  1209. target_charm=$(get_service_charm "$target_service") || return 1
  1210. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1211. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1212. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1213. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1214. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1215. export BASE_SERVICE_NAME=$service
  1216. export BASE_CHARM_NAME=$charm
  1217. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1218. export TARGET_SERVICE_NAME=$target_service
  1219. export TARGET_CHARM_NAME=$target_charm
  1220. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1221. export RELATION_DATA_FILE
  1222. target_errlvl=0
  1223. if [ -z "$target_script_name" ]; then
  1224. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1225. else
  1226. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1227. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1228. RELATION_CONFIG="$relation_dir/config_provider"
  1229. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1230. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1231. {
  1232. (
  1233. SERVICE_NAME=$target_service
  1234. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1235. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1236. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1237. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1238. echo "$?" > "$relation_dir/target_errlvl"
  1239. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1240. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1241. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1242. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1243. "failed before outputing an errorlevel."
  1244. ((target_errlvl |= "1" ))
  1245. }
  1246. if [ -e "$RELATION_CONFIG" ]; then
  1247. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1248. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1249. rm "$RELATION_CONFIG"
  1250. ((target_errlvl |= "$?"))
  1251. fi
  1252. fi
  1253. if [ "$target_errlvl" == 0 ]; then
  1254. errlvl=0
  1255. if [ "$base_script_name" ]; then
  1256. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1257. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1258. RELATION_CONFIG="$relation_dir/config_providee"
  1259. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1260. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1261. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1262. {
  1263. (
  1264. SERVICE_NAME=$service
  1265. SERVICE_DATASTORE="$DATASTORE/$service"
  1266. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1267. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1268. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1269. echo "$?" > "$relation_dir/errlvl"
  1270. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1271. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1272. errlvl="$(cat "$relation_dir/errlvl")" || {
  1273. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1274. "failed before outputing an errorlevel."
  1275. ((errlvl |= "1" ))
  1276. }
  1277. if [ -e "$RELATION_CONFIG" ]; then
  1278. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1279. rm "$RELATION_CONFIG"
  1280. ((errlvl |= "$?" ))
  1281. fi
  1282. if [ "$errlvl" != 0 ]; then
  1283. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1284. fi
  1285. else
  1286. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1287. fi
  1288. else
  1289. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1290. fi
  1291. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1292. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1293. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1294. return 0
  1295. else
  1296. return 1
  1297. fi
  1298. }
  1299. export -f _run_service_relation
  1300. _get_compose_relations_cached () {
  1301. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1302. relation_name relation_def target_service
  1303. if [ -e "$cache_file" ]; then
  1304. #debug "$FUNCNAME: STATIC cache hit $1"
  1305. cat "$cache_file" &&
  1306. touch "$cache_file" || return 1
  1307. return 0
  1308. fi
  1309. (
  1310. set -o pipefail
  1311. if [ "$compose_service_def" ]; then
  1312. while read-0 relation_name relation_def; do
  1313. ## XXXvlab: could we use braces here instead of parenthesis ?
  1314. (
  1315. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1316. "str")
  1317. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)"
  1318. target_charm=$(get_service_charm "$target_service") || return 1
  1319. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1320. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1321. ;;
  1322. "sequence")
  1323. while read-0 target_service; do
  1324. target_charm=$(get_service_charm "$target_service") || return 1
  1325. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1326. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1327. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1328. ;;
  1329. "struct")
  1330. while read-0 target_service relation_config; do
  1331. target_charm=$(get_service_charm "$target_service") || return 1
  1332. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1333. echo -en "$relation_name\0$target_service\0$relation_config\0$tech_dep\0"
  1334. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1335. ;;
  1336. esac
  1337. ) </dev/null >> "$cache_file" || return 1
  1338. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1339. fi
  1340. )
  1341. if [ "$?" != 0 ]; then
  1342. err "Error while looking for compose relations."
  1343. rm -f "$cache_file" ## no cache
  1344. return 1
  1345. fi
  1346. [ -e "$cache_file" ] && cat "$cache_file"
  1347. return 0
  1348. }
  1349. export -f _get_compose_relations_cached
  1350. get_compose_relations () {
  1351. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1352. compose_def
  1353. if [ -e "$cache_file" ]; then
  1354. #debug "$FUNCNAME: SESSION cache hit $1"
  1355. cat "$cache_file"
  1356. return 0
  1357. fi
  1358. compose_def="$(get_compose_service_def "$service")" || return 1
  1359. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1360. if [ "$?" != 0 ]; then
  1361. rm -f "$cache_file" ## no cache
  1362. return 1
  1363. fi
  1364. cat "$cache_file"
  1365. }
  1366. export -f get_compose_relations
  1367. get_compose_relation_def() {
  1368. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  1369. while read-0 relation_name target_service relation_config tech_dep; do
  1370. [ "$relation_name" == "$relation" ] || continue
  1371. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  1372. done < <(get_compose_relations "$service") || return 1
  1373. }
  1374. export -f get_compose_relation_def
  1375. run_service_relations () {
  1376. local service services loaded subservices subservice
  1377. PROJECT_NAME=$(get_default_project_name) || return 1
  1378. export PROJECT_NAME
  1379. declare -A loaded
  1380. subservices=$(get_ordered_service_dependencies "$@") || return 1
  1381. for service in $subservices; do
  1382. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  1383. for subservice in $(get_service_deps "$service") "$service"; do
  1384. [ "${loaded[$subservice]}" ] && continue
  1385. export BASE_SERVICE_NAME=$service
  1386. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1387. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1388. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  1389. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  1390. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  1391. while read-0 relation_name target_service relation_config tech_dep; do
  1392. export relation_config
  1393. export TARGET_SERVICE_NAME=$target_service
  1394. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  1395. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  1396. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  1397. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  1398. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  1399. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  1400. EOF
  1401. done < <(get_compose_relations "$subservice") || return 1
  1402. loaded[$subservice]=1
  1403. done
  1404. done
  1405. }
  1406. export -f run_service_relations
  1407. _run_service_action_direct() {
  1408. local service="$1" action="$2" charm _dummy
  1409. shift; shift
  1410. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  1411. if read-0 _dummy || [ "$_dummy" ]; then
  1412. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1413. return 1
  1414. fi
  1415. compose_file=$(get_compose_yml_location) || return 1
  1416. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1417. export state_tmpdir
  1418. {
  1419. (
  1420. set +e ## Prevents unwanted leaks from parent shell
  1421. export COMPOSE_CONFIG=$(cat "$compose_file")
  1422. export METADATA_CONFIG=$(charm.metadata "$charm")
  1423. export SERVICE_NAME=$service
  1424. export ACTION_NAME=$action
  1425. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  1426. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1427. export SERVICE_DATASTORE="$DATASTORE/$service"
  1428. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1429. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1430. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  1431. echo "$?" > "$action_errlvl_file"
  1432. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1433. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1434. if ! [ -e "$action_errlvl_file" ]; then
  1435. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1436. "to output an errlvl"
  1437. return 1
  1438. fi
  1439. return "$(cat "$action_errlvl_file")"
  1440. }
  1441. export -f _run_service_action_direct
  1442. _run_service_action_relation() {
  1443. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  1444. shift; shift
  1445. read-0 charm target_service target_charm relation_name relation_config || true
  1446. if read-0 _dummy || [ "$_dummy" ]; then
  1447. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1448. return 1
  1449. fi
  1450. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  1451. compose_file=$(get_compose_yml_location) || return 1
  1452. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1453. export state_tmpdir
  1454. {
  1455. (
  1456. set +e ## Prevents unwanted leaks from parent shell
  1457. export METADATA_CONFIG=$(charm.metadata "$charm")
  1458. export SERVICE_NAME=$service
  1459. export RELATION_TARGET_SERVICE="$target_service"
  1460. export RELATION_TARGET_CHARM="$target_charm"
  1461. export RELATION_BASE_SERVICE="$service"
  1462. export RELATION_BASE_CHARM="$charm"
  1463. export ACTION_NAME=$action
  1464. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  1465. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1466. export SERVICE_DATASTORE="$DATASTORE/$service"
  1467. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1468. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1469. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  1470. echo "$?" > "$action_errlvl_file"
  1471. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1472. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1473. if ! [ -e "$action_errlvl_file" ]; then
  1474. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1475. "to output an errlvl"
  1476. return 1
  1477. fi
  1478. return "$(cat "$action_errlvl_file")"
  1479. }
  1480. export -f _run_service_action_relation
  1481. get_relation_data_dir() {
  1482. local service="$1" target_service="$2" relation_name="$3" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1483. if [ -e "$cache_file" ]; then
  1484. # debug "$FUNCNAME: cache hit ($*)"
  1485. cat "$cache_file"
  1486. return 0
  1487. fi
  1488. project=$(get_default_project_name) || return 1
  1489. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  1490. if ! [ -d "$relation_dir" ]; then
  1491. mkdir -p "$relation_dir" || return 1
  1492. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  1493. fi
  1494. echo "$relation_dir" || tee "$cache_file"
  1495. }
  1496. export -f get_relation_data_dir
  1497. get_relation_data_file() {
  1498. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  1499. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1500. relation_data_file="$relation_dir/data"
  1501. new=
  1502. if [ -e "$relation_data_file" ]; then
  1503. ## Has reference changed ?
  1504. new_md5=$(echo "$relation_config" | md5_compat)
  1505. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  1506. new=true
  1507. fi
  1508. else
  1509. new=true
  1510. fi
  1511. if [ "$new" ]; then
  1512. echo "$relation_config" > "$relation_data_file"
  1513. chmod go-rwx "$relation_data_file" ## protecting this file
  1514. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  1515. fi
  1516. echo "$relation_data_file"
  1517. }
  1518. export -f get_relation_data_file
  1519. has_service_action () {
  1520. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1521. charm target_charm relation_name target_service relation_config _tech_dep
  1522. if [ -e "$cache_file" ]; then
  1523. # debug "$FUNCNAME: cache hit ($*)"
  1524. cat "$cache_file"
  1525. return 0
  1526. fi
  1527. charm=$(get_service_charm "$service") || return 1
  1528. ## Action directly provided ?
  1529. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  1530. echo -en "direct\0$charm" | tee "$cache_file"
  1531. return 0
  1532. fi
  1533. ## Action provided by relation ?
  1534. while read-0 relation_name target_service relation_config _tech_dep; do
  1535. target_charm=$(get_service_charm "$target_service") || return 1
  1536. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  1537. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  1538. return 0
  1539. fi
  1540. done < <(get_compose_relations "$service")
  1541. return 1
  1542. # master=$(get_top_master_service_for_service "$service")
  1543. # [ "$master" == "$charm" ] && return 1
  1544. # has_service_action "$master" "$action"
  1545. }
  1546. export -f has_service_action
  1547. run_service_action () {
  1548. local service="$1" action="$2"
  1549. shift ; shift
  1550. {
  1551. if ! read-0 action_type; then
  1552. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  1553. info " Add an executable script to 'actions/$action' to implement action."
  1554. return 1
  1555. fi
  1556. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  1557. "_run_service_action_${action_type}" "$service" "$action" "$@"
  1558. } < <(has_service_action "$service" "$action")
  1559. }
  1560. export -f run_service_action
  1561. get_compose_relation_config() {
  1562. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1563. if [ -e "$cache_file" ]; then
  1564. # debug "$FUNCNAME: cache hit ($*)"
  1565. cat "$cache_file"
  1566. return 0
  1567. fi
  1568. compose_service_def=$(get_compose_service_def "$service") || return 1
  1569. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  1570. }
  1571. export -f get_compose_relation_config
  1572. # ## Return key-values-0
  1573. # get_compose_relation_config_for_service() {
  1574. # local service=$1 relation_name=$2 relation_config
  1575. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  1576. # if ! relation_config=$(
  1577. # echo "$compose_service_relations" |
  1578. # shyaml get-value "${relation_name}" 2>/dev/null); then
  1579. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  1580. # "relation config in compose configuration."
  1581. # return 1
  1582. # fi
  1583. # if [ -z "$relation_config" ]; then
  1584. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  1585. # return 1
  1586. # fi
  1587. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  1588. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  1589. # return 1
  1590. # fi
  1591. # }
  1592. # export -f get_compose_relation_config_for_service
  1593. _get_master_service_for_service_cached () {
  1594. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1595. charm requires master_charm target_charm target_service service_def found
  1596. if [ -e "$cache_file" ]; then
  1597. # debug "$FUNCNAME: STATIC cache hit ($1)"
  1598. cat "$cache_file" &&
  1599. touch "$cache_file" || return 1
  1600. return 0
  1601. fi
  1602. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  1603. ## just return service name
  1604. echo "$service" | tee "$cache_file"
  1605. return 0
  1606. fi
  1607. ## fetch the container relation
  1608. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1609. if [ -z "$requires" ]; then
  1610. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any 'requires' " \
  1611. "section."
  1612. fi
  1613. found=
  1614. while read-0 relation_name relation; do
  1615. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  1616. found=1
  1617. break
  1618. }
  1619. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1620. if [ -z "$found" ]; then
  1621. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  1622. " ${WHITE}scope${NORMAL} set to 'container'."
  1623. fi
  1624. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1625. if [ -z "$interface" ]; then
  1626. err "No ${WHITE}interface${NORMAL} set for relation $DARKBLUE$relation_name$NORMAL."
  1627. return 1
  1628. fi
  1629. ## Action provided by relation ?
  1630. found=
  1631. while read-0 relation_name target_service _relation_config _tech_dep; do
  1632. [ "$interface" == "$relation_name" ] && {
  1633. found=1
  1634. break
  1635. }
  1636. done < <(get_compose_relations "$service")
  1637. if [ -z "$found" ]; then
  1638. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1639. "${DARKYELLOW}$service$NORMAL compose definition."
  1640. return 1
  1641. fi
  1642. echo "$target_service" | tee "$cache_file"
  1643. }
  1644. export -f _get_master_service_for_service_cached
  1645. get_master_service_for_service() {
  1646. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1647. charm metadata result
  1648. if [ -e "$cache_file" ]; then
  1649. # debug "$FUNCNAME: SESSION cache hit ($*)"
  1650. cat "$cache_file" || return 1
  1651. return 0
  1652. fi
  1653. charm=$(get_service_charm "$service") || return 1
  1654. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  1655. metadata=""
  1656. warn "No charm $DARKPINK$charm$NORMAL found."
  1657. }
  1658. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  1659. echo "$result" | tee "$cache_file" || return 1
  1660. }
  1661. export -f get_master_service_for_service
  1662. get_top_master_service_for_service() {
  1663. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1664. current_service
  1665. if [ -e "$cache_file" ]; then
  1666. # debug "$FUNCNAME: cache hit ($*)"
  1667. cat "$cache_file"
  1668. return 0
  1669. fi
  1670. current_service="$service"
  1671. while true; do
  1672. master_service=$(get_master_service_for_service "$current_service") || return 1
  1673. [ "$master_service" == "$current_service" ] && break
  1674. current_service="$master_service"
  1675. done
  1676. echo "$current_service" | tee "$cache_file"
  1677. return 0
  1678. }
  1679. export -f get_top_master_service_for_service
  1680. ##
  1681. ## The result is a mixin that is not always a complete valid
  1682. ## docker-compose entry (thinking of subordinates). The result
  1683. ## will be merge with master charms.
  1684. _get_docker_compose_mixin_from_metadata_cached() {
  1685. local service="$1" charm="$2" metadata="$3" has_build_dir="$4" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1686. metadata_file metadata volumes docker_compose subordinate image
  1687. if [ -e "$cache_file" ]; then
  1688. #debug "$FUNCNAME: STATIC cache hit $1"
  1689. cat "$cache_file" &&
  1690. touch "$cache_file" || return 1
  1691. return 0
  1692. fi
  1693. mixin=$(echo -en "labels:\n- compose.charm=$charm")
  1694. if [ "$metadata" ]; then
  1695. ## resources to volumes
  1696. volumes=$(
  1697. for resource_type in data config; do
  1698. while read-0 resource; do
  1699. eval "echo \" - \$${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  1700. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1701. done
  1702. while read-0 resource; do
  1703. if [[ "$resource" == /*:/*:* ]]; then
  1704. echo " - $resource"
  1705. elif [[ "$resource" == /*:/* ]]; then
  1706. echo " - $resource:rw"
  1707. elif [[ "$resource" == /*:* ]]; then
  1708. echo " - ${resource%%:*}:$resource"
  1709. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  1710. echo " - $resource:$resource:rw"
  1711. else
  1712. die "Invalid host-resource specified in 'metadata.yml'."
  1713. fi
  1714. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1715. while read-0 resource; do
  1716. dest="$(charm.get_dir "$charm")/resources$resource"
  1717. if ! [ -e "$dest" ]; then
  1718. die "charm-resource: '$resource' does not exist (file: '$dest')."
  1719. fi
  1720. echo " - $dest:$resource:ro"
  1721. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1722. ) || return 1
  1723. if [ "$volumes" ]; then
  1724. mixin=$(merge_yaml_str "$mixin" "$(echo -en "volumes:\n$volumes")") || {
  1725. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1726. "from charm ${DARKPINK}$charm$NORMAL."
  1727. return 1
  1728. }
  1729. fi
  1730. docker_compose=$(echo "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null)
  1731. if [ "$docker_compose" ]; then
  1732. mixin=$(merge_yaml_str "$mixin" "$docker_compose") || {
  1733. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1734. "from charm ${DARKPINK}$charm$NORMAL."
  1735. return 1
  1736. }
  1737. fi
  1738. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1739. subordinate=true
  1740. fi
  1741. fi
  1742. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1743. image_or_build_statement=
  1744. if [ "$image" ]; then
  1745. if [ "$subordinate" ]; then
  1746. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1747. return 1
  1748. fi
  1749. image_or_build_statement="image: $image"
  1750. elif [ "$has_build_dir" ]; then
  1751. if [ "$subordinate" ]; then
  1752. err "Subordinate charm can not have a 'build' sub directory."
  1753. return 1
  1754. fi
  1755. image_or_build_statement="build: $(charm.get_dir "$charm")/build"
  1756. fi
  1757. if [ "$image_or_build_statement" ]; then
  1758. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1759. fi
  1760. echo "$mixin" | tee "$cache_file"
  1761. }
  1762. export -f _get_docker_compose_mixin_from_metadata_cached
  1763. get_docker_compose_mixin_from_metadata() {
  1764. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1765. if [ -e "$cache_file" ]; then
  1766. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1767. cat "$cache_file"
  1768. return 0
  1769. fi
  1770. charm=$(get_service_charm "$service") || return 1
  1771. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  1772. has_build_dir=
  1773. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  1774. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  1775. echo "$mixin" | tee "$cache_file"
  1776. }
  1777. export -f get_docker_compose_mixin_from_metadata
  1778. _save() {
  1779. local name="$1"
  1780. cat - | tee -a "$docker_compose_dir/.data/$name"
  1781. }
  1782. export -f _save
  1783. get_default_project_name() {
  1784. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1785. echo "$DEFAULT_PROJECT_NAME"
  1786. return 0
  1787. fi
  1788. compose_yml_location="$(get_compose_yml_location)" || return 1
  1789. if [ "$compose_yml_location" ]; then
  1790. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1791. echo "$(basename "$(dirname "$normalized_path")")"
  1792. return 0
  1793. fi
  1794. fi
  1795. echo "project"
  1796. return 0
  1797. }
  1798. export -f get_default_project_name
  1799. launch_docker_compose() {
  1800. local charm docker_compose_tmpdir docker_compose_dir
  1801. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1802. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1803. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1804. # rm -rf \"$docker_compose_tmpdir\""
  1805. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1806. project=$(get_default_project_name)
  1807. mkdir -p "$docker_compose_tmpdir/$project"
  1808. docker_compose_dir="$docker_compose_tmpdir/$project"
  1809. # if [ -z "$SERVICE_PACK" ]; then
  1810. # export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1811. # fi
  1812. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1813. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1814. # debug "Merging some config data in docker-compose.yml:"
  1815. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1816. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1817. fi
  1818. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  1819. die "Generated 'docker-compose.yml' is unexpectedly empty."
  1820. fi
  1821. ## XXXvlab: could be more specific and only link the needed charms
  1822. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  1823. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  1824. # if charm.exists "$charm"; then
  1825. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  1826. # fi
  1827. # done
  1828. mkdir "$docker_compose_dir/.data"
  1829. {
  1830. {
  1831. cd "$docker_compose_dir"
  1832. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  1833. debug "$(cat "$docker_compose_dir/docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  1834. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1835. if [ "$DRY_COMPOSE_RUN" ]; then
  1836. echo docker-compose "$@"
  1837. else
  1838. docker-compose "$@"
  1839. fi
  1840. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1841. } | _save stdout
  1842. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1843. 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
  1844. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1845. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1846. fi
  1847. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  1848. if [ -z "$docker_compose_errlvl" ]; then
  1849. err "Something went wrong before you could gather docker-compose errorlevel."
  1850. return 1
  1851. fi
  1852. return "$docker_compose_errlvl"
  1853. }
  1854. export -f launch_docker_compose
  1855. get_compose_yml_location() {
  1856. parent=$(while ! [ -e "./compose.yml" ]; do
  1857. [ "$PWD" == "/" ] && exit 0
  1858. cd ..
  1859. done; echo "$PWD"
  1860. )
  1861. if [ "$parent" ]; then
  1862. echo "$parent/compose.yml"
  1863. return 0
  1864. fi
  1865. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1866. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1867. err "No 'compose.yml' was found in current or parent dirs," \
  1868. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  1869. "(${DEFAULT_COMPOSE_FILE})"
  1870. die "Please provide a 'compose.yml' file."
  1871. fi
  1872. echo "$DEFAULT_COMPOSE_FILE"
  1873. return 0
  1874. fi
  1875. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1876. die "Please provide a 'compose.yml' file."
  1877. return 1
  1878. }
  1879. export -f get_compose_yml_location
  1880. get_default_target_services() {
  1881. local services=("$@")
  1882. if [ -z "${services[*]}" ]; then
  1883. if [ "$DEFAULT_SERVICES" ]; then
  1884. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1885. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1886. services="$DEFAULT_SERVICES"
  1887. else
  1888. err "No service provided."
  1889. return 1
  1890. fi
  1891. fi
  1892. echo "${services[*]}"
  1893. }
  1894. export -f get_default_target_services
  1895. get_master_services() {
  1896. local loaded master_service service
  1897. declare -A loaded
  1898. for service in "$@"; do
  1899. master_service=$(get_top_master_service_for_service "$service") || return 1
  1900. if [ "${loaded[$master_service]}" ]; then
  1901. continue
  1902. fi
  1903. echo "$master_service"
  1904. loaded["$master_service"]=1
  1905. done | xargs printf "%s "
  1906. return "${PIPESTATUS[0]}"
  1907. }
  1908. export -f get_master_services
  1909. _setup_state_dir() {
  1910. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1911. #debug "Creating temporary state directory in '$state_tmpdir'."
  1912. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1913. # rm -rf \"$state_tmpdir\""
  1914. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1915. }
  1916. get_docker_compose_help_msg() {
  1917. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1918. docker_compose_help_msg
  1919. if [ -e "$cache_file" ]; then
  1920. cat "$cache_file" &&
  1921. touch "$cache_file" || return 1
  1922. return 0
  1923. fi
  1924. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  1925. echo "$docker_compose_help_msg" |
  1926. tee "$cache_file" || return 1
  1927. }
  1928. get_docker_compose_usage() {
  1929. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1930. docker_compose_help_msg
  1931. if [ -e "$cache_file" ]; then
  1932. cat "$cache_file" &&
  1933. touch "$cache_file" || return 1
  1934. return 0
  1935. fi
  1936. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  1937. echo "$docker_compose_help_msg" |
  1938. grep -m 1 "^Usage:" -A 10000 |
  1939. egrep -m 1 "^\$" -B 10000 |
  1940. xargs printf "%s " |
  1941. sed -r 's/^Usage: //g' |
  1942. tee "$cache_file" || return 1
  1943. }
  1944. get_docker_compose_opts_help() {
  1945. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1946. docker_compose_help_msg
  1947. if [ -e "$cache_file" ]; then
  1948. cat "$cache_file" &&
  1949. touch "$cache_file" || return 1
  1950. return 0
  1951. fi
  1952. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  1953. echo "$docker_compose_opts_help" |
  1954. grep '^Options:' -A 20000 |
  1955. tail -n +2 |
  1956. { cat ; echo; } |
  1957. egrep -m 1 "^\S*\$" -B 10000 |
  1958. head -n -1 |
  1959. tee "$cache_file" || return 1
  1960. }
  1961. get_docker_compose_commands_help() {
  1962. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1963. docker_compose_help_msg
  1964. if [ -e "$cache_file" ]; then
  1965. cat "$cache_file" &&
  1966. touch "$cache_file" || return 1
  1967. return 0
  1968. fi
  1969. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  1970. echo "$docker_compose_opts_help" |
  1971. grep '^Commands:' -A 20000 |
  1972. tail -n +2 |
  1973. { cat ; echo; } |
  1974. egrep -m 1 "^\S*\$" -B 10000 |
  1975. head -n -1 |
  1976. tee "$cache_file" || return 1
  1977. }
  1978. get_docker_compose_opts_list() {
  1979. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1980. docker_compose_help_msg
  1981. if [ -e "$cache_file" ]; then
  1982. cat "$cache_file" &&
  1983. touch "$cache_file" || return 1
  1984. return 0
  1985. fi
  1986. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  1987. echo "$docker_compose_opts_help" |
  1988. egrep "^\s+-" |
  1989. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1990. tee "$cache_file" || return 1
  1991. }
  1992. options_parser() {
  1993. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  1994. printf "\0"
  1995. }
  1996. remove_options_in_option_help_msg() {
  1997. {
  1998. read-0 null
  1999. if [ "$null" ]; then
  2000. err "options parsing error, should start with an option line."
  2001. return 1
  2002. fi
  2003. while read-0 opt full_txt;do
  2004. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2005. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2006. for to_remove in "$@"; do
  2007. str_matches "$to_remove" $multi_opts $single_opts && {
  2008. continue 2
  2009. }
  2010. done
  2011. echo -n "$full_txt"
  2012. done
  2013. } < <(options_parser)
  2014. }
  2015. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2016. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2017. multi_opts_filter() {
  2018. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2019. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2020. tr ',' "\n" | xargs printf "%s "
  2021. }
  2022. single_opts_filter() {
  2023. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2024. tr ',' "\n" | xargs printf "%s "
  2025. }
  2026. get_docker_compose_multi_opts_list() {
  2027. local action="$1" opts_list
  2028. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2029. echo "$opts_list" | multi_opts_filter
  2030. }
  2031. get_docker_compose_single_opts_list() {
  2032. local action="$1" opts_list
  2033. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2034. echo "$opts_list" | single_opts_filter
  2035. }
  2036. display_help() {
  2037. print_help
  2038. echo "${WHITE}Options${NORMAL}:"
  2039. echo " -h, --help Print this message and quit"
  2040. echo " (ignoring any other options)"
  2041. echo " -V, --version Print current version and quit"
  2042. echo " (ignoring any other options)"
  2043. echo " --dirs Display data dirs and quit"
  2044. echo " (ignoring any other options)"
  2045. echo " -v, --verbose Be more verbose"
  2046. echo " -d, --debug Print full debugging information (sets also verbose)"
  2047. echo " --dry-compose-run If docker-compose will be run, only print out what"
  2048. echo " command line will be used."
  2049. echo " --rebuild-relations-to-service, -R SERVICE"
  2050. echo " Will rebuild all relations to given service"
  2051. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  2052. filter_docker_compose_help_message
  2053. echo
  2054. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2055. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2056. }
  2057. _graph_service() {
  2058. local service="$1" base="$1"
  2059. charm=$(get_service_charm "$service") || return 1
  2060. metadata=$(charm.metadata "$charm") || return 1
  2061. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  2062. if [ "$subordinate" == "True" ]; then
  2063. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  2064. master_charm=
  2065. while read-0 relation_name relation; do
  2066. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  2067. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  2068. if [ -z "$interface" ]; then
  2069. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  2070. return 1
  2071. fi
  2072. ## Action provided by relation ?
  2073. target_service=
  2074. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  2075. [ "$interface" == "$relation_name" ] && {
  2076. target_service="$candidate_target_service"
  2077. break
  2078. }
  2079. done < <(get_compose_relations "$service")
  2080. if [ -z "$target_service" ]; then
  2081. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  2082. "${DARKYELLOW}$service$NORMAL compose definition."
  2083. return 1
  2084. fi
  2085. master_service="$target_service"
  2086. master_charm=$(get_service_charm "$target_service") || return 1
  2087. break
  2088. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  2089. fi
  2090. _graph_node_service "$service" "$base" "$charm"
  2091. _graph_edge_service "$service" "$subordinate" "$master_service"
  2092. }
  2093. _graph_node_service() {
  2094. local service="$1" base="$2" charm="$3"
  2095. cat <<EOF
  2096. "$(_graph_node_service_label ${service})" [
  2097. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  2098. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  2099. color = $([ "$base" ] && echo "blue" || echo "black")
  2100. fillcolor = "white"
  2101. fontname = "Courier New"
  2102. shape = "Mrecord"
  2103. label =<$(_graph_node_service_content "$service")>
  2104. ];
  2105. EOF
  2106. }
  2107. _graph_edge_service() {
  2108. local service="$1" subordinate="$2" master_service="$3"
  2109. while read-0 relation_name target_service relation_config tech_dep; do
  2110. cat <<EOF
  2111. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  2112. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  2113. fontsize = 16
  2114. fontcolor = "black"
  2115. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  2116. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  2117. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  2118. arrowtail = odot
  2119. # arrowhead = dotlicurve
  2120. taillabel = "$relation_name" ];
  2121. EOF
  2122. done < <(get_compose_relations "$service") || return 1
  2123. }
  2124. _graph_node_service_label() {
  2125. local service="$1"
  2126. echo "service_$service"
  2127. }
  2128. _graph_node_service_content() {
  2129. local service="$1"
  2130. charm=$(get_service_charm "$service") || return 1
  2131. cat <<EOF
  2132. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  2133. <tr>
  2134. <td bgcolor="black" align="center" colspan="2">
  2135. <font color="white">$service</font>
  2136. </td>
  2137. </tr>
  2138. $(if [ "$charm" != "$service" ]; then
  2139. cat <<EOF2
  2140. <tr>
  2141. <td align="left" port="r0">charm: $charm</td>
  2142. </tr>
  2143. EOF2
  2144. fi)
  2145. </table>
  2146. EOF
  2147. }
  2148. cla_contains () {
  2149. local e
  2150. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  2151. return 1
  2152. }
  2153. filter_docker_compose_help_message() {
  2154. cat - |
  2155. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  2156. s/docker-compose.yml/compose.yml/g;
  2157. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  2158. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  2159. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  2160. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  2161. }
  2162. graph() {
  2163. local services=("$@")
  2164. declare -A entries
  2165. cat <<EOF
  2166. digraph g {
  2167. graph [
  2168. fontsize=30
  2169. labelloc="t"
  2170. label=""
  2171. splines=true
  2172. overlap=false
  2173. #rankdir = "LR"
  2174. ];
  2175. ratio = auto;
  2176. EOF
  2177. for target_service in "$@"; do
  2178. services=$(get_ordered_service_dependencies "$target_service") || return 1
  2179. for service in $services; do
  2180. [ "${entries[$service]}" ] && continue || entries[$service]=1
  2181. if cla_contains "$service" "${services[@]}"; then
  2182. base=true
  2183. else
  2184. base=
  2185. fi
  2186. _graph_service "$service" "$base"
  2187. done
  2188. done
  2189. echo "}"
  2190. }
  2191. [ "$SOURCED" ] && return 0
  2192. # if [[ "$UID" != 0 ]]; then
  2193. # die "'$exname' requires root permissions (for now). Please run as root."
  2194. # fi
  2195. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  2196. if [ -r /etc/default/charm ]; then
  2197. . /etc/default/charm
  2198. fi
  2199. if [ -r "/etc/default/$exname" ]; then
  2200. . "/etc/default/$exname"
  2201. fi
  2202. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  2203. ## userdir ? and global /etc/compose.yml ?
  2204. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  2205. /etc/default/compose /etc/compose/local.conf; do
  2206. [ -e "$cfgfile" ] || continue
  2207. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  2208. done
  2209. fi
  2210. _setup_state_dir
  2211. mkdir -p "$CACHEDIR" || exit 1
  2212. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs printf "%s " | cut -f 2 -d " ") || {
  2213. die "Couldn't determine docker host net"
  2214. }
  2215. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  2216. die "Couldn't determine docker host ip"
  2217. }
  2218. export DOCKER_HOST_NET DOCKER_HOST_IP
  2219. ##
  2220. ## Argument parsing
  2221. ##
  2222. services=()
  2223. remainder_args=()
  2224. compose_opts=()
  2225. action_opts=()
  2226. services_args=()
  2227. pos_arg_ct=0
  2228. no_hooks=
  2229. no_init=
  2230. action=
  2231. stage="main" ## switches from 'main', to 'action', 'remainder'
  2232. is_docker_compose_action=
  2233. rebuild_relations_to_service=()
  2234. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  2235. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  2236. while read-0 arg; do
  2237. case "$stage" in
  2238. "main")
  2239. case "$arg" in
  2240. --help|-h)
  2241. no_init=true ; no_hooks=true ; no_relations=true
  2242. display_help
  2243. exit 0
  2244. ;;
  2245. --verbose|-v)
  2246. export VERBOSE=true
  2247. compose_opts+=("--verbose")
  2248. ;;
  2249. --version|-V)
  2250. print_version
  2251. docker-compose --version
  2252. docker --version
  2253. exit 0
  2254. ;;
  2255. -f|--file)
  2256. read-0 value
  2257. [ -e "$value" ] || die "File $value doesn't exists"
  2258. export DEFAULT_COMPOSE_FILE="$value"
  2259. compose_opts+=("--file $value")
  2260. shift
  2261. ;;
  2262. -p|--project-name)
  2263. read-0 value
  2264. export DEFAULT_PROJECT_NAME="$value"
  2265. compose_opts+=("--project-name $value")
  2266. shift
  2267. ;;
  2268. --no-relations)
  2269. export no_relations=true
  2270. ;;
  2271. --no-hooks)
  2272. export no_hooks=true
  2273. ;;
  2274. --no-init)
  2275. export no_init=true
  2276. ;;
  2277. --rebuild-relations-to-service|-R)
  2278. read-0 value
  2279. rebuild_relations_to_service+=("$value")
  2280. shift
  2281. ;;
  2282. --debug)
  2283. export DEBUG=true
  2284. export VERBOSE=true
  2285. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  2286. ;;
  2287. --dirs)
  2288. echo "CACHEDIR: $CACHEDIR"
  2289. echo "VARDIR: $VARDIR"
  2290. exit 0
  2291. ;;
  2292. --dry-compose-run)
  2293. export DRY_COMPOSE_RUN=true
  2294. ;;
  2295. --*|-*)
  2296. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2297. read-0 value
  2298. compose_opts+=("$arg" "$value")
  2299. shift;
  2300. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2301. compose_opts+=("$arg")
  2302. else
  2303. err "Unknown option '$arg'. Please check help:"
  2304. display_help
  2305. exit 1
  2306. fi
  2307. ;;
  2308. *)
  2309. action="$arg"
  2310. stage="action"
  2311. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  2312. is_docker_compose_action=true
  2313. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  2314. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  2315. if [ "$DC_MATCH_MULTI" ]; then
  2316. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  2317. fi
  2318. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  2319. pos_args=("${pos_args[@]:1}")
  2320. # echo "USAGE: $DC_USAGE"
  2321. # echo "pos_args: ${pos_args[@]}"
  2322. # echo "MULTI: $DC_MATCH_MULTI"
  2323. # echo "SINGLE: $DC_MATCH_SINGLE"
  2324. # exit 1
  2325. else
  2326. stage="remainder"
  2327. fi
  2328. ;;
  2329. esac
  2330. ;;
  2331. "action") ## Only for docker-compose actions
  2332. case "$arg" in
  2333. --help|-h)
  2334. no_init=true ; no_hooks=true ; no_relations=true
  2335. action_opts+=("$arg")
  2336. ;;
  2337. --*|-*)
  2338. if [ "$is_docker_compose_action" ]; then
  2339. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2340. read-0 value
  2341. action_opts+=("$arg" "$value")
  2342. shift;
  2343. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2344. action_opts+=("$arg")
  2345. else
  2346. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  2347. docker-compose "$action" --help |
  2348. filter_docker_compose_help_message >&2
  2349. exit 1
  2350. fi
  2351. fi
  2352. ;;
  2353. *)
  2354. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  2355. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  2356. services_args+=("$arg")
  2357. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  2358. services_args=("$arg") || exit 1
  2359. stage="remainder"
  2360. else
  2361. action_posargs+=("$arg")
  2362. ((pos_arg_ct++))
  2363. fi
  2364. ;;
  2365. esac
  2366. ;;
  2367. "remainder")
  2368. remainder_args+=("$arg")
  2369. while read-0 arg; do
  2370. remainder_args+=("$arg")
  2371. done
  2372. break 3
  2373. ;;
  2374. esac
  2375. shift
  2376. done < <(cla.normalize "$@")
  2377. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  2378. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  2379. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  2380. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  2381. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  2382. ##
  2383. ## Actual code
  2384. ##
  2385. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  2386. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2387. export COMPOSE_YML_FILE
  2388. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2389. output=$(shyaml get-value < "$COMPOSE_YML_FILE" 2>&1)
  2390. if [ "$?" != 0 ]; then
  2391. outputed_something=
  2392. while IFS='' read -r line1 && IFS='' read -r line2; do
  2393. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2394. outputed_something=true
  2395. echo "$line1 $GRAY($line2)$NORMAL"
  2396. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2397. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2398. prefix " $GRAY|$NORMAL "
  2399. [ "$outputed_something" ] || {
  2400. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2401. echo "$output" | prefix " $GRAY|$NORMAL "
  2402. }
  2403. exit 1
  2404. fi
  2405. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  2406. ##
  2407. ## Get services in command line.
  2408. ##
  2409. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  2410. action_service=${remainder_args[0]}
  2411. remainder_args=("${remainder_args[@]:1}")
  2412. if is_service_action=$(has_service_action "$action_service" "$action"); then
  2413. {
  2414. read-0 action_type
  2415. case "$action_type" in
  2416. "relation")
  2417. read-0 _ target_service _target_charm relation_name
  2418. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  2419. ;;
  2420. "direct")
  2421. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  2422. ;;
  2423. esac
  2424. } < <(has_service_action "$action_service" "$action")
  2425. services_args=("$action_service")
  2426. else
  2427. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  2428. fi
  2429. else
  2430. if [[ "$action" =~ (up|ps) && "${#services_args[@]}" == 0 ]]; then
  2431. services_args=($(shyaml keys <"$COMPOSE_YML_FILE"))
  2432. fi
  2433. if [ "$action" == "config" ]; then
  2434. services_args=("${action_posargs[@]}")
  2435. fi
  2436. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  2437. services=($(get_master_services "${services_args[@]}")) || exit 1
  2438. action_posargs+=("${services[@]}")
  2439. fi
  2440. fi
  2441. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  2442. err "Fails to compile base 'docker-compose.yml'"
  2443. exit 1
  2444. }
  2445. ##
  2446. ## Pre-action
  2447. ##
  2448. full_init=
  2449. case "$action" in
  2450. up|run)
  2451. full_init=true
  2452. post_hook=true
  2453. ;;
  2454. ""|down|restart|logs|config|ps)
  2455. full_init=
  2456. ;;
  2457. *)
  2458. if [ "$is_service_action" ]; then
  2459. full_init=true
  2460. fi
  2461. ;;
  2462. esac
  2463. if [ "$full_init" ]; then
  2464. ## init in order
  2465. if [ -z "$no_init" ]; then
  2466. Section setup host resources
  2467. setup_host_resources "${services_args[@]}" || exit 1
  2468. Section initialisation
  2469. run_service_hook init "${services_args[@]}" || exit 1
  2470. fi
  2471. ## Get relations
  2472. if [ -z "$no_relations" ]; then
  2473. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  2474. rebuild_relations_to_service=(
  2475. $(get_master_services "${rebuild_relations_to_service[@]}"))
  2476. project=$(get_default_project_name) || return 1
  2477. for service in "${rebuild_relations_to_service[@]}"; do
  2478. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  2479. [ -d "$dir" ] && rm -rf "$dir"
  2480. done
  2481. done
  2482. fi
  2483. run_service_relations "${services_args[@]}" || exit 1
  2484. fi
  2485. fi
  2486. export SERVICE_PACK="${services_args[*]}"
  2487. ##
  2488. ## Docker-compose
  2489. ##
  2490. case "$action" in
  2491. up|start|stop|build|run)
  2492. if [[ "$action" == "up" ]] && ! array_member action_opts -d; then ## force daemon mode for up
  2493. action_opts+=("-d" "${action_opts[@]}")
  2494. fi
  2495. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2496. ;;
  2497. "")
  2498. launch_docker_compose "${compose_opts[@]}"
  2499. ;;
  2500. graph)
  2501. graph $SERVICE_PACK
  2502. ;;
  2503. config)
  2504. ## removing the services
  2505. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  2506. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2507. warn "Runtime configuration modification (from relations) are not included here."
  2508. ;;
  2509. down)
  2510. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  2511. debug "Adding a default argument of '--remove-orphans'"
  2512. action_opts+=("--remove-orphans")
  2513. fi
  2514. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2515. ;;
  2516. *)
  2517. if [ "$is_service_action" ]; then
  2518. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2519. else
  2520. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2521. fi
  2522. ;;
  2523. esac
  2524. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  2525. run_service_hook post_deploy "${services_args[@]}" || exit 1
  2526. fi