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.

2400 lines
78 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
9 years ago
9 years ago
9 years ago
9 years ago
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. #:-
  26. [ -e /etc/shlib ] && . /etc/shlib || {
  27. echo "Unsatisfied dependency. Please install 'kal-shlib-core'."
  28. exit 1
  29. }
  30. #:-
  31. include pretty
  32. include parse
  33. depends shyaml docker
  34. version=0.1
  35. usage="$exname [COMPOSE_OPTS] [ACTION [ACTION_OPTS]]"
  36. help="\
  37. $WHITE$exname$NORMAL jobs is to run various shell scripts to build
  38. a running orchestrated and configured docker containers. These shell
  39. scripts will have the opportunity to build a 'docker-compose.yml'.
  40. Once init script and relations scripts are executed, $WHITE$exname$NORMAL
  41. delegate the launching to ${WHITE}docker-compose${NORMAL} by providing it
  42. the final 'docker-compose.yml'.
  43. $WHITE$exname$NORMAL also leverage charms to offer some additional custom
  44. actions per charm, which are simply other scripts that can be
  45. run without launching ${WHITE}docker-compose${NORMAL}.
  46. In compose message, color coding is enforced as such:
  47. - ${DARKCYAN}action$NORMAL,
  48. - ${DARKBLUE}relation$NORMAL,
  49. - ${DARKYELLOW}charm${NORMAL}/${DARKYELLOW}service${NORMAL},
  50. - ${WHITE}option-name${NORMAL}/${WHITE}command-name${NORMAL}/${WHITE}Section-Title${NORMAL}
  51. $WHITE$exname$NORMAL reads '/etc/compose.conf' for global variables, and
  52. '/etc/compose.local.conf' for local host adjustements.
  53. ${WHITE}$exname Options${NORMAL}:
  54. -h, --help Print this message and quit
  55. (ignoring any other options)
  56. -V, --version Print current version and quit
  57. (ignoring any other options)
  58. -v, --verbose Be more verbose
  59. -d, --debug Print full debugging information (sets also verbose)
  60. "
  61. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  62. export CACHEDIR=/var/cache/compose
  63. export VARDIR=/var/lib/compose
  64. md5_compat() { md5sum | cut -c -32; }
  65. quick_cat_file() { quick_cat_stdin < "$1"; }
  66. quick_cat_stdin() { local IFS=''; while read -r line; do echo "$line"; done ; }
  67. export -f quick_cat_file quick_cat_stdin md5_compat
  68. clean_cache() {
  69. local i=0
  70. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  71. ((i++))
  72. rm -f "$f"
  73. done
  74. if (( i > 0 )); then
  75. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  76. fi
  77. }
  78. trap_add "EXIT" clean_cache
  79. usage="$exname CHARM"'
  80. Deploy and manage a swarm of containers to provide services based on
  81. a ``compose.yml`` definition and charms from a ``charm-store``.
  82. '
  83. export DEFAULT_COMPOSE_FILE
  84. ##
  85. ## Merge YAML files
  86. ##
  87. export _merge_yaml_common_code="
  88. import sys
  89. import yaml
  90. try:
  91. # included in standard lib from Python 2.7
  92. from collections import OrderedDict
  93. except ImportError:
  94. # try importing the backported drop-in replacement
  95. # it's available on PyPI
  96. from ordereddict import OrderedDict
  97. ## Ensure that there are no collision with legacy OrderedDict
  98. ## that could be used for omap for instance.
  99. class MyOrderedDict(OrderedDict):
  100. pass
  101. yaml.add_representer(
  102. MyOrderedDict,
  103. lambda cls, data: cls.represent_dict(data.items()))
  104. yaml.add_constructor(
  105. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  106. lambda cls, node: MyOrderedDict(cls.construct_pairs(node)))
  107. def fc(filename):
  108. with open(filename) as f:
  109. return f.read()
  110. def merge(*args):
  111. # sys.stderr.write('%r\n' % (args, ))
  112. args = [arg for arg in args if arg is not None]
  113. if len(args) == 0:
  114. return None
  115. if len(args) == 1:
  116. return args[0]
  117. if all(isinstance(arg, (int, basestring, bool)) for arg in args):
  118. return args[-1]
  119. elif all(isinstance(arg, list) for arg in args):
  120. res = []
  121. for arg in args:
  122. for elt in arg:
  123. if elt in res:
  124. res.remove(elt)
  125. res.append(elt)
  126. return res
  127. elif all(isinstance(arg, dict) for arg in args):
  128. keys = set()
  129. for arg in args:
  130. keys |= set(arg.keys())
  131. dct = {}
  132. for key in keys:
  133. sub_args = []
  134. for arg in args:
  135. if key in arg:
  136. sub_args.append(arg)
  137. try:
  138. dct[key] = merge(*(a[key] for a in sub_args))
  139. except NotImplementedError as e:
  140. raise NotImplementedError(
  141. e.args[0],
  142. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  143. e.args[2])
  144. if dct[key] is None:
  145. del dct[key]
  146. return dct
  147. else:
  148. raise NotImplementedError(
  149. 'Unsupported types: %s'
  150. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  151. return None
  152. def merge_cli(*args):
  153. try:
  154. c = merge(*args)
  155. except NotImplementedError as e:
  156. sys.stderr.write('%s. Conflicting key is %r. Values are:\n%s\n' % (e.args[0], e.args[1], e.args[2]))
  157. exit(1)
  158. if c is not None:
  159. print '%s' % yaml.dump(c, default_flow_style=False)
  160. "
  161. merge_yaml() {
  162. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  163. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  164. $_merge_yaml_common_code
  165. merge_cli(*(yaml.load(fc(f)) for f in sys.argv[1:]))
  166. EOF
  167. fi
  168. python "$state_tmpdir/merge_yaml.py" "$@"
  169. }
  170. export -f merge_yaml
  171. merge_yaml_str() {
  172. local entries="$@"
  173. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  174. cat <<EOF > "$state_tmpdir/merge_yaml_str.py"
  175. $_merge_yaml_common_code
  176. merge_cli(*(yaml.load(f) for f in sys.argv[1:]))
  177. EOF
  178. fi
  179. python "$state_tmpdir/merge_yaml_str.py" "$@"
  180. }
  181. export -f merge_yaml_str
  182. yaml_key_val_str() {
  183. local entries="$@"
  184. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  185. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  186. $_merge_yaml_common_code
  187. print '%s' % yaml.dump({
  188. yaml.load(sys.argv[1]):
  189. yaml.load(sys.argv[2])}, default_flow_style=False)
  190. EOF
  191. fi
  192. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  193. }
  194. export -f yaml_key_val_str
  195. ##
  196. ## Docker
  197. ##
  198. docker_has_image() {
  199. local image="$1"
  200. images=$(docker images -q "$image" 2>/dev/null) || {
  201. err "docker images call has failed unexpectedly."
  202. return 1
  203. }
  204. [ "$images" ]
  205. }
  206. export -f docker_has_image
  207. cmd_on_base_image() {
  208. local charm="$1"
  209. shift
  210. base_image=$(service_base_docker_image "$charm") || return 1
  211. docker run -i --entrypoint /bin/bash "$base_image" -c "$*"
  212. }
  213. export -f cmd_on_base_image
  214. cached_cmd_on_base_image() {
  215. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  216. shift
  217. if [ -e "$cache_file" ]; then
  218. # debug "$FUNCNAME: cache hit ($*)"
  219. quick_cat_stdin < "$cache_file"
  220. return 0
  221. fi
  222. base_image=$(service_base_docker_image "$charm") || return 1
  223. result=$(cmd_on_base_image "$charm" "$@") || return 1
  224. echo "$result" | tee "$cache_file"
  225. }
  226. export -f cached_cmd_on_base_image
  227. image_exposed_ports_0() {
  228. local image="$1"
  229. docker inspect --format='{{range $p, $conf := .Config.ExposedPorts}}{{$p}}{{"\x00"}}{{end}}' "$image"
  230. }
  231. export -f image_exposed_ports_0
  232. ##
  233. ## Generic
  234. ##
  235. fn.exists() {
  236. declare -F "$1" >/dev/null
  237. }
  238. str_matches() {
  239. local str="$1"
  240. shift
  241. for pattern in "$@"; do
  242. eval "[[ \"$str\" == $pattern ]]" && return 0
  243. done
  244. return 1
  245. }
  246. gen_password() {
  247. local l=( {a..z} {A..Z} {0..9} ) nl="${#l[@]}" size=${1:-16}
  248. while ((size--)); do
  249. echo -n "${l[$((RANDOM * nl / 32768))]}"
  250. done
  251. echo
  252. }
  253. export -f gen_password
  254. file_put() {
  255. local TARGET="$1"
  256. mkdir -p "$(dirname "$TARGET")" &&
  257. cat - > "$TARGET"
  258. }
  259. export -f file_put
  260. file_put_0() {
  261. local TARGET="$1"
  262. mkdir -p "$(dirname "$TARGET")" &&
  263. cat > "$TARGET"
  264. }
  265. export -f file_put_0
  266. fetch_file() {
  267. local src="$1"
  268. case "$src" in
  269. *"://"*)
  270. err "Unsupported target scheme."
  271. return 1
  272. ;;
  273. *)
  274. ## Try direct
  275. if ! [ -r "$src" ]; then
  276. err "File '$src' not found/readable."
  277. return 1
  278. fi
  279. cat "$src" || return 1
  280. ;;
  281. esac
  282. }
  283. export -f fetch_file
  284. ## receives stdin content to decompress on stdout
  285. ## stdout content should be tar format.
  286. uncompress_file() {
  287. local filename="$1"
  288. ## Warning, the content of the file is already as stdin, the filename
  289. ## is there to hint for correct decompression.
  290. case "$filename" in
  291. *".gz")
  292. gunzip
  293. ;;
  294. *".bz2")
  295. bunzip2
  296. ;;
  297. *)
  298. cat
  299. ;;
  300. esac
  301. }
  302. export -f uncompress_file
  303. get_file() {
  304. local src="$1"
  305. fetch_file "$src" | uncompress_file "$src"
  306. }
  307. export -f get_file
  308. ##
  309. ## Common database lib
  310. ##
  311. _clean_docker() {
  312. local _DB_NAME="$1" container_id="$2"
  313. (
  314. set +e
  315. debug "Removing container $_DB_NAME"
  316. docker stop "$container_id"
  317. docker rm "$_DB_NAME"
  318. rm -vf "/tmp/${_DB_NAME}.state"
  319. )
  320. }
  321. export -f _clean_docker
  322. get_service_base_image_dir_uid_gid() {
  323. local service="$1" dir="$2" uid_gid
  324. uid_gid=$(cached_cmd_on_base_image "$service" "stat -c '%u %g' '$dir'") || {
  325. debug "Failed to query '$dir' uid in ${DARKYELLOW}$service${NORMAL} base image."
  326. return 1
  327. }
  328. info "uid and gid from ${DARKYELLOW}$service${NORMAL}:$dir is '$uid_gid'"
  329. echo "$uid_gid"
  330. }
  331. export -f get_service_base_image_dir_uid_gid
  332. are_files_locked_in_dir() {
  333. local dir="$1" device hdev ldev
  334. device=$(stat -c %d "$dir") || {
  335. err "Can't stat %d."
  336. return 1
  337. }
  338. device=$(printf "%04x" $device)
  339. hdev=${device:0:2}
  340. ldev=${device:2:2}
  341. inodes=$(find "$dir" -printf ':%i:\n')
  342. found=
  343. while read -r inode; do
  344. debug "try inode:$inode"
  345. if [[ "$inodes" == *":$inode:"* ]]; then
  346. found=1
  347. break
  348. fi
  349. done < <(cat /proc/locks | grep " $hdev:$ldev:" | sed -r "s/^.*$hdev:$ldev:([0-9]+).*$/\1/g")
  350. [ "$found" ]
  351. }
  352. export -f are_files_locked_in_dir
  353. export _PID="$$"
  354. ensure_db_docker_running () {
  355. _DB_NAME="db_${DB_NAME}_${_PID}"
  356. if [ -e "/tmp/${_DB_NAME}.state" ]; then
  357. export DOCKER_IP="$(cat "/tmp/${_DB_NAME}.state")"
  358. debug "Re-using previous docker/connection '$DOCKER_IP'."
  359. _set_db_params "$DOCKER_IP"
  360. return 0
  361. fi
  362. if [ -e "/tmp/${_DB_NAME}.working" ]; then
  363. ## avoid recursive calls.
  364. if [ -z "$DOCKER_IP" ]; then
  365. err "Currently figuring up DOCKER_IP, please set it yourself before this call if needed."
  366. return 1
  367. else
  368. debug "Ignoring recursive call."
  369. fi
  370. return 0
  371. fi
  372. touch "/tmp/${_DB_NAME}.working"
  373. docker rm "$_DB_NAME" 2>/dev/null || true
  374. host_db_working_dir="$DATASTORE/${SERVICE_NAME}$DB_DATADIR"
  375. if is_db_locked; then
  376. info "Some process is using '$host_db_working_dir'. Trying to find a docker that would do this..."
  377. found=
  378. for docker_id in $(docker ps -q); do
  379. has_volume_mounted=$(
  380. docker inspect \
  381. --format "{{range .Mounts}}{{if eq .Destination \"$DB_DATADIR\"}}{{.Source}}{{end}}{{end}}" \
  382. "$docker_id")
  383. if [ "$has_volume_mounted" == "$host_db_working_dir" ]; then
  384. found="$docker_id"
  385. break
  386. fi
  387. done
  388. if [ -z "$found" ]; then
  389. err "Please shutdown any other docker using this directory."
  390. return 1
  391. fi
  392. export container_id="$found"
  393. info "Found docker $docker_id is already running."
  394. else
  395. verb "Database is not locked."
  396. if ! docker_has_image "$DOCKER_BASE_IMAGE"; then
  397. docker pull "$DOCKER_BASE_IMAGE"
  398. fi
  399. docker_opts=
  400. if [ -f "$DB_PASSFILE" ]; then
  401. verb "Found and using '$DB_PASSFILE'."
  402. docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  403. fi
  404. debug docker run -d \
  405. --name "$_DB_NAME" \
  406. $docker_opts \
  407. -v "$host_db_working_dir:$DB_DATADIR" \
  408. "$DOCKER_BASE_IMAGE"
  409. if ! container_id=$(
  410. docker run -d \
  411. --name "$_DB_NAME" \
  412. $docker_opts \
  413. -v "$host_db_working_dir:$DB_DATADIR" \
  414. "$DOCKER_BASE_IMAGE"
  415. ); then
  416. err "'docker run' failed !"
  417. _clean_docker "$_DB_NAME" "$container_id"
  418. rm "/tmp/${_DB_NAME}.working"
  419. return 1
  420. fi
  421. trap_add EXIT,ERR "_clean_docker '$_DB_NAME' '$container_id'"
  422. fi
  423. if DOCKER_IP=$(wait_for_docker_ip "$container_id"); then
  424. echo "$DOCKER_IP" > "/tmp/${_DB_NAME}.state"
  425. debug "written /tmp/${_DB_NAME}.state"
  426. rm "/tmp/${_DB_NAME}.working"
  427. _set_db_params "$DOCKER_IP"
  428. return 0
  429. else
  430. err "Db not found. Docker logs follows:"
  431. docker logs --tail=5 "$container_id" 2>&1 | prefix " | " >&2
  432. rm "/tmp/${_DB_NAME}.working"
  433. return 1
  434. fi
  435. }
  436. export -f ensure_db_docker_running
  437. ## Require to set $db_docker_opts if needed, and $DB_PASSFILE
  438. ##
  439. _dcmd() {
  440. local docker_opts command="$1"
  441. shift
  442. debug "Db> $command $@"
  443. if [ -f "$DB_PASSFILE" ]; then
  444. verb "Found and using '$DB_PASSFILE'."
  445. db_docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  446. fi
  447. debug docker run -i --rm \
  448. $db_docker_opts \
  449. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  450. docker run -i --rm \
  451. $db_docker_opts \
  452. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  453. }
  454. export -f _dcmd
  455. ## Executes code through db
  456. dcmd () {
  457. [ "$DB_NAME" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_NAME."
  458. [ "$DB_DATADIR" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_DATADIR."
  459. [ "$DB_PASSFILE" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_PASSFILE."
  460. [ "$_PID" ] || print_syntax_error "$FUNCNAME: You must provide \$_PID."
  461. [ "$(type -t is_db_locked)" == "function" ] || print_syntax_error "$FUNCNAME: You must provide function 'is_db_locked'."
  462. [ "$(type -t _set_db_params)" == "function" ] || print_syntax_error "$FUNCNAME: You must provide function '_set_db_params'."
  463. [ "$(type -t ddb)" == "function" ] || print_syntax_error "$FUNCNAME: You must provide function 'ddb'."
  464. ensure_db_docker_running </dev/null || return 1
  465. _dcmd "$@"
  466. }
  467. export -f dcmd
  468. ## Warning: requires a ``ddb`` matching current database to be checked
  469. wait_for_docker_ip() {
  470. local name=$1 timeout=5 timeout_count=0 DOCKER_IP= DB_OK=
  471. while [ -z "$DOCKER_IP" ]; do
  472. sleep 1
  473. DOCKER_IP=$(docker inspect --format='{{.NetworkSettings.IPAddress}}' "$name" 2>/dev/null)
  474. verb "[1/2] Waiting for docker $name... ($[timeout_count + 1]/$timeout)"
  475. ((timeout_count++)) || true
  476. if [ "$timeout_count" == "$timeout" ]; then
  477. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  478. "Could not find '$name' docker" \
  479. "container's IP."
  480. return 1
  481. fi
  482. done
  483. verb "[1/2] Found docker $name IP: $DOCKER_IP"
  484. timeout_count=0
  485. DB_OK=
  486. _set_db_params "$DOCKER_IP"
  487. while [ -z "$DB_OK" ]; do
  488. sleep 1
  489. echo "SELECT 1;" | ddb >/dev/null && DB_OK=1
  490. verb "[2/2] Waiting for db service from docker $name... ($[timeout_count + 1]/$timeout)"
  491. ((timeout_count++)) || true
  492. if [ "$timeout_count" == "$timeout" ]; then
  493. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  494. "Could not connect to db on $DOCKER_IP." \
  495. "container's IP."
  496. return 1
  497. fi
  498. done
  499. verb "[2/2] Db is ready !"
  500. echo "$DOCKER_IP"
  501. return 0
  502. }
  503. export -f wait_for_docker_ip
  504. ##
  505. ## Arrays
  506. ##
  507. array_values_to_stdin() {
  508. local e
  509. if [ "$#" -ne "1" ]; then
  510. print_syntax_warning "$FUNCNAME: need one argument."
  511. return 1
  512. fi
  513. var="$1"
  514. eval "for e in \"\${$var[@]}\"; do echo -en \"\$e\\0\"; done"
  515. }
  516. array_keys_to_stdin() {
  517. local e
  518. if [ "$#" -ne "1" ]; then
  519. print_syntax_warning "$FUNCNAME: need one argument."
  520. return 1
  521. fi
  522. var="$1"
  523. eval "for e in \"\${!$var[@]}\"; do echo -en \"\$e\\0\"; done"
  524. }
  525. array_kv_to_stdin() {
  526. local e
  527. if [ "$#" -ne "1" ]; then
  528. print_syntax_warning "$FUNCNAME: need one argument."
  529. return 1
  530. fi
  531. var="$1"
  532. eval "for e in \"\${!$var[@]}\"; do echo -n \"\$e\"; echo -en '\0'; echo -n \"\${$var[\$e]}\"; echo -en '\0'; done"
  533. }
  534. array_pop() {
  535. local narr="$1" nres="$2"
  536. for key in $(eval "echo \${!$narr[@]}"); do
  537. eval "$nres=\${$narr[\"\$key\"]}"
  538. eval "unset $narr[\"\$key\"]"
  539. return 0
  540. done
  541. }
  542. export -f array_pop
  543. array_member() {
  544. local src elt
  545. src="$1"
  546. elt="$2"
  547. while read-0 key; do
  548. if [ "$(eval "echo -n \"\${$src[\$key]}\"")" == "$elt" ]; then
  549. return 0
  550. fi
  551. done < <(array_keys_to_stdin "$src")
  552. return 1
  553. }
  554. export -f array_member
  555. ##
  556. ## Internal Process
  557. ##
  558. get_docker_compose_links() {
  559. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  560. links charm charm_part master_charm
  561. if [ -z "$service" ]; then
  562. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  563. return 1
  564. fi
  565. if [ -e "$cache_file" ]; then
  566. # debug "$FUNCNAME: cache hit ($*)"
  567. cat "$cache_file"
  568. return 0
  569. fi
  570. master_charm=$(get_top_master_charm_for_service "$service") || return 1
  571. deps=()
  572. while read-0 relation_name target_service relation_config tech_dep; do
  573. master_target_charm="$(get_top_master_charm_for_service "$target_service")"
  574. [ "$master_charm" == "$master_target_charm" ] && continue
  575. if [ "$tech_dep" == "reversed" ]; then
  576. deps+=("$(echo -en "$master_target_charm:\n links:\n - $master_charm")")
  577. elif [ "$tech_dep" == "True" ]; then
  578. deps+=("$(echo -en "$master_charm:\n links:\n - $master_target_charm")")
  579. fi
  580. done < <(get_compose_relations "$service") || return 1
  581. merge_yaml_str "${deps[@]}" | tee "$cache_file"
  582. }
  583. _get_docker_compose_opts() {
  584. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  585. links charm charm_part master_charm
  586. if [ -z "$service" ]; then
  587. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  588. return 1
  589. fi
  590. if [ -e "$cache_file" ]; then
  591. # debug "$FUNCNAME: cache hit ($*)"
  592. cat "$cache_file"
  593. return 0
  594. fi
  595. compose_def="$(get_compose_service_def "$service")" || return 1
  596. master_charm="$(get_top_master_charm_for_service "$service")"
  597. docker_compose_opts=$(echo "$compose_def" | shyaml get-value "docker-compose" 2>/dev/null)
  598. if [ "$docker_compose_opts" ]; then
  599. yaml_key_val_str "$master_charm" "$docker_compose_opts"
  600. fi | tee "$cache_file"
  601. }
  602. ##
  603. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  604. ## Some metadata.yml (of subordinates) will indeed modify other
  605. ## services than themselves.
  606. _get_docker_compose_service_mixin() {
  607. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" links charm charm_part
  608. if [ -z "$service" ]; then
  609. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  610. return 1
  611. fi
  612. if [ -e "$cache_file" ]; then
  613. # debug "$FUNCNAME: cache hit ($*)"
  614. cat "$cache_file"
  615. return 0
  616. fi
  617. master_charm=$(get_top_master_charm_for_service "$service") || return 1
  618. ## The compose part
  619. links_yaml=$(get_docker_compose_links "$service") || return 1
  620. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  621. ## the charm part
  622. #debug "Get charm name from service name $DARKYELLOW$service$NORMAL."
  623. charm=$(get_service_charm "$service") || return 1
  624. charm_part=$(get_docker_compose_mixin_from_metadata "$charm") || return 1
  625. ## Merge results
  626. if [ "$charm_part" ]; then
  627. charm_yaml="$(yaml_key_val_str "$master_charm" "$charm_part")" || return 1
  628. merge_yaml_str "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  629. else
  630. echo "$links_yaml"
  631. fi | tee "$cache_file"
  632. }
  633. export -f _get_docker_compose_service_mixin
  634. ##
  635. ## Get full `docker-compose.yml` format for all listed services (and
  636. ## their deps)
  637. ##
  638. ## @export
  639. ## @cache: !system !nofail +stdout
  640. get_docker_compose () {
  641. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" entries services service start
  642. if [ -e "$cache_file" ]; then
  643. # debug "$FUNCNAME: cache hit ($*)"
  644. cat "$cache_file"
  645. return 0
  646. fi
  647. ##
  648. ## Adding sub services configurations
  649. ##
  650. declare -A entries
  651. start_compilation=$SECONDS
  652. debug "Compiling 'docker-compose.yml' base for $DARKYELLOW$@$NORMAL..."
  653. for target_service in "$@"; do
  654. start=$SECONDS
  655. services=$(get_ordered_service_dependencies "$target_service") || return 1
  656. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" $services "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  657. for service in $services; do
  658. if [ "${entries[$service]}" ]; then
  659. ## Prevent double inclusion of same service if this
  660. ## service is deps of two or more of your
  661. ## requirements.
  662. continue
  663. fi
  664. ## mark the service as "loaded" as well as it's containers
  665. ## if this is a subordinate service
  666. start_service=$SECONDS
  667. entries[$service]=$(_get_docker_compose_service_mixin "$service") || return 1
  668. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  669. done
  670. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  671. done
  672. merge_yaml_str "${entries[@]}" > "$cache_file"
  673. export _current_docker_compose="$(cat "$cache_file")"
  674. echo "$_current_docker_compose"
  675. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  676. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  677. # debug "$_current_docker_compose"
  678. }
  679. export -f get_docker_compose
  680. _get_compose_service_def_cached () {
  681. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  682. if [ -e "$cache_file" ]; then
  683. #debug "$FUNCNAME: STATIC cache hit"
  684. cat "$cache_file"
  685. touch "$cache_file"
  686. return 0
  687. fi
  688. service_def_base="charm: $service"
  689. value=$(echo "$docker_compose" | shyaml get-value "$service" 2>/dev/null)
  690. merge_yaml <(echo "$service_def_base") <(echo "$value") | tee "$cache_file"
  691. }
  692. export -f _get_compose_service_def_cached
  693. ## XXXvlab: a lot to be done to cache the results
  694. get_compose_service_def () {
  695. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  696. result
  697. if [ -e "$cache_file" ]; then
  698. #debug "$FUNCNAME: SESSION cache hit"
  699. cat "$cache_file"
  700. return 0
  701. fi
  702. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  703. docker_compose=$(cat "$COMPOSE_YML_FILE") || return 1
  704. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  705. echo "$result" | tee "$cache_file"
  706. }
  707. export -f get_compose_service_def
  708. _get_service_charm_cached () {
  709. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  710. if [ -e "$cache_file" ]; then
  711. # debug "$FUNCNAME: cache hit $1"
  712. cat "$cache_file"
  713. touch "$cache_file"
  714. return 0
  715. fi
  716. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  717. if [ -z "$charm" ]; then
  718. err "Missing charm in service $DARKYELLOW$service$NORMAL definition."
  719. return 1
  720. fi
  721. echo "$charm" | tee "$cache_file"
  722. }
  723. export -f _get_service_charm_cached
  724. get_service_charm () {
  725. local service="$1"
  726. if [ -z "$service" ]; then
  727. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  728. return 1
  729. fi
  730. service_def=$(get_compose_service_def "$service") || return 1
  731. _get_service_charm_cached "$service" "$service_def"
  732. }
  733. export -f get_service_charm
  734. ## built above the docker-compose abstraction, so it relies on the
  735. ## full docker-compose.yml to be already built.
  736. get_service_def () {
  737. local service="$1" def
  738. if [ -z "$_current_docker_compose" ]; then
  739. print_syntax_error "$FUNCNAME is meant to be called after"\
  740. "\$_current_docker_compose has been calculated."
  741. fi
  742. def=$(echo "$_current_docker_compose" | shyaml get-value "$service" 2>/dev/null)
  743. if [ -z "$def" ]; then
  744. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  745. return 1
  746. fi
  747. echo "$def"
  748. }
  749. export -f get_service_def
  750. ## Return the base docker image name of a service
  751. service_base_docker_image() {
  752. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  753. master_charm charm service_image service_build service_dockerfile
  754. if [ -e "$cache_file" ]; then
  755. # debug "$FUNCNAME: cache hit ($*)"
  756. cat "$cache_file"
  757. return 0
  758. fi
  759. master_charm="$(get_top_master_charm_for_service "$service")" || {
  760. err "Could not compute base charm for service $DARKYELLOW$service$NORMAL."
  761. return 1
  762. }
  763. service_def="$(get_service_def "$master_charm")" || {
  764. err "Could not get docker-compose service definition for $DARKYELLOW$master_charm$NORMAL."
  765. return 1
  766. }
  767. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  768. if [ "$?" != 0 ]; then
  769. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  770. if [ "$?" != 0 ]; then
  771. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  772. echo "$service_def" >&2
  773. return 1
  774. fi
  775. service_dockerfile="$CHARM_STORE/${service_build}/Dockerfile"
  776. if ! [ -e "$service_dockerfile" ]; then
  777. err "No Dockerfile found in '$service_dockerfile' location."
  778. return 1
  779. fi
  780. grep '^FROM' "$service_dockerfile" | xargs echo | cut -f 2 -d " "
  781. else
  782. echo "$service_image"
  783. fi | tee "$cache_file"
  784. }
  785. export -f service_base_docker_image
  786. get_charm_relation_def () {
  787. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  788. relation_def metadata
  789. if [ -e "$cache_file" ]; then
  790. # debug "$FUNCNAME: cache hit ($*)"
  791. cat "$cache_file"
  792. return 0
  793. fi
  794. metadata="$(get_charm_metadata "$charm")" || return 1
  795. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  796. echo "$relation_def" | tee "$cache_file"
  797. }
  798. export -f get_charm_relation_def
  799. get_charm_tech_dep_orientation_for_relation() {
  800. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  801. relation_def metadata value
  802. if [ -e "$cache_file" ]; then
  803. # debug "$FUNCNAME: cache hit ($*)"
  804. cat "$cache_file"
  805. return 0
  806. fi
  807. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  808. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  809. value=${value:-True}
  810. echo "$value" | tee "$cache_file"
  811. }
  812. export -f get_charm_tech_dep_orientation_for_relation
  813. ##
  814. ## Use compose file to get deps, and relation definition in metadata.yml
  815. ## for tech-dep attribute.
  816. get_service_deps() {
  817. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  818. if [ -e "$cache_file" ]; then
  819. # debug "$FUNCNAME: cache hit ($*)"
  820. cat "$cache_file"
  821. return 0
  822. fi
  823. (
  824. set -o pipefail
  825. get_compose_relations "$service" | \
  826. while read-0 relation_name target_service _relation_config tech_dep; do
  827. echo "$target_service"
  828. done | tee "$cache_file"
  829. ) || return 1
  830. }
  831. export -f get_service_deps
  832. _rec_get_depth() {
  833. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  834. [ "${depths[$elt]}" ] && return 0
  835. if [ -e "$cache_file" ]; then
  836. # debug "$FUNCNAME: cache hit ($*)"
  837. depths[$elt]=$(cat "$cache_file")
  838. return 0
  839. fi
  840. visited[$elt]=1
  841. #debug "Setting visited[$elt]"
  842. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  843. deps=$(get_service_deps "$elt") || {
  844. debug "Failed get_service_deps $elt"
  845. return 1
  846. }
  847. # debug "$elt deps are:" $deps
  848. max=0
  849. for dep in $deps; do
  850. [ "${visited[$dep]}" ] && {
  851. #debug "Already computing $dep"
  852. continue
  853. }
  854. _rec_get_depth "$dep" || return 1
  855. #debug "Requesting depth[$dep]"
  856. if (( ${depths[$dep]} > max )); then
  857. max="${depths[$dep]}"
  858. fi
  859. done
  860. # debug "Setting depth[$elt] to $((max + 1))"
  861. depths[$elt]=$((max + 1))
  862. echo "${depths[$elt]}" > $cache_file
  863. }
  864. export -f _rec_get_depth
  865. get_ordered_service_dependencies() {
  866. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  867. if [ -e "$cache_file" ]; then
  868. # debug "$FUNCNAME: cache hit ($*)"
  869. cat "$cache_file"
  870. return 0
  871. fi
  872. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  873. if [ -z "${services[*]}" ]; then
  874. print_syntax_error "$FUNCNAME: no arguments"
  875. return 1
  876. fi
  877. declare -A depths
  878. declare -A visited
  879. heads=("${services[@]}")
  880. while [ "${#heads[@]}" != 0 ]; do
  881. array_pop heads head
  882. _rec_get_depth "$head" || return 1
  883. done
  884. i=0
  885. while [ "${#depths[@]}" != 0 ]; do
  886. for key in "${!depths[@]}"; do
  887. value="${depths[$key]}"
  888. if [ "$value" == "$i" ]; then
  889. echo "$key"
  890. unset depths[$key]
  891. fi
  892. done
  893. i=$((i + 1))
  894. done | tee "$cache_file"
  895. }
  896. export -f get_ordered_service_dependencies
  897. run_service_hook () {
  898. local services="$1" action="$2" loaded
  899. declare -A loaded
  900. for service in $services; do
  901. for subservice in $(get_ordered_service_dependencies "$service"); do
  902. if [ "${loaded[$subservice]}" ]; then
  903. ## Prevent double inclusion of same service if this
  904. ## service is deps of two or more of your
  905. ## requirements.
  906. continue
  907. fi
  908. charm=$(get_service_charm "$subservice") || return 1
  909. TARGET_SCRIPT="$CHARM_STORE/$charm/hooks/$action"
  910. [ -e "$TARGET_SCRIPT" ] || continue
  911. PROJECT_NAME=$(get_default_project_name) || return 1
  912. Wrap -d "$YELLOW$action$NORMAL hook of charm $DARKYELLOW$charm$NORMAL" <<EOF || return 1
  913. cd "$CHARM_STORE/$charm"
  914. export SERVICE_NAME=$subservice
  915. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  916. export CONTAINER_NAME=\${IMAGE_NAME}_1
  917. export CHARM_NAME="$charm"
  918. export PROJECT_NAME=$PROJECT_NAME
  919. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$charm")
  920. export SERVICE_DATASTORE="$DATASTORE/$charm"
  921. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm"
  922. "$TARGET_SCRIPT"
  923. EOF
  924. loaded[$subservice]=1
  925. done
  926. done
  927. return 0
  928. }
  929. host_resource_get() {
  930. local location="$1" cfg="$2"
  931. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  932. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  933. return 1
  934. }
  935. if fn.exists host_resource_get_$type; then
  936. host_resource_get_$type "$location" "$cfg"
  937. else
  938. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  939. "${WHITE}host-resource$NORMAL '$location' defined in" \
  940. "$DARKYELLOW$subservice$NORMAL config."
  941. return 1
  942. fi
  943. }
  944. export -f host_resource_get
  945. host_resource_get_git() {
  946. local location="$1" cfg="$2" branch parent url
  947. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  948. branch=${branch:-master}
  949. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  950. parent="$(dirname "$location")"
  951. (
  952. mkdir -p "$parent" && cd "$parent" &&
  953. git clone -b "$branch" "$url" "$(basename "$location")"
  954. ) || return 1
  955. }
  956. export -f host_resource_get_git
  957. host_resource_get_git-sub() {
  958. local location="$1" cfg="$2" branch parent url
  959. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  960. branch=${branch:-master}
  961. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  962. parent="$(dirname "$location")"
  963. (
  964. mkdir -p "$parent" && cd "$parent" &&
  965. git sub clone -b "$branch" "$url" "$(basename "$location")"
  966. ) || return 1
  967. }
  968. export -f host_resource_get_git-sub
  969. setup_host_resources () {
  970. local services="$1" action="$2" loaded location cfg
  971. declare -A loaded
  972. for service in $services; do
  973. for subservice in $(get_ordered_service_dependencies "$service"); do
  974. if [ "${loaded[$subservice]}" ]; then
  975. ## Prevent double inclusion of same service if this
  976. ## service is deps of two or more of your
  977. ## requirements.
  978. continue
  979. fi
  980. service_def=$(get_compose_service_def "$subservice") || return 1
  981. while read-0 location cfg; do
  982. ## XXXvlab: will it be a git resources always ?
  983. if [ -d "$location" -a ! -d "$location/.git" ]; then
  984. err "Hum, location '$location' does not seem to be a git directory."
  985. return 1
  986. fi
  987. if [ -d "$location" ]; then
  988. info "host resource '$location' already set up."
  989. continue
  990. fi
  991. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  992. if [ -z "$get" ]; then
  993. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  994. "specified for $DARKYELLOW$subservice$NORMAL."
  995. return 1
  996. fi
  997. host_resource_get "$location" "$get" || return 1
  998. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  999. loaded[$subservice]=1
  1000. done
  1001. done
  1002. return 0
  1003. }
  1004. relation-get () {
  1005. local key="$1"
  1006. cat "$RELATION_DATA_FILE" | shyaml get-value "$key" 2>/dev/null
  1007. if [ "$?" != 0 ]; then
  1008. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1009. return 1
  1010. fi
  1011. }
  1012. export -f relation-get
  1013. relation-base-compose-get () {
  1014. local key="$1"
  1015. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1016. if [ "$?" != 0 ]; then
  1017. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1018. return 1
  1019. fi
  1020. }
  1021. export -f relation-base-compose-get
  1022. relation-target-compose-get () {
  1023. local key="$1"
  1024. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1025. if [ "$?" != 0 ]; then
  1026. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1027. return 1
  1028. fi
  1029. }
  1030. export -f relation-target-compose-get
  1031. relation-set () {
  1032. local key="$1" value="$2"
  1033. if [ -z "$RELATION_DATA_FILE" ]; then
  1034. err "$FUNCNAME: relation does not seems to be correctly setup."
  1035. return 1
  1036. fi
  1037. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1038. err "$FUNCNAME: can't read relation's data." >&2
  1039. return 1
  1040. fi
  1041. _config_merge "$RELATION_DATA_FILE" <(echo "$key: $value")
  1042. }
  1043. export -f relation-set
  1044. _config_merge() {
  1045. local config_filename="$1" merge_to_file="$2"
  1046. touch "$config_filename" &&
  1047. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  1048. mv "$config_filename.tmp" "$config_filename"
  1049. }
  1050. export -f _config_merge
  1051. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1052. config-add() {
  1053. local metadata="$1"
  1054. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1055. }
  1056. export -f config-add
  1057. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1058. init-config-add() {
  1059. local metadata="$1"
  1060. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" <(echo "$metadata")
  1061. }
  1062. export -f init-config-add
  1063. logstdout() {
  1064. local name="$1"
  1065. sed -r 's%^%'"${name}"'> %g'
  1066. }
  1067. export -f logstdout
  1068. logstderr() {
  1069. local name="$1"
  1070. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1071. }
  1072. export -f logstderr
  1073. _run_service_relation () {
  1074. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1075. charm=$(get_service_charm "$service") || return 1
  1076. target_charm=$(get_service_charm "$target_service") || return 1
  1077. base_script_name=$(echo "$relation_name" | tr "-" "_" )-relation-joined
  1078. script_name="hooks/${base_script_name}"
  1079. [ ! -e "$CHARM_STORE/$target_charm/$script_name" -a ! -e "$CHARM_STORE/$charm/$script_name" ] &&
  1080. return 0
  1081. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  1082. RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config") || return 1
  1083. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$service") || return 1
  1084. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  1085. export BASE_SERVICE_NAME=$service
  1086. export TARGET_SERVICE_NAME=$target_service
  1087. export BASE_CHARM_NAME=$charm
  1088. export TARGET_CHARM_NAME=$target_charm
  1089. PROJECT_NAME=$(get_default_project_name) || return 1
  1090. MASTER_BASE_CHARM_NAME=$(get_top_master_charm_for_service "$service") || return 1
  1091. MASTER_TARGET_CHARM_NAME=$(get_top_master_charm_for_service "$target_service") || return 1
  1092. export RELATION_DATA_FILE RELATION_BASE_COMPOSE_DEF RELATION_TARGET_COMPOSE_DEF
  1093. export MASTER_BASE_CHARM_NAME MASTER_TARGET_CHARM_NAME PROJECT_NAME
  1094. target_errlvl=0
  1095. if ! [ -e "$CHARM_STORE/$target_charm/$script_name" ]; then
  1096. verb "No relation script '$script_name' in $DARKYELLOW$target_charm$NORMAL."
  1097. else
  1098. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1099. "for target charm $DARKYELLOW$target_charm$NORMAL"
  1100. RELATION_CONFIG="$relation_dir/config_provider"
  1101. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1102. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1103. {
  1104. (
  1105. cd "$CHARM_STORE/$target_charm"
  1106. SERVICE_NAME=$target_service
  1107. SERVICE_DATASTORE="$DATASTORE/$target_charm"
  1108. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_charm"
  1109. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1110. "$script_name"
  1111. echo "$?" > "$relation_dir/target_errlvl"
  1112. ) | logstdout "$DARKYELLOW$target_charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1113. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1114. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1115. err "Relation script '$script_name' in $DARKYELLOW$target_charm$NORMAL" \
  1116. "failed before outputing an errorlevel."
  1117. ((target_errlvl |= "1" ))
  1118. }
  1119. if [ -e "$RELATION_CONFIG" ]; then
  1120. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1121. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1122. rm "$RELATION_CONFIG"
  1123. ((target_errlvl |= "$?"))
  1124. fi
  1125. fi
  1126. if [ "$target_errlvl" == 0 ]; then
  1127. errlvl=0
  1128. if [ -e "$CHARM_STORE/$charm/$script_name" ]; then
  1129. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1130. "for charm $DARKYELLOW$charm$NORMAL"
  1131. RELATION_CONFIG="$relation_dir/config_providee"
  1132. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1133. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1134. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1135. {
  1136. (
  1137. cd "$CHARM_STORE/$charm"
  1138. SERVICE_NAME=$service
  1139. SERVICE_DATASTORE="$DATASTORE/$charm"
  1140. SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm"
  1141. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1142. "$script_name"
  1143. echo "$?" > "$relation_dir/errlvl"
  1144. ) | logstdout "$DARKYELLOW$charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1145. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1146. errlvl="$(cat "$relation_dir/errlvl")" || {
  1147. err "Relation script '$script_name' in $DARKYELLOW$charm$NORMAL" \
  1148. "failed before outputing an errorlevel."
  1149. ((errlvl |= "1" ))
  1150. }
  1151. if [ -e "$RELATION_CONFIG" ]; then
  1152. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1153. rm "$RELATION_CONFIG"
  1154. ((errlvl |= "$?" ))
  1155. fi
  1156. if [ "$errlvl" != 0 ]; then
  1157. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$charm$NORMAL failed to run properly."
  1158. fi
  1159. else
  1160. verb "No relation script '$script_name' in charm $DARKYELLOW$charm$NORMAL. Ignoring."
  1161. fi
  1162. else
  1163. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_charm$NORMAL failed to run properly."
  1164. fi
  1165. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1166. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1167. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1168. return 0
  1169. else
  1170. return 1
  1171. fi
  1172. }
  1173. export -f _run_service_relation
  1174. _get_compose_relations_cached () {
  1175. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1176. relation_name relation_def target_service
  1177. if [ -e "$cache_file" ]; then
  1178. #debug "$FUNCNAME: STATIC cache hit $1"
  1179. cat "$cache_file"
  1180. touch "$cache_file"
  1181. return 0
  1182. fi
  1183. (
  1184. set -o pipefail
  1185. if [ "$compose_service_def" ]; then
  1186. while read-0 relation_name relation_def; do
  1187. (
  1188. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1189. "str")
  1190. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)"
  1191. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1192. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1193. ;;
  1194. "sequence")
  1195. while read-0 target_service; do
  1196. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1197. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1198. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1199. ;;
  1200. "struct")
  1201. while read-0 target_service relation_config; do
  1202. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1203. echo -en "$relation_name\0$target_service\0$relation_config\0$tech_dep\0"
  1204. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1205. ;;
  1206. esac
  1207. ) </dev/null >> "$cache_file"
  1208. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1209. fi
  1210. )
  1211. if [ "$?" != 0 ]; then
  1212. err "Error while looking for compose relations."
  1213. rm -f "$cache_file" ## no cache
  1214. return 1
  1215. fi
  1216. [ -e "$cache_file" ] && cat "$cache_file"
  1217. return 0
  1218. }
  1219. export -f _get_compose_relations_cached
  1220. get_compose_relations () {
  1221. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1222. compose_def
  1223. if [ -e "$cache_file" ]; then
  1224. #debug "$FUNCNAME: SESSION cache hit $1"
  1225. cat "$cache_file"
  1226. return 0
  1227. fi
  1228. compose_def="$(get_compose_service_def "$service")" || return 1
  1229. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1230. if [ "$?" != 0 ]; then
  1231. err "Error while looking for compose relations."
  1232. rm -f "$cache_file" ## no cache
  1233. return 1
  1234. fi
  1235. cat "$cache_file"
  1236. }
  1237. export -f get_compose_relations
  1238. run_service_relations () {
  1239. local services="$1" loaded
  1240. declare -A loaded
  1241. for service in $(get_ordered_service_dependencies $services); do
  1242. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  1243. for subservice in $(get_service_deps "$service") "$service"; do
  1244. [ "${loaded[$subservice]}" ] && continue
  1245. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  1246. while read-0 relation_name target_service relation_config tech_dep; do
  1247. export relation_config
  1248. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  1249. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  1250. EOF
  1251. done < <(get_compose_relations "$subservice") || return 1
  1252. loaded[$subservice]=1
  1253. done
  1254. done
  1255. }
  1256. export -f run_service_relations
  1257. _run_service_action_direct() {
  1258. local service="$1" action="$2" charm script _dummy
  1259. shift; shift
  1260. read-0 charm script || true ## against 'set -e' that could be setup in parent scripts
  1261. if read-0 _dummy || [ "$_dummy" ]; then
  1262. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1263. return 1
  1264. fi
  1265. compose_file=$(get_compose_yml_location) || return 1
  1266. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1267. export state_tmpdir
  1268. {
  1269. (
  1270. set +e ## Prevents unwanted leaks from parent shell
  1271. cd "$CHARM_STORE/$charm"
  1272. export COMPOSE_CONFIG=$(cat "$compose_file")
  1273. export METADATA_CONFIG=$(cat "$CHARM_STORE/$charm/metadata.yml")
  1274. export SERVICE_NAME=$service
  1275. export ACTION_NAME=$action
  1276. export CONTAINER_NAME=$(get_top_master_charm_for_service "$service")
  1277. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1278. export SERVICE_DATASTORE="$DATASTORE/$service"
  1279. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1280. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1281. stdbuf -oL -eL "$script" "$@"
  1282. echo "$?" > "$action_errlvl_file"
  1283. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1284. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1285. if ! [ -e "$action_errlvl_file" ]; then
  1286. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1287. "to output an errlvl"
  1288. return 1
  1289. fi
  1290. return "$(cat "$action_errlvl_file")"
  1291. }
  1292. export -f _run_service_action_direct
  1293. _run_service_action_relation() {
  1294. local service="$1" action="$2" charm target_charm relation_name target_script relation_config _dummy
  1295. shift; shift
  1296. read-0 charm target_charm relation_name target_script relation_config || true
  1297. if read-0 _dummy || [ "$_dummy" ]; then
  1298. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1299. return 1
  1300. fi
  1301. export RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config")
  1302. compose_file=$(get_compose_yml_location) || return 1
  1303. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1304. export state_tmpdir
  1305. {
  1306. (
  1307. set +e ## Prevents unwanted leaks from parent shell
  1308. cd "$CHARM_STORE/$charm"
  1309. export METADATA_CONFIG=$(cat "$CHARM_STORE/$charm/metadata.yml")
  1310. export SERVICE_NAME=$service
  1311. export RELATION_TARGET_CHARM="$target_charm"
  1312. export RELATION_BASE_CHARM="$charm"
  1313. export ACTION_NAME=$action
  1314. export CONTAINER_NAME=$(get_top_master_charm_for_service "$service")
  1315. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1316. export SERVICE_DATASTORE="$DATASTORE/$service"
  1317. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1318. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1319. stdbuf -oL -eL "$target_script" "$@"
  1320. echo "$?" > "$action_errlvl_file"
  1321. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1322. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1323. if ! [ -e "$action_errlvl_file" ]; then
  1324. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1325. "to output an errlvl"
  1326. return 1
  1327. fi
  1328. return "$(cat "$action_errlvl_file")"
  1329. }
  1330. export -f _run_service_action_relation
  1331. get_relation_data_dir() {
  1332. local charm="$1" target_charm="$2" relation_name="$3" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1333. if [ -e "$cache_file" ]; then
  1334. # debug "$FUNCNAME: cache hit ($*)"
  1335. cat "$cache_file"
  1336. return 0
  1337. fi
  1338. project=$(get_default_project_name) || return 1
  1339. relation_dir="$VARDIR/relations/$project/$charm-$target_charm/$relation_name"
  1340. if ! [ -d "$relation_dir" ]; then
  1341. mkdir -p "$relation_dir" || return 1
  1342. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  1343. fi
  1344. echo "$relation_dir" || tee "$cache_file"
  1345. }
  1346. export -f get_relation_data_dir
  1347. get_relation_data_file() {
  1348. local charm="$1" target_charm="$2" relation_name="$3" relation_config="$4"
  1349. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  1350. relation_data_file="$relation_dir/data"
  1351. new=
  1352. if [ -e "$relation_data_file" ]; then
  1353. ## Has reference changed ?
  1354. new_md5=$(echo "$relation_config" | md5_compat)
  1355. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  1356. new=true
  1357. fi
  1358. else
  1359. new=true
  1360. fi
  1361. if [ "$new" ]; then
  1362. echo "$relation_config" > "$relation_data_file"
  1363. chmod go-rwx "$relation_data_file" ## protecting this file
  1364. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  1365. fi
  1366. echo "$relation_data_file"
  1367. }
  1368. export -f get_relation_data_file
  1369. has_service_action () {
  1370. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1371. target_script charm target_charm
  1372. if [ -e "$cache_file" ]; then
  1373. # debug "$FUNCNAME: cache hit ($*)"
  1374. cat "$cache_file"
  1375. return 0
  1376. fi
  1377. charm=$(get_service_charm "$service") || return 1
  1378. ## Action directly provided ?
  1379. target_script="$CHARM_STORE/$charm/actions/$action"
  1380. if [ -x "$target_script" ]; then
  1381. echo -en "direct\0$charm\0$target_script" | tee "$cache_file"
  1382. return 0
  1383. fi
  1384. ## Action provided by relation ?
  1385. while read-0 relation_name target_service relation_config tech_dep; do
  1386. target_charm=$(get_service_charm "$target_service") || return 1
  1387. target_script="$CHARM_STORE/$target_charm/actions/relations/$relation_name/$action"
  1388. if [ -x "$target_script" ]; then
  1389. echo -en "relation\0$charm\0$target_charm\0$relation_name\0$target_script\0$relation_config" | tee "$cache_file"
  1390. return 0
  1391. fi
  1392. done < <(get_compose_relations "$service")
  1393. return 1
  1394. # master=$(get_top_master_charm_for_service "$charm")
  1395. # [ "$master" == "$charm" ] && return 1
  1396. # has_service_action "$master" "$action"
  1397. }
  1398. export -f has_service_action
  1399. run_service_action () {
  1400. local service="$1" action="$2"
  1401. shift ; shift
  1402. {
  1403. if ! read-0 action_type; then
  1404. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  1405. info " Add an executable script to '$CHARM_STORE/$charm/actions/$action' to implement action."
  1406. return 1
  1407. fi
  1408. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  1409. "_run_service_action_${action_type}" "$service" "$action" "$@"
  1410. } < <(has_service_action "$service" "$action")
  1411. }
  1412. export -f run_service_action
  1413. get_compose_relation_config() {
  1414. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1415. if [ -e "$cache_file" ]; then
  1416. # debug "$FUNCNAME: cache hit ($*)"
  1417. cat "$cache_file"
  1418. return 0
  1419. fi
  1420. compose_service_def=$(get_compose_service_def "$service") || return 1
  1421. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  1422. }
  1423. export -f get_compose_relation_config
  1424. # ## Return key-values-0
  1425. # get_compose_relation_config_for_service() {
  1426. # local service=$1 relation_name=$2 relation_config
  1427. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  1428. # if ! relation_config=$(
  1429. # echo "$compose_service_relations" |
  1430. # shyaml get-value "${relation_name}" 2>/dev/null); then
  1431. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  1432. # "relation config in compose configuration."
  1433. # return 1
  1434. # fi
  1435. # if [ -z "$relation_config" ]; then
  1436. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  1437. # return 1
  1438. # fi
  1439. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  1440. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  1441. # return 1
  1442. # fi
  1443. # }
  1444. # export -f get_compose_relation_config_for_service
  1445. _get_master_charm_for_service_cached () {
  1446. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1447. charm requires master_charm target_charm target_service service_def
  1448. if [ -e "$cache_file" ]; then
  1449. # debug "$FUNCNAME: STATIC cache hit ($1)"
  1450. cat "$cache_file"
  1451. touch "$cache_file"
  1452. return 0
  1453. fi
  1454. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  1455. ## just return charm name
  1456. echo "$charm" | tee "$cache_file"
  1457. return 0
  1458. fi
  1459. ## fetch the container relation
  1460. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1461. if [ -z "$requires" ]; then
  1462. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any 'requires' " \
  1463. "section."
  1464. fi
  1465. master_charm=
  1466. while read-0 relation_name relation; do
  1467. if [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ]; then
  1468. # debug "$DARKYELLOW$service$NORMAL's relation" \
  1469. # "$DARKBLUE${relation_name}$NORMAL is a container."
  1470. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1471. if [ -z "$interface" ]; then
  1472. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1473. return 1
  1474. fi
  1475. ## Action provided by relation ?
  1476. target_service=
  1477. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  1478. [ "$interface" == "$relation_name" ] && {
  1479. target_service="$candidate_target_service"
  1480. break
  1481. }
  1482. done < <(get_compose_relations "$service")
  1483. if [ -z "$target_service" ]; then
  1484. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1485. "${DARKYELLOW}$service$NORMAL compose definition."
  1486. return 1
  1487. fi
  1488. master_charm=$(get_service_charm "$target_service") || return 1
  1489. break
  1490. fi
  1491. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1492. if [ -z "$master_charm" ]; then
  1493. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any relation with" \
  1494. " ${WHITE}scope${NORMAL} set to 'container'."
  1495. fi
  1496. echo "$master_charm" | tee "$cache_file"
  1497. }
  1498. export -f _get_master_charm_for_service_cached
  1499. get_master_charm_for_service() {
  1500. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1501. charm metadata result
  1502. if [ -e "$cache_file" ]; then
  1503. # debug "$FUNCNAME: SESSION cache hit ($*)"
  1504. cat "$cache_file"
  1505. return 0
  1506. fi
  1507. charm=$(get_service_charm "$service") || return 1
  1508. metadata=$(get_charm_metadata "$charm") || return 1
  1509. result=$(_get_master_charm_for_service_cached "$service" "$charm" "$metadata") || return 1
  1510. echo "$result" | tee "$cache_file"
  1511. }
  1512. export -f get_master_charm_for_service
  1513. get_top_master_charm_for_service() {
  1514. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1515. current_service
  1516. if [ -e "$cache_file" ]; then
  1517. # debug "$FUNCNAME: cache hit ($*)"
  1518. cat "$cache_file"
  1519. return 0
  1520. fi
  1521. current_service="$service"
  1522. while true; do
  1523. master_service=$(get_master_charm_for_service "$current_service") || return 1
  1524. [ "$master_service" == "$current_service" ] && break
  1525. current_service="$master_service"
  1526. done
  1527. echo "$current_service" | tee "$cache_file"
  1528. return 0
  1529. }
  1530. export -f get_top_master_charm_for_service
  1531. get_charm_metadata() {
  1532. local charm="$1" metadata_file
  1533. metadata_file="$CHARM_STORE/$charm/metadata.yml"
  1534. if ! [ -e "$metadata_file" ]; then
  1535. return 0 ## No metadata file is as if metadata was empty
  1536. fi
  1537. if ! [ -d "$CHARM_STORE/$charm" ]; then
  1538. die "No charm $charm was found in charm store."
  1539. fi
  1540. cat "$metadata_file"
  1541. }
  1542. export -f get_charm_metadata
  1543. ##
  1544. ## The result is a mixin that is not always a complete valid
  1545. ## docker-compose entry (thinking of subordinates). The result
  1546. ## will be merge with master charms.
  1547. _get_docker_compose_mixin_from_metadata_cached() {
  1548. local charm="$1" metadata="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1549. metadata_file metadata volumes docker_compose subordinate image
  1550. if [ -e "$cache_file" ]; then
  1551. #debug "$FUNCNAME: STATIC cache hit $1"
  1552. cat "$cache_file"
  1553. touch "$cache_file"
  1554. return 0
  1555. fi
  1556. mixin=
  1557. if [ "$metadata" ]; then
  1558. ## resources to volumes
  1559. volumes=$(
  1560. for resource_type in data config; do
  1561. while read-0 resource; do
  1562. eval "echo \" - \$${resource_type^^}STORE/\$charm\$resource:\$resource:rw\""
  1563. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1564. done
  1565. while read-0 resource; do
  1566. if [[ "$resource" == *:* ]]; then
  1567. echo " - $resource:rw"
  1568. else
  1569. echo " - $resource:$resource:rw"
  1570. fi
  1571. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1572. while read-0 resource; do
  1573. echo " - $CHARM_STORE/$charm/resources$resource:$resource:rw"
  1574. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1575. ) || return 1
  1576. if [ "$volumes" ]; then
  1577. mixin=$(echo -en "volumes:\n$volumes")
  1578. fi
  1579. docker_compose=$(echo "$metadata" | shyaml get-value "docker-compose" 2>/dev/null)
  1580. if [ "$docker_compose" ]; then
  1581. mixin=$(merge_yaml_str "$mixin" "$docker_compose")
  1582. fi
  1583. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1584. subordinate=true
  1585. fi
  1586. fi
  1587. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1588. image_or_build_statement=
  1589. if [ "$image" ]; then
  1590. if [ "$subordinate" ]; then
  1591. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1592. return 1
  1593. fi
  1594. image_or_build_statement="image: $image"
  1595. elif [ -d "$CHARM_STORE/$charm/build" ]; then
  1596. if [ "$subordinate" ]; then
  1597. err "Subordinate charm can not have a 'build' sub directory."
  1598. return 1
  1599. fi
  1600. image_or_build_statement="build: $charm/build"
  1601. fi
  1602. if [ "$image_or_build_statement" ]; then
  1603. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1604. fi
  1605. echo "$mixin" | tee "$cache_file"
  1606. }
  1607. export -f _get_docker_compose_mixin_from_metadata_cached
  1608. get_docker_compose_mixin_from_metadata() {
  1609. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1610. if [ -e "$cache_file" ]; then
  1611. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1612. cat "$cache_file"
  1613. return 0
  1614. fi
  1615. metadata="$(get_charm_metadata "$charm")" || return 1
  1616. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$charm" "$metadata") || return 1
  1617. echo "$mixin" | tee "$cache_file"
  1618. }
  1619. export -f get_docker_compose_mixin_from_metadata
  1620. _save() {
  1621. local name="$1"
  1622. cat - | tee -a "$docker_compose_dir/.data/$name"
  1623. }
  1624. export -f _save
  1625. get_default_project_name() {
  1626. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1627. echo "$DEFAULT_PROJECT_NAME"
  1628. return 0
  1629. fi
  1630. compose_yml_location="$(get_compose_yml_location)" || return 1
  1631. if [ "$compose_yml_location" ]; then
  1632. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1633. echo "$(basename "$(dirname "$normalized_path")")"
  1634. return 0
  1635. fi
  1636. fi
  1637. echo "project"
  1638. return 0
  1639. }
  1640. export -f get_default_project_name
  1641. launch_docker_compose() {
  1642. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1643. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1644. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1645. # rm -rf \"$docker_compose_tmpdir\""
  1646. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1647. project=$(get_default_project_name)
  1648. mkdir -p "$docker_compose_tmpdir/$project"
  1649. docker_compose_dir="$docker_compose_tmpdir/$project"
  1650. if [ -z "$SERVICE_PACK" ]; then
  1651. export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1652. fi
  1653. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1654. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1655. # debug "Merging some config data in docker-compose.yml:"
  1656. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1657. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1658. fi
  1659. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  1660. die "Unexpected empty docker-compose."
  1661. fi
  1662. ## XXXvlab: could be more specific and only link the needed charms
  1663. ln -sf "$CHARM_STORE/"* "$docker_compose_dir/"
  1664. mkdir "$docker_compose_dir/.data"
  1665. {
  1666. {
  1667. cd "$docker_compose_dir"
  1668. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  1669. debug "$(cat "$docker_compose_dir/docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  1670. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1671. docker-compose "$@"
  1672. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1673. } | _save stdout
  1674. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1675. 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
  1676. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1677. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1678. fi
  1679. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  1680. if [ -z "$docker_compose_errlvl" ]; then
  1681. err "Something went wrong before you could gather docker-compose errorlevel."
  1682. return 1
  1683. fi
  1684. return "$docker_compose_errlvl"
  1685. }
  1686. export -f launch_docker_compose
  1687. get_compose_yml_location() {
  1688. parent=$(while ! [ -e "./compose.yml" ]; do
  1689. [ "$PWD" == "/" ] && exit 0
  1690. cd ..
  1691. done; echo "$PWD"
  1692. )
  1693. if [ "$parent" ]; then
  1694. echo "$parent/compose.yml"
  1695. return 0
  1696. fi
  1697. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1698. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1699. err "No 'compose.yml' was found in current or parent dirs," \
  1700. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file."
  1701. die "Please provide a 'compose.yml' file."
  1702. fi
  1703. echo "$DEFAULT_COMPOSE_FILE"
  1704. return 0
  1705. fi
  1706. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1707. die "Please provide a 'compose.yml' file."
  1708. return 1
  1709. }
  1710. export -f get_compose_yml_location
  1711. get_default_target_services() {
  1712. local services=("$@")
  1713. if [ -z "${services[*]}" ]; then
  1714. if [ "$DEFAULT_SERVICES" ]; then
  1715. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1716. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1717. services="$DEFAULT_SERVICES"
  1718. else
  1719. err "No service provided."
  1720. return 1
  1721. fi
  1722. fi
  1723. echo "${services[*]}"
  1724. }
  1725. export -f get_default_target_services
  1726. get_master_services() {
  1727. local loaded master_service
  1728. declare -A loaded
  1729. for service in "$@"; do
  1730. master_service=$(get_top_master_charm_for_service "$service") || return 1
  1731. if [ "${loaded[$master_service]}" ]; then
  1732. continue
  1733. fi
  1734. echo "$master_service"
  1735. loaded["$master_service"]=1
  1736. done | xargs echo
  1737. }
  1738. export -f get_master_services
  1739. _setup_state_dir() {
  1740. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1741. #debug "Creating temporary state directory in '$state_tmpdir'."
  1742. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1743. # rm -rf \"$state_tmpdir\""
  1744. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1745. }
  1746. get_docker_compose_opts_list() {
  1747. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$action"; cat "$(which docker-compose)" | md5_compat)"
  1748. if [ -e "$cache_file" ]; then
  1749. cat "$cache_file"
  1750. return 0
  1751. fi
  1752. docker_compose_help_msg=$(docker-compose "$action" --help 2>/dev/null) || return 1
  1753. echo "$docker_compose_help_msg" | grep '^Options:' -A 20000 |
  1754. tail -n +2 |
  1755. egrep "^\s+-" |
  1756. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1757. tee "$cache_file"
  1758. }
  1759. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  1760. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  1761. get_docker_compose_multi_opts_list() {
  1762. local action="$1" opts_list
  1763. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1764. echo "$opts_list" | egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1765. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  1766. tr ',' "\n" | xargs echo
  1767. }
  1768. get_docker_compose_single_opts_list() {
  1769. local action="$1" opts_list
  1770. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1771. echo "$opts_list" | egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1772. tr ',' "\n" | xargs echo
  1773. }
  1774. clean_cache() {
  1775. local i=0
  1776. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  1777. ((i++))
  1778. rm -f "$f"
  1779. done
  1780. if (( i > 0 )); then
  1781. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  1782. fi
  1783. }
  1784. [ "$SOURCED" ] && return 0
  1785. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  1786. if [ -r /etc/default/charm ]; then
  1787. . /etc/default/charm
  1788. fi
  1789. if [ -r "/etc/default/$exname" ]; then
  1790. . "/etc/default/$exname"
  1791. fi
  1792. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  1793. ## userdir ? and global /etc/compose.yml ?
  1794. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  1795. /etc/default/compose /etc/compose/local.conf; do
  1796. [ -e "$cfgfile" ] || continue
  1797. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  1798. done
  1799. fi
  1800. _setup_state_dir
  1801. mkdir -p "$CACHEDIR" || exit 1
  1802. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs echo | cut -f 2 -d " ") || {
  1803. die "Couldn't determine docker host net"
  1804. }
  1805. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  1806. die "Couldn't determine docker host ip"
  1807. }
  1808. export DOCKER_HOST_NET DOCKER_HOST_IP
  1809. ##
  1810. ## Argument parsing
  1811. ##
  1812. remainder_args=()
  1813. compose_opts=()
  1814. action_opts=()
  1815. no_hooks=
  1816. no_init=
  1817. action=
  1818. stage="main" ## switches from 'main', to 'action', 'remainder'
  1819. is_docker_compose_action=
  1820. DC_MATCH_MULTI=
  1821. DC_MATCH_SINGLE=
  1822. while [ "$#" != 0 ]; do
  1823. case "$stage" in
  1824. "main")
  1825. case "$1" in
  1826. --help|-h)
  1827. no_init=true ; no_hooks=true ; no_relations=true
  1828. print_help
  1829. exit 0
  1830. ;;
  1831. --verbose|-v)
  1832. export VERBOSE=true
  1833. ;;
  1834. --version|-V)
  1835. print_version
  1836. exit 0
  1837. ;;
  1838. -f)
  1839. [ -e "$2" ] || die "File $2 doesn't exists"
  1840. export DEFAULT_COMPOSE_FILE="$2"
  1841. shift
  1842. ;;
  1843. -p)
  1844. export DEFAULT_PROJECT_NAME="$2"
  1845. shift
  1846. ;;
  1847. --no-relations)
  1848. export no_relations=true
  1849. ;;
  1850. --no-hooks)
  1851. export no_hooks=true
  1852. ;;
  1853. --no-init)
  1854. export no_init=true
  1855. ;;
  1856. --debug)
  1857. export DEBUG=true
  1858. export VERBOSE=true
  1859. ;;
  1860. --*|-*)
  1861. compose_opts+=("$1")
  1862. ;;
  1863. *)
  1864. action="$1"
  1865. stage="action"
  1866. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  1867. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  1868. if [ "$DC_MATCH_MULTI" ]; then
  1869. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  1870. fi
  1871. is_docker_compose_action=true
  1872. ;;
  1873. esac
  1874. ;;
  1875. "action")
  1876. case "$1" in
  1877. --help|-h)
  1878. no_init=true ; no_hooks=true ; no_relations=true
  1879. action_opts+=("$1")
  1880. ;;
  1881. --*|-*)
  1882. if [ "$is_docker_compose_action" ]; then
  1883. if str_matches "$1" $DC_MATCH_MULTI; then
  1884. action_opts=("$1" "$2")
  1885. shift;
  1886. elif str_matches "$1" $DC_MATCH_SINGLE; then
  1887. action_opts=("$1")
  1888. else
  1889. err "Unknown option '$1'. Please check help."
  1890. docker-compose "$action" --help >&2
  1891. exit 1
  1892. fi
  1893. fi
  1894. ;;
  1895. *)
  1896. action_posargs+=("$1")
  1897. stage="remainder"
  1898. ;;
  1899. esac
  1900. ;;
  1901. "remainder")
  1902. remainder_args+=("$@")
  1903. break 3;;
  1904. esac
  1905. shift
  1906. done
  1907. [ "${compose_opts[*]}" ] && debug "Main docker-compose opts: ${compose_opts[*]}"
  1908. [ "${action_opts[*]}" ] && debug "Action $DARKCYAN$action$NORMAL with opts: ${action_opts[*]}"
  1909. [ "${remainder_args[*]}" ] && debug "Remainder args: ${remainder_args[*]}"
  1910. ##
  1911. ## Actual code
  1912. ##
  1913. export CHARM_STORE=${CHARM_STORE:-/srv/charm-store}
  1914. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  1915. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  1916. export COMPOSE_YML_FILE
  1917. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  1918. output=$(shyaml get-value < "$COMPOSE_YML_FILE" 2>&1)
  1919. if [ "$?" != 0 ]; then
  1920. err "Invalid YAML in '$COMPOSE_YML_FILE':"
  1921. while IFS='' read -r line1 && IFS='' read -r line2; do
  1922. echo "$line1 $GRAY($line2)$NORMAL"
  1923. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  1924. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  1925. prefix " $GRAY|$NORMAL "
  1926. exit 1
  1927. fi
  1928. if ! [ -d "$CHARM_STORE" ]; then
  1929. err "Charm store path $YELLOW$CHARM_STORE$NORMAL does not exists. "
  1930. err "Please check your $YELLOW\$CHARM_STORE$NORMAL variable value."
  1931. exit 1
  1932. fi
  1933. if [ -z "$(cd "$CHARM_STORE"; ls)" ]; then
  1934. err "no available charms in charm store $YELLOW$CHARM_STORE$NORMAL. Either:"
  1935. err " - check $YELLOW\$CHARM_STORE$NORMAL variable value"
  1936. err " - download charms in $CHARM_STORE"
  1937. print_error "Charm store is empty. Cannot continue."
  1938. fi
  1939. ##
  1940. ## Get services in command line.
  1941. ##
  1942. is_service_action=
  1943. case "$action" in
  1944. up|build|start|stop|config)
  1945. services="$(get_default_target_services "${action_posargs[@]}")" || exit 1
  1946. orig_services="${action_posargs[@]:1}"
  1947. ;;
  1948. run)
  1949. services="${action_posargs[0]}"
  1950. ;;
  1951. "")
  1952. services=
  1953. ;;
  1954. *)
  1955. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  1956. {
  1957. read-0 action_type
  1958. case "$action_type" in
  1959. "relation")
  1960. read-0 _ target_service relation_name
  1961. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  1962. ;;
  1963. "direct")
  1964. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL.$DARKCYAN$action$NORMAL"
  1965. ;;
  1966. esac
  1967. } < <(has_service_action "${action_posargs[0]}" "$action")
  1968. services="${action_posargs[0]}"
  1969. else
  1970. services="$(get_default_target_services "${action_posargs[@]}")"
  1971. fi
  1972. ;;
  1973. esac
  1974. get_docker_compose $services >/dev/null || { ## precalculate variable \$_current_docker_compose
  1975. err "Fails to compile base 'docker-compose.yml'"
  1976. exit 1
  1977. }
  1978. ##
  1979. ## Pre-action
  1980. ##
  1981. full_init=
  1982. case "$action" in
  1983. up|run)
  1984. full_init=true
  1985. ;;
  1986. "")
  1987. full_init=
  1988. ;;
  1989. *)
  1990. if [ "$is_service_action" ]; then
  1991. full_init=true
  1992. fi
  1993. ;;
  1994. esac
  1995. if [ "$full_init" ]; then
  1996. ## init in order
  1997. if [ -z "$no_init" ]; then
  1998. Section setup host resources
  1999. setup_host_resources "$services" || exit 1
  2000. Section initialisation
  2001. run_service_hook "$services" init || exit 1
  2002. fi
  2003. ## Get relations
  2004. if [ -z "$no_relations" ]; then
  2005. run_service_relations "$services" || exit 1
  2006. fi
  2007. ## XXXvlab: to be removed when all relation and service stuff is resolved
  2008. if [ -z "$no_hooks" ]; then
  2009. ordered_services=$(get_ordered_service_dependencies $services) || exit 1
  2010. for service in $ordered_services; do
  2011. charm=$(get_service_charm "$service") || exit 1
  2012. for script in "$CHARM_STORE/$charm/hooks.d/"*.sh; do
  2013. [ -e "$script" ] || continue
  2014. [ -x "$script" ] || { echo "compose: script $script is not executable." >&2; exit 1; }
  2015. (
  2016. debug "Launching '$script'."
  2017. cd "$(dirname "$script)")";
  2018. "$script" "$@"
  2019. ) || { echo "compose: hook $script failed. Stopping." >&2; exit 1; }
  2020. done
  2021. done
  2022. fi
  2023. fi
  2024. export SERVICE_PACK="$services"
  2025. ##
  2026. ## Docker-compose
  2027. ##
  2028. case "$action" in
  2029. up|start|stop|build)
  2030. master_services=$(get_master_services $SERVICE_PACK) || exit 1
  2031. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" $master_services
  2032. ;;
  2033. run)
  2034. master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2035. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2036. ;;
  2037. # enter)
  2038. # master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2039. # [ "${remainder_args[*]}" ] || remainder_args=("/bin/bash" "-c" "export TERM=xterm; exec bash")
  2040. # docker exec -ti "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2041. # ;;
  2042. config)
  2043. ## removing the services
  2044. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2045. warn "Runtime configuration modification (from relations) are not included here."
  2046. ;;
  2047. *)
  2048. if [ "$is_service_action" ]; then
  2049. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2050. else
  2051. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2052. fi
  2053. ;;
  2054. esac