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.

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