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.

2518 lines
82 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
  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. include charm
  34. depends shyaml docker
  35. version=0.1
  36. usage="$exname [COMPOSE_OPTS] [ACTION [ACTION_OPTS]]"
  37. help="\
  38. $WHITE$exname$NORMAL jobs is to run various shell scripts to build
  39. a running orchestrated and configured docker containers. These shell
  40. scripts will have the opportunity to build a 'docker-compose.yml'.
  41. Once init script and relations scripts are executed, $WHITE$exname$NORMAL
  42. delegate the launching to ${WHITE}docker-compose${NORMAL} by providing it
  43. the final 'docker-compose.yml'.
  44. $WHITE$exname$NORMAL also leverage charms to offer some additional custom
  45. actions per charm, which are simply other scripts that can be
  46. run without launching ${WHITE}docker-compose${NORMAL}.
  47. In compose message, color coding is enforced as such:
  48. - ${DARKCYAN}action$NORMAL,
  49. - ${DARKBLUE}relation$NORMAL,
  50. - ${DARKYELLOW}charm${NORMAL}/${DARKYELLOW}service${NORMAL},
  51. - ${WHITE}option-name${NORMAL}/${WHITE}command-name${NORMAL}/${WHITE}Section-Title${NORMAL}
  52. $WHITE$exname$NORMAL reads '/etc/compose.conf' for global variables, and
  53. '/etc/compose.local.conf' for local host adjustements.
  54. ${WHITE}$exname Options${NORMAL}:
  55. -h, --help Print this message and quit
  56. (ignoring any other options)
  57. -V, --version Print current version and quit
  58. (ignoring any other options)
  59. -v, --verbose Be more verbose
  60. -d, --debug Print full debugging information (sets also verbose)
  61. "
  62. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  63. export CACHEDIR=/var/cache/compose
  64. export VARDIR=/var/lib/compose
  65. md5_compat() { md5sum | cut -c -32; }
  66. quick_cat_file() { quick_cat_stdin < "$1"; }
  67. quick_cat_stdin() { local IFS=''; while read -r line; do echo "$line"; done ; }
  68. export -f quick_cat_file quick_cat_stdin md5_compat
  69. clean_cache() {
  70. local i=0
  71. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  72. ((i++))
  73. rm -f "$f"
  74. done
  75. if (( i > 0 )); then
  76. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  77. fi
  78. }
  79. trap_add "EXIT" clean_cache
  80. usage="$exname CHARM"'
  81. Deploy and manage a swarm of containers to provide services based on
  82. a ``compose.yml`` definition and charms from a ``charm-store``.
  83. '
  84. export DEFAULT_COMPOSE_FILE
  85. ##
  86. ## Merge YAML files
  87. ##
  88. export _merge_yaml_common_code="
  89. import sys
  90. import yaml
  91. try:
  92. # included in standard lib from Python 2.7
  93. from collections import OrderedDict
  94. except ImportError:
  95. # try importing the backported drop-in replacement
  96. # it's available on PyPI
  97. from ordereddict import OrderedDict
  98. ## Ensure that there are no collision with legacy OrderedDict
  99. ## that could be used for omap for instance.
  100. class MyOrderedDict(OrderedDict):
  101. pass
  102. yaml.add_representer(
  103. MyOrderedDict,
  104. lambda cls, data: cls.represent_dict(data.items()))
  105. yaml.add_constructor(
  106. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  107. lambda cls, node: MyOrderedDict(cls.construct_pairs(node)))
  108. def fc(filename):
  109. with open(filename) as f:
  110. return f.read()
  111. def merge(*args):
  112. # sys.stderr.write('%r\n' % (args, ))
  113. args = [arg for arg in args if arg is not None]
  114. if len(args) == 0:
  115. return None
  116. if len(args) == 1:
  117. return args[0]
  118. if all(isinstance(arg, (int, basestring, bool)) for arg in args):
  119. return args[-1]
  120. elif all(isinstance(arg, list) for arg in args):
  121. res = []
  122. for arg in args:
  123. for elt in arg:
  124. if elt in res:
  125. res.remove(elt)
  126. res.append(elt)
  127. return res
  128. elif all(isinstance(arg, dict) for arg in args):
  129. keys = set()
  130. for arg in args:
  131. keys |= set(arg.keys())
  132. dct = {}
  133. for key in keys:
  134. sub_args = []
  135. for arg in args:
  136. if key in arg:
  137. sub_args.append(arg)
  138. try:
  139. dct[key] = merge(*(a[key] for a in sub_args))
  140. except NotImplementedError as e:
  141. raise NotImplementedError(
  142. e.args[0],
  143. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  144. e.args[2])
  145. if dct[key] is None:
  146. del dct[key]
  147. return dct
  148. else:
  149. raise NotImplementedError(
  150. 'Unsupported types: %s'
  151. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  152. return None
  153. def merge_cli(*args):
  154. try:
  155. c = merge(*args)
  156. except NotImplementedError as e:
  157. sys.stderr.write('%s. Conflicting key is %r. Values are:\n%s\n' % (e.args[0], e.args[1], e.args[2]))
  158. exit(1)
  159. if c is not None:
  160. print '%s' % yaml.dump(c, default_flow_style=False)
  161. "
  162. merge_yaml() {
  163. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  164. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  165. $_merge_yaml_common_code
  166. merge_cli(*(yaml.load(fc(f)) for f in sys.argv[1:]))
  167. EOF
  168. fi
  169. python "$state_tmpdir/merge_yaml.py" "$@"
  170. }
  171. export -f merge_yaml
  172. merge_yaml_str() {
  173. local entries="$@"
  174. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  175. cat <<EOF > "$state_tmpdir/merge_yaml_str.py"
  176. $_merge_yaml_common_code
  177. merge_cli(*(yaml.load(f) for f in sys.argv[1:]))
  178. EOF
  179. fi
  180. python "$state_tmpdir/merge_yaml_str.py" "$@"
  181. }
  182. export -f merge_yaml_str
  183. yaml_key_val_str() {
  184. local entries="$@"
  185. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  186. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  187. $_merge_yaml_common_code
  188. print '%s' % yaml.dump({
  189. yaml.load(sys.argv[1]):
  190. yaml.load(sys.argv[2])}, default_flow_style=False)
  191. EOF
  192. fi
  193. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  194. }
  195. export -f yaml_key_val_str
  196. ##
  197. ## Docker
  198. ##
  199. docker_has_image() {
  200. local image="$1"
  201. images=$(docker images -q "$image" 2>/dev/null) || {
  202. err "docker images call has failed unexpectedly."
  203. return 1
  204. }
  205. [ "$images" ]
  206. }
  207. export -f docker_has_image
  208. cmd_on_base_image() {
  209. local charm="$1" base_image
  210. shift
  211. base_image=$(service_base_docker_image "$charm") || return 1
  212. docker run -i --entrypoint /bin/bash "$base_image" -c "$*"
  213. }
  214. export -f cmd_on_base_image
  215. cached_cmd_on_base_image() {
  216. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  217. shift
  218. if [ -e "$cache_file" ]; then
  219. # debug "$FUNCNAME: cache hit ($*)"
  220. quick_cat_stdin < "$cache_file"
  221. return 0
  222. fi
  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="$1" elt="$2"
  545. while read-0 key; do
  546. if [ "$(eval "echo -n \"\${$src[\$key]}\"")" == "$elt" ]; then
  547. return 0
  548. fi
  549. done < <(array_keys_to_stdin "$src")
  550. return 1
  551. }
  552. export -f array_member
  553. ##
  554. ## Internal Process
  555. ##
  556. get_docker_compose_links() {
  557. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  558. links charm charm_part master_charm
  559. if [ -z "$service" ]; then
  560. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  561. return 1
  562. fi
  563. if [ -e "$cache_file" ]; then
  564. # debug "$FUNCNAME: cache hit ($*)"
  565. cat "$cache_file"
  566. return 0
  567. fi
  568. master_charm=$(get_top_master_charm_for_service "$service") || return 1
  569. deps=()
  570. while read-0 relation_name target_service relation_config tech_dep; do
  571. master_target_charm="$(get_top_master_charm_for_service "$target_service")"
  572. [ "$master_charm" == "$master_target_charm" ] && continue
  573. if [ "$tech_dep" == "reversed" ]; then
  574. deps+=("$(echo -en "$master_target_charm:\n links:\n - $master_charm")")
  575. elif [ "$tech_dep" == "True" ]; then
  576. deps+=("$(echo -en "$master_charm:\n links:\n - $master_target_charm")")
  577. fi
  578. done < <(get_compose_relations "$service") || return 1
  579. merge_yaml_str "${deps[@]}" | tee "$cache_file"
  580. }
  581. _get_docker_compose_opts() {
  582. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  583. links charm charm_part master_charm
  584. if [ -z "$service" ]; then
  585. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  586. return 1
  587. fi
  588. if [ -e "$cache_file" ]; then
  589. # debug "$FUNCNAME: cache hit ($*)"
  590. cat "$cache_file"
  591. return 0
  592. fi
  593. compose_def="$(get_compose_service_def "$service")" || return 1
  594. master_charm="$(get_top_master_charm_for_service "$service")"
  595. docker_compose_opts=$(echo "$compose_def" | shyaml get-value "docker-compose" 2>/dev/null)
  596. if [ "$docker_compose_opts" ]; then
  597. yaml_key_val_str "$master_charm" "$docker_compose_opts"
  598. fi | tee "$cache_file"
  599. }
  600. ##
  601. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  602. ## Some metadata.yml (of subordinates) will indeed modify other
  603. ## services than themselves.
  604. _get_docker_compose_service_mixin() {
  605. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" links charm charm_part
  606. if [ -z "$service" ]; then
  607. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  608. return 1
  609. fi
  610. if [ -e "$cache_file" ]; then
  611. # debug "$FUNCNAME: cache hit ($*)"
  612. cat "$cache_file"
  613. return 0
  614. fi
  615. master_charm=$(get_top_master_charm_for_service "$service") || {
  616. err "Failed to get top master charm for service $DARKYELLOW$service$NORMAL"
  617. return 1
  618. }
  619. ## The compose part
  620. links_yaml=$(get_docker_compose_links "$service") || return 1
  621. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  622. ## the charm part
  623. #debug "Get charm name from service name $DARKYELLOW$service$NORMAL."
  624. charm=$(get_service_charm "$service") || return 1
  625. charm_part=$(get_docker_compose_mixin_from_metadata "$charm") || return 1
  626. ## Merge results
  627. if [ "$charm_part" ]; then
  628. charm_yaml="$(yaml_key_val_str "$master_charm" "$charm_part")" || return 1
  629. merge_yaml_str "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  630. else
  631. echo "$links_yaml"
  632. fi | tee "$cache_file"
  633. }
  634. export -f _get_docker_compose_service_mixin
  635. ##
  636. ## Get full `docker-compose.yml` format for all listed services (and
  637. ## their deps)
  638. ##
  639. ## @export
  640. ## @cache: !system !nofail +stdout
  641. get_docker_compose () {
  642. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" entries services service start
  643. if [ -e "$cache_file" ]; then
  644. # debug "$FUNCNAME: cache hit ($*)"
  645. cat "$cache_file"
  646. return 0
  647. fi
  648. ##
  649. ## Adding sub services configurations
  650. ##
  651. declare -A entries
  652. start_compilation=$SECONDS
  653. debug "Compiling 'docker-compose.yml' base for $DARKYELLOW$@$NORMAL..."
  654. for target_service in "$@"; do
  655. start=$SECONDS
  656. services=$(get_ordered_service_dependencies "$target_service") || {
  657. err "Failed to get dependencies for $DARKYELLOW$target_service$NORMAL"
  658. return 1
  659. }
  660. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" $services "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  661. for service in $services; do
  662. if [ "${entries[$service]}" ]; then
  663. ## Prevent double inclusion of same service if this
  664. ## service is deps of two or more of your
  665. ## requirements.
  666. continue
  667. fi
  668. ## mark the service as "loaded" as well as it's containers
  669. ## if this is a subordinate service
  670. start_service=$SECONDS
  671. entries[$service]=$(_get_docker_compose_service_mixin "$service") || {
  672. err "Failed to get service mixin for $DARKYELLOW$service$NORMAL"
  673. return 1
  674. }
  675. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  676. done
  677. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  678. done
  679. merge_yaml_str "${entries[@]}" > "$cache_file"
  680. export _current_docker_compose="$(cat "$cache_file")"
  681. echo "$_current_docker_compose"
  682. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  683. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  684. # debug "$_current_docker_compose"
  685. }
  686. export -f get_docker_compose
  687. _get_compose_service_def_cached () {
  688. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  689. if [ -e "$cache_file" ]; then
  690. #debug "$FUNCNAME: STATIC cache hit"
  691. cat "$cache_file"
  692. touch "$cache_file"
  693. return 0
  694. fi
  695. service_def_base="charm: $service"
  696. value=$(echo "$docker_compose" | shyaml get-value "$service" 2>/dev/null)
  697. merge_yaml <(echo "$service_def_base") <(echo "$value") | tee "$cache_file"
  698. }
  699. export -f _get_compose_service_def_cached
  700. ## XXXvlab: a lot to be done to cache the results
  701. get_compose_service_def () {
  702. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  703. result
  704. if [ -e "$cache_file" ]; then
  705. #debug "$FUNCNAME: SESSION cache hit"
  706. cat "$cache_file"
  707. return 0
  708. fi
  709. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  710. docker_compose=$(cat "$COMPOSE_YML_FILE") || return 1
  711. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  712. echo "$result" | tee "$cache_file"
  713. }
  714. export -f get_compose_service_def
  715. _get_service_charm_cached () {
  716. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  717. if [ -e "$cache_file" ]; then
  718. # debug "$FUNCNAME: cache hit $1"
  719. cat "$cache_file"
  720. touch "$cache_file"
  721. return 0
  722. fi
  723. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  724. if [ -z "$charm" ]; then
  725. err "Missing charm in service $DARKYELLOW$service$NORMAL definition."
  726. return 1
  727. fi
  728. echo "$charm" | tee "$cache_file"
  729. }
  730. export -f _get_service_charm_cached
  731. get_service_charm () {
  732. local service="$1"
  733. if [ -z "$service" ]; then
  734. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  735. return 1
  736. fi
  737. service_def=$(get_compose_service_def "$service") || return 1
  738. _get_service_charm_cached "$service" "$service_def"
  739. }
  740. export -f get_service_charm
  741. ## built above the docker-compose abstraction, so it relies on the
  742. ## full docker-compose.yml to be already built.
  743. get_service_def () {
  744. local service="$1" def
  745. if [ -z "$_current_docker_compose" ]; then
  746. print_syntax_error "$FUNCNAME is meant to be called after"\
  747. "\$_current_docker_compose has been calculated."
  748. fi
  749. def=$(echo "$_current_docker_compose" | shyaml get-value "$service" 2>/dev/null)
  750. if [ -z "$def" ]; then
  751. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  752. return 1
  753. fi
  754. echo "$def"
  755. }
  756. export -f get_service_def
  757. ## Return the base docker image name of a service
  758. service_base_docker_image() {
  759. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  760. master_charm charm service_image service_build service_dockerfile
  761. if [ -e "$cache_file" ]; then
  762. # debug "$FUNCNAME: cache hit ($*)"
  763. cat "$cache_file"
  764. return 0
  765. fi
  766. master_charm="$(get_top_master_charm_for_service "$service")" || {
  767. err "Could not compute base charm for service $DARKYELLOW$service$NORMAL."
  768. return 1
  769. }
  770. service_def="$(get_service_def "$master_charm")" || {
  771. err "Could not get docker-compose service definition for $DARKYELLOW$master_charm$NORMAL."
  772. return 1
  773. }
  774. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  775. if [ "$?" != 0 ]; then
  776. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  777. if [ "$?" != 0 ]; then
  778. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  779. echo "$service_def" >&2
  780. return 1
  781. fi
  782. service_dockerfile="$(charm.get_dir "${service_build%%/*}")"/"${service_build#*/}"/Dockerfile
  783. if ! [ -e "$service_dockerfile" ]; then
  784. err "No Dockerfile found in '$service_dockerfile' location."
  785. return 1
  786. fi
  787. grep '^FROM' "$service_dockerfile" | xargs echo | cut -f 2 -d " "
  788. else
  789. echo "$service_image"
  790. fi | tee "$cache_file"
  791. }
  792. export -f service_base_docker_image
  793. get_charm_relation_def () {
  794. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  795. relation_def metadata
  796. if [ -e "$cache_file" ]; then
  797. # debug "$FUNCNAME: cache hit ($*)"
  798. cat "$cache_file"
  799. return 0
  800. fi
  801. metadata="$(charm.metadata "$charm")" || return 1
  802. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  803. echo "$relation_def" | tee "$cache_file"
  804. }
  805. export -f get_charm_relation_def
  806. get_charm_tech_dep_orientation_for_relation() {
  807. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  808. relation_def metadata value
  809. if [ -e "$cache_file" ]; then
  810. # debug "$FUNCNAME: cache hit ($*)"
  811. cat "$cache_file"
  812. return 0
  813. fi
  814. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  815. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  816. value=${value:-True}
  817. echo "$value" | tee "$cache_file"
  818. }
  819. export -f get_charm_tech_dep_orientation_for_relation
  820. ##
  821. ## Use compose file to get deps, and relation definition in metadata.yml
  822. ## for tech-dep attribute.
  823. get_service_deps() {
  824. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  825. if [ -e "$cache_file" ]; then
  826. # debug "$FUNCNAME: cache hit ($*)"
  827. cat "$cache_file"
  828. return 0
  829. fi
  830. (
  831. set -o pipefail
  832. get_compose_relations "$service" | \
  833. while read-0 relation_name target_service _relation_config tech_dep; do
  834. echo "$target_service"
  835. done | tee "$cache_file"
  836. ) || return 1
  837. }
  838. export -f get_service_deps
  839. _rec_get_depth() {
  840. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  841. [ "${depths[$elt]}" ] && return 0
  842. if [ -e "$cache_file" ]; then
  843. # debug "$FUNCNAME: cache hit ($*)"
  844. depths[$elt]=$(cat "$cache_file")
  845. return 0
  846. fi
  847. visited[$elt]=1
  848. #debug "Setting visited[$elt]"
  849. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  850. deps=$(get_service_deps "$elt") || {
  851. debug "Failed get_service_deps $elt"
  852. return 1
  853. }
  854. # debug "$elt deps are:" $deps
  855. max=0
  856. for dep in $deps; do
  857. [ "${visited[$dep]}" ] && {
  858. #debug "Already computing $dep"
  859. continue
  860. }
  861. _rec_get_depth "$dep" || return 1
  862. #debug "Requesting depth[$dep]"
  863. if (( ${depths[$dep]} > max )); then
  864. max="${depths[$dep]}"
  865. fi
  866. done
  867. # debug "Setting depth[$elt] to $((max + 1))"
  868. depths[$elt]=$((max + 1))
  869. echo "${depths[$elt]}" > $cache_file
  870. }
  871. export -f _rec_get_depth
  872. get_ordered_service_dependencies() {
  873. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  874. if [ -e "$cache_file" ]; then
  875. # debug "$FUNCNAME: cache hit ($*)"
  876. cat "$cache_file"
  877. return 0
  878. fi
  879. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  880. if [ -z "${services[*]}" ]; then
  881. print_syntax_error "$FUNCNAME: no arguments"
  882. return 1
  883. fi
  884. declare -A depths
  885. declare -A visited
  886. heads=("${services[@]}")
  887. while [ "${#heads[@]}" != 0 ]; do
  888. array_pop heads head
  889. _rec_get_depth "$head" || return 1
  890. done
  891. i=0
  892. while [ "${#depths[@]}" != 0 ]; do
  893. for key in "${!depths[@]}"; do
  894. value="${depths[$key]}"
  895. if [ "$value" == "$i" ]; then
  896. echo "$key"
  897. unset depths[$key]
  898. fi
  899. done
  900. i=$((i + 1))
  901. done | tee "$cache_file"
  902. }
  903. export -f get_ordered_service_dependencies
  904. run_service_hook () {
  905. local services="$1" action="$2" loaded
  906. declare -A loaded
  907. for service in $services; do
  908. for subservice in $(get_ordered_service_dependencies "$service"); do
  909. if [ "${loaded[$subservice]}" ]; then
  910. ## Prevent double inclusion of same service if this
  911. ## service is deps of two or more of your
  912. ## requirements.
  913. continue
  914. fi
  915. charm=$(get_service_charm "$subservice") || return 1
  916. charm.has_hook "$charm" "$action" >/dev/null || continue
  917. PROJECT_NAME=$(get_default_project_name) || return 1
  918. Wrap -d "$YELLOW$action$NORMAL hook of charm $DARKYELLOW$charm$NORMAL" <<EOF || return 1
  919. export SERVICE_NAME=$subservice
  920. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  921. export CONTAINER_NAME=\${IMAGE_NAME}_1
  922. export CHARM_NAME="$charm"
  923. export PROJECT_NAME=$PROJECT_NAME
  924. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$charm")
  925. export SERVICE_DATASTORE="$DATASTORE/$charm"
  926. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm"
  927. charm.run_hook "$charm" "$action"
  928. EOF
  929. loaded[$subservice]=1
  930. done
  931. done
  932. return 0
  933. }
  934. host_resource_get() {
  935. local location="$1" cfg="$2"
  936. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  937. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  938. return 1
  939. }
  940. if fn.exists host_resource_get_$type; then
  941. host_resource_get_$type "$location" "$cfg"
  942. else
  943. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  944. "${WHITE}host-resource$NORMAL '$location' defined in" \
  945. "$DARKYELLOW$subservice$NORMAL config."
  946. return 1
  947. fi
  948. }
  949. export -f host_resource_get
  950. host_resource_get_git() {
  951. local location="$1" cfg="$2" branch parent url
  952. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  953. branch=${branch:-master}
  954. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  955. parent="$(dirname "$location")"
  956. (
  957. mkdir -p "$parent" && cd "$parent" &&
  958. git clone -b "$branch" "$url" "$(basename "$location")"
  959. ) || return 1
  960. }
  961. export -f host_resource_get_git
  962. host_resource_get_git-sub() {
  963. local location="$1" cfg="$2" branch parent url
  964. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  965. branch=${branch:-master}
  966. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  967. parent="$(dirname "$location")"
  968. (
  969. mkdir -p "$parent" && cd "$parent" &&
  970. git sub clone -b "$branch" "$url" "$(basename "$location")"
  971. ) || return 1
  972. }
  973. export -f host_resource_get_git-sub
  974. setup_host_resource () {
  975. local service="$1" service_def location get cfg
  976. service_def=$(get_compose_service_def "$subservice") || return 1
  977. while read-0 location cfg; do
  978. ## XXXvlab: will it be a git resources always ?
  979. if [ -d "$location" -a ! -d "$location/.git" ]; then
  980. err "Hum, location '$location' does not seem to be a git directory."
  981. return 1
  982. fi
  983. if [ -d "$location" ]; then
  984. info "host resource '$location' already set up."
  985. continue
  986. fi
  987. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  988. if [ -z "$get" ]; then
  989. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  990. "specified for $DARKYELLOW$subservice$NORMAL."
  991. return 1
  992. fi
  993. host_resource_get "$location" "$get" || return 1
  994. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  995. }
  996. export -f setup_host_resource
  997. setup_host_resources () {
  998. local services="$1" loaded
  999. declare -A loaded
  1000. for service in $services; do
  1001. for subservice in $(get_ordered_service_dependencies "$service"); do
  1002. if [ "${loaded[$subservice]}" ]; then
  1003. ## Prevent double inclusion of same service if this
  1004. ## service is deps of two or more of your
  1005. ## requirements.
  1006. continue
  1007. fi
  1008. setup_host_resource "$service"
  1009. loaded[$subservice]=1
  1010. done
  1011. done
  1012. return 0
  1013. }
  1014. export -f setup_host_resources
  1015. relation-get () {
  1016. local key="$1"
  1017. cat "$RELATION_DATA_FILE" | shyaml get-value "$key" 2>/dev/null
  1018. if [ "$?" != 0 ]; then
  1019. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1020. return 1
  1021. fi
  1022. }
  1023. export -f relation-get
  1024. relation-base-compose-get () {
  1025. local key="$1"
  1026. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1027. if [ "$?" != 0 ]; then
  1028. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1029. return 1
  1030. fi
  1031. }
  1032. export -f relation-base-compose-get
  1033. relation-target-compose-get () {
  1034. local key="$1"
  1035. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1036. if [ "$?" != 0 ]; then
  1037. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1038. return 1
  1039. fi
  1040. }
  1041. export -f relation-target-compose-get
  1042. relation-set () {
  1043. local key="$1" value="$2"
  1044. if [ -z "$RELATION_DATA_FILE" ]; then
  1045. err "$FUNCNAME: relation does not seems to be correctly setup."
  1046. return 1
  1047. fi
  1048. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1049. err "$FUNCNAME: can't read relation's data." >&2
  1050. return 1
  1051. fi
  1052. _config_merge "$RELATION_DATA_FILE" <(echo "$key: $value")
  1053. }
  1054. export -f relation-set
  1055. _config_merge() {
  1056. local config_filename="$1" merge_to_file="$2"
  1057. touch "$config_filename" &&
  1058. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  1059. mv "$config_filename.tmp" "$config_filename"
  1060. }
  1061. export -f _config_merge
  1062. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1063. config-add() {
  1064. local metadata="$1"
  1065. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1066. }
  1067. export -f config-add
  1068. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1069. init-config-add() {
  1070. local metadata="$1"
  1071. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" <(echo "$metadata")
  1072. }
  1073. export -f init-config-add
  1074. logstdout() {
  1075. local name="$1"
  1076. sed -r 's%^%'"${name}"'> %g'
  1077. }
  1078. export -f logstdout
  1079. logstderr() {
  1080. local name="$1"
  1081. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1082. }
  1083. export -f logstderr
  1084. _run_service_relation () {
  1085. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1086. charm=$(get_service_charm "$service") || return 1
  1087. target_charm=$(get_service_charm "$target_service") || return 1
  1088. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1089. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1090. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1091. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  1092. RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config") || return 1
  1093. export BASE_CHARM_NAME=$charm
  1094. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1095. export TARGET_CHARM_NAME=$target_charm
  1096. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1097. export RELATION_DATA_FILE
  1098. target_errlvl=0
  1099. if [ -z "$target_script_name" ]; then
  1100. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKYELLOW$target_charm$NORMAL."
  1101. else
  1102. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1103. "for target charm $DARKYELLOW$target_charm$NORMAL"
  1104. RELATION_CONFIG="$relation_dir/config_provider"
  1105. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1106. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1107. {
  1108. (
  1109. SERVICE_NAME=$target_service
  1110. SERVICE_DATASTORE="$DATASTORE/$target_charm"
  1111. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_charm"
  1112. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1113. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1114. echo "$?" > "$relation_dir/target_errlvl"
  1115. ) | logstdout "$DARKYELLOW$target_charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1116. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1117. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1118. err "Relation script '$script_name' in $DARKYELLOW$target_charm$NORMAL" \
  1119. "failed before outputing an errorlevel."
  1120. ((target_errlvl |= "1" ))
  1121. }
  1122. if [ -e "$RELATION_CONFIG" ]; then
  1123. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1124. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1125. rm "$RELATION_CONFIG"
  1126. ((target_errlvl |= "$?"))
  1127. fi
  1128. fi
  1129. if [ "$target_errlvl" == 0 ]; then
  1130. errlvl=0
  1131. if [ "$base_script_name" ]; then
  1132. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1133. "for charm $DARKYELLOW$charm$NORMAL"
  1134. RELATION_CONFIG="$relation_dir/config_providee"
  1135. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1136. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1137. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1138. {
  1139. (
  1140. SERVICE_NAME=$service
  1141. SERVICE_DATASTORE="$DATASTORE/$charm"
  1142. SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm"
  1143. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1144. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1145. echo "$?" > "$relation_dir/errlvl"
  1146. ) | logstdout "$DARKYELLOW$charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1147. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1148. errlvl="$(cat "$relation_dir/errlvl")" || {
  1149. err "Relation script '$script_name' in $DARKYELLOW$charm$NORMAL" \
  1150. "failed before outputing an errorlevel."
  1151. ((errlvl |= "1" ))
  1152. }
  1153. if [ -e "$RELATION_CONFIG" ]; then
  1154. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1155. rm "$RELATION_CONFIG"
  1156. ((errlvl |= "$?" ))
  1157. fi
  1158. if [ "$errlvl" != 0 ]; then
  1159. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$charm$NORMAL failed to run properly."
  1160. fi
  1161. else
  1162. verb "No relation script '$script_name' in charm $DARKYELLOW$charm$NORMAL. Ignoring."
  1163. fi
  1164. else
  1165. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_charm$NORMAL failed to run properly."
  1166. fi
  1167. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1168. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1169. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1170. return 0
  1171. else
  1172. return 1
  1173. fi
  1174. }
  1175. export -f _run_service_relation
  1176. _get_compose_relations_cached () {
  1177. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1178. relation_name relation_def target_service
  1179. if [ -e "$cache_file" ]; then
  1180. #debug "$FUNCNAME: STATIC cache hit $1"
  1181. cat "$cache_file"
  1182. touch "$cache_file"
  1183. return 0
  1184. fi
  1185. (
  1186. set -o pipefail
  1187. if [ "$compose_service_def" ]; then
  1188. while read-0 relation_name relation_def; do
  1189. (
  1190. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1191. "str")
  1192. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)"
  1193. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1194. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1195. ;;
  1196. "sequence")
  1197. while read-0 target_service; do
  1198. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1199. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1200. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1201. ;;
  1202. "struct")
  1203. while read-0 target_service relation_config; do
  1204. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_service" "$relation_name")"
  1205. echo -en "$relation_name\0$target_service\0$relation_config\0$tech_dep\0"
  1206. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1207. ;;
  1208. esac
  1209. ) </dev/null >> "$cache_file"
  1210. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1211. fi
  1212. )
  1213. if [ "$?" != 0 ]; then
  1214. err "Error while looking for compose relations."
  1215. rm -f "$cache_file" ## no cache
  1216. return 1
  1217. fi
  1218. [ -e "$cache_file" ] && cat "$cache_file"
  1219. return 0
  1220. }
  1221. export -f _get_compose_relations_cached
  1222. get_compose_relations () {
  1223. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1224. compose_def
  1225. if [ -e "$cache_file" ]; then
  1226. #debug "$FUNCNAME: SESSION cache hit $1"
  1227. cat "$cache_file"
  1228. return 0
  1229. fi
  1230. compose_def="$(get_compose_service_def "$service")" || return 1
  1231. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1232. if [ "$?" != 0 ]; then
  1233. err "Error while looking for compose relations."
  1234. rm -f "$cache_file" ## no cache
  1235. return 1
  1236. fi
  1237. cat "$cache_file"
  1238. }
  1239. export -f get_compose_relations
  1240. run_service_relations () {
  1241. local services="$1" loaded
  1242. PROJECT_NAME=$(get_default_project_name) || return 1
  1243. export PROJECT_NAME
  1244. declare -A loaded
  1245. for service in $(get_ordered_service_dependencies $services); do
  1246. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  1247. for subservice in $(get_service_deps "$service") "$service"; do
  1248. [ "${loaded[$subservice]}" ] && continue
  1249. export BASE_SERVICE_NAME=$service
  1250. MASTER_BASE_CHARM_NAME=$(get_top_master_charm_for_service "$subservice") || return 1
  1251. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  1252. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_CHARM_NAME
  1253. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  1254. while read-0 relation_name target_service relation_config tech_dep; do
  1255. export relation_config
  1256. export TARGET_SERVICE_NAME=$target_service
  1257. MASTER_TARGET_CHARM_NAME=$(get_top_master_charm_for_service "$target_service") || return 1
  1258. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  1259. export MASTER_TARGET_CHARM_NAME RELATION_TARGET_COMPOSE_DEF
  1260. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  1261. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  1262. EOF
  1263. done < <(get_compose_relations "$subservice") || return 1
  1264. loaded[$subservice]=1
  1265. done
  1266. done
  1267. }
  1268. export -f run_service_relations
  1269. _run_service_action_direct() {
  1270. local service="$1" action="$2" charm _dummy
  1271. shift; shift
  1272. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  1273. if read-0 _dummy || [ "$_dummy" ]; then
  1274. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1275. return 1
  1276. fi
  1277. compose_file=$(get_compose_yml_location) || return 1
  1278. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1279. export state_tmpdir
  1280. {
  1281. (
  1282. set +e ## Prevents unwanted leaks from parent shell
  1283. export COMPOSE_CONFIG=$(cat "$compose_file")
  1284. export METADATA_CONFIG=$(charm.metadata "$charm")
  1285. export SERVICE_NAME=$service
  1286. export ACTION_NAME=$action
  1287. export CONTAINER_NAME=$(get_top_master_charm_for_service "$service")
  1288. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1289. export SERVICE_DATASTORE="$DATASTORE/$service"
  1290. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1291. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1292. stdbuf -oL -eL charm.run_direct_action "$charm" "$action" "$@"
  1293. echo "$?" > "$action_errlvl_file"
  1294. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1295. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1296. if ! [ -e "$action_errlvl_file" ]; then
  1297. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1298. "to output an errlvl"
  1299. return 1
  1300. fi
  1301. return "$(cat "$action_errlvl_file")"
  1302. }
  1303. export -f _run_service_action_direct
  1304. _run_service_action_relation() {
  1305. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  1306. shift; shift
  1307. read-0 charm target_charm relation_name relation_config || true
  1308. if read-0 _dummy || [ "$_dummy" ]; then
  1309. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1310. return 1
  1311. fi
  1312. export RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config")
  1313. compose_file=$(get_compose_yml_location) || return 1
  1314. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1315. export state_tmpdir
  1316. {
  1317. (
  1318. set +e ## Prevents unwanted leaks from parent shell
  1319. export METADATA_CONFIG=$(charm.metadata "$charm")
  1320. export SERVICE_NAME=$service
  1321. export RELATION_TARGET_CHARM="$target_charm"
  1322. export RELATION_BASE_CHARM="$charm"
  1323. export ACTION_NAME=$action
  1324. export CONTAINER_NAME=$(get_top_master_charm_for_service "$service")
  1325. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1326. export SERVICE_DATASTORE="$DATASTORE/$service"
  1327. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1328. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1329. stdbuf -oL -eL charm.run_relation_action "$charm" "$relation_name" "$action" "$@"
  1330. echo "$?" > "$action_errlvl_file"
  1331. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1332. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1333. if ! [ -e "$action_errlvl_file" ]; then
  1334. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1335. "to output an errlvl"
  1336. return 1
  1337. fi
  1338. return "$(cat "$action_errlvl_file")"
  1339. }
  1340. export -f _run_service_action_relation
  1341. get_relation_data_dir() {
  1342. local charm="$1" target_charm="$2" relation_name="$3" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1343. if [ -e "$cache_file" ]; then
  1344. # debug "$FUNCNAME: cache hit ($*)"
  1345. cat "$cache_file"
  1346. return 0
  1347. fi
  1348. project=$(get_default_project_name) || return 1
  1349. relation_dir="$VARDIR/relations/$project/$charm-$target_charm/$relation_name"
  1350. if ! [ -d "$relation_dir" ]; then
  1351. mkdir -p "$relation_dir" || return 1
  1352. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  1353. fi
  1354. echo "$relation_dir" || tee "$cache_file"
  1355. }
  1356. export -f get_relation_data_dir
  1357. get_relation_data_file() {
  1358. local charm="$1" target_charm="$2" relation_name="$3" relation_config="$4"
  1359. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  1360. relation_data_file="$relation_dir/data"
  1361. new=
  1362. if [ -e "$relation_data_file" ]; then
  1363. ## Has reference changed ?
  1364. new_md5=$(echo "$relation_config" | md5_compat)
  1365. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  1366. new=true
  1367. fi
  1368. else
  1369. new=true
  1370. fi
  1371. if [ "$new" ]; then
  1372. echo "$relation_config" > "$relation_data_file"
  1373. chmod go-rwx "$relation_data_file" ## protecting this file
  1374. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  1375. fi
  1376. echo "$relation_data_file"
  1377. }
  1378. export -f get_relation_data_file
  1379. has_service_action () {
  1380. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1381. charm target_charm
  1382. if [ -e "$cache_file" ]; then
  1383. # debug "$FUNCNAME: cache hit ($*)"
  1384. cat "$cache_file"
  1385. return 0
  1386. fi
  1387. charm=$(get_service_charm "$service") || return 1
  1388. ## Action directly provided ?
  1389. if charm.has_direct_action "$charm" "$action"; then
  1390. echo -en "direct\0$charm" | tee "$cache_file"
  1391. return 0
  1392. fi
  1393. ## Action provided by relation ?
  1394. while read-0 relation_name target_service relation_config tech_dep; do
  1395. target_charm=$(get_service_charm "$target_service") || return 1
  1396. if charm.has_relation_action "$target_charm" "$relation_name" "$action"; then
  1397. echo -en "relation\0$charm\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  1398. return 0
  1399. fi
  1400. done < <(get_compose_relations "$service")
  1401. return 1
  1402. # master=$(get_top_master_charm_for_service "$charm")
  1403. # [ "$master" == "$charm" ] && return 1
  1404. # has_service_action "$master" "$action"
  1405. }
  1406. export -f has_service_action
  1407. run_service_action () {
  1408. local service="$1" action="$2"
  1409. shift ; shift
  1410. {
  1411. if ! read-0 action_type; then
  1412. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  1413. info " Add an executable script to 'actions/$action' to implement action."
  1414. return 1
  1415. fi
  1416. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  1417. "_run_service_action_${action_type}" "$service" "$action" "$@"
  1418. } < <(has_service_action "$service" "$action")
  1419. }
  1420. export -f run_service_action
  1421. get_compose_relation_config() {
  1422. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1423. if [ -e "$cache_file" ]; then
  1424. # debug "$FUNCNAME: cache hit ($*)"
  1425. cat "$cache_file"
  1426. return 0
  1427. fi
  1428. compose_service_def=$(get_compose_service_def "$service") || return 1
  1429. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  1430. }
  1431. export -f get_compose_relation_config
  1432. # ## Return key-values-0
  1433. # get_compose_relation_config_for_service() {
  1434. # local service=$1 relation_name=$2 relation_config
  1435. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  1436. # if ! relation_config=$(
  1437. # echo "$compose_service_relations" |
  1438. # shyaml get-value "${relation_name}" 2>/dev/null); then
  1439. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  1440. # "relation config in compose configuration."
  1441. # return 1
  1442. # fi
  1443. # if [ -z "$relation_config" ]; then
  1444. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  1445. # return 1
  1446. # fi
  1447. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  1448. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  1449. # return 1
  1450. # fi
  1451. # }
  1452. # export -f get_compose_relation_config_for_service
  1453. _get_master_charm_for_service_cached () {
  1454. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1455. charm requires master_charm target_charm target_service service_def
  1456. if [ -e "$cache_file" ]; then
  1457. # debug "$FUNCNAME: STATIC cache hit ($1)"
  1458. cat "$cache_file"
  1459. touch "$cache_file"
  1460. return 0
  1461. fi
  1462. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  1463. ## just return charm name
  1464. echo "$charm" | tee "$cache_file"
  1465. return 0
  1466. fi
  1467. ## fetch the container relation
  1468. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1469. if [ -z "$requires" ]; then
  1470. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any 'requires' " \
  1471. "section."
  1472. fi
  1473. master_charm=
  1474. while read-0 relation_name relation; do
  1475. if [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ]; then
  1476. # debug "$DARKYELLOW$service$NORMAL's relation" \
  1477. # "$DARKBLUE${relation_name}$NORMAL is a container."
  1478. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1479. if [ -z "$interface" ]; then
  1480. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1481. return 1
  1482. fi
  1483. ## Action provided by relation ?
  1484. target_service=
  1485. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  1486. [ "$interface" == "$relation_name" ] && {
  1487. target_service="$candidate_target_service"
  1488. break
  1489. }
  1490. done < <(get_compose_relations "$service")
  1491. if [ -z "$target_service" ]; then
  1492. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1493. "${DARKYELLOW}$service$NORMAL compose definition."
  1494. return 1
  1495. fi
  1496. master_charm=$(get_service_charm "$target_service") || return 1
  1497. break
  1498. fi
  1499. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1500. if [ -z "$master_charm" ]; then
  1501. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any relation with" \
  1502. " ${WHITE}scope${NORMAL} set to 'container'."
  1503. fi
  1504. echo "$master_charm" | tee "$cache_file"
  1505. }
  1506. export -f _get_master_charm_for_service_cached
  1507. get_master_charm_for_service() {
  1508. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1509. charm metadata result
  1510. if [ -e "$cache_file" ]; then
  1511. # debug "$FUNCNAME: SESSION cache hit ($*)"
  1512. cat "$cache_file"
  1513. return 0
  1514. fi
  1515. charm=$(get_service_charm "$service") || return 1
  1516. metadata=$(charm.metadata "$charm") || {
  1517. err "Failed to access metadata of charm $DARKYELLOW$charm$NORMAL"
  1518. return 1
  1519. }
  1520. result=$(_get_master_charm_for_service_cached "$service" "$charm" "$metadata") || return 1
  1521. echo "$result" | tee "$cache_file"
  1522. }
  1523. export -f get_master_charm_for_service
  1524. get_top_master_charm_for_service() {
  1525. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1526. current_service
  1527. if [ -e "$cache_file" ]; then
  1528. # debug "$FUNCNAME: cache hit ($*)"
  1529. cat "$cache_file"
  1530. return 0
  1531. fi
  1532. current_service="$service"
  1533. while true; do
  1534. master_service=$(get_master_charm_for_service "$current_service") || return 1
  1535. [ "$master_service" == "$current_service" ] && break
  1536. current_service="$master_service"
  1537. done
  1538. echo "$current_service" | tee "$cache_file"
  1539. return 0
  1540. }
  1541. export -f get_top_master_charm_for_service
  1542. ##
  1543. ## The result is a mixin that is not always a complete valid
  1544. ## docker-compose entry (thinking of subordinates). The result
  1545. ## will be merge with master charms.
  1546. _get_docker_compose_mixin_from_metadata_cached() {
  1547. local charm="$1" metadata="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1548. metadata_file metadata volumes docker_compose subordinate image
  1549. if [ -e "$cache_file" ]; then
  1550. #debug "$FUNCNAME: STATIC cache hit $1"
  1551. cat "$cache_file"
  1552. touch "$cache_file"
  1553. return 0
  1554. fi
  1555. mixin=
  1556. if [ "$metadata" ]; then
  1557. ## resources to volumes
  1558. volumes=$(
  1559. for resource_type in data config; do
  1560. while read-0 resource; do
  1561. eval "echo \" - \$${resource_type^^}STORE/\$charm\$resource:\$resource:rw\""
  1562. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1563. done
  1564. while read-0 resource; do
  1565. if [[ "$resource" == *:* ]]; then
  1566. echo " - $resource:rw"
  1567. else
  1568. echo " - $resource:$resource:rw"
  1569. fi
  1570. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1571. while read-0 resource; do
  1572. dest="$(charm.get_dir "$charm")/resources$resource"
  1573. if ! [ -e "$dest" ]; then
  1574. die "charm-resource: '$resource' does not exist (file: '$dest')."
  1575. fi
  1576. echo " - $dest:$resource:rw"
  1577. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1578. ) || return 1
  1579. if [ "$volumes" ]; then
  1580. mixin=$(echo -en "volumes:\n$volumes")
  1581. fi
  1582. docker_compose=$(echo "$metadata" | shyaml get-value "docker-compose" 2>/dev/null)
  1583. if [ "$docker_compose" ]; then
  1584. mixin=$(merge_yaml_str "$mixin" "$docker_compose")
  1585. fi
  1586. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1587. subordinate=true
  1588. fi
  1589. fi
  1590. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1591. image_or_build_statement=
  1592. if [ "$image" ]; then
  1593. if [ "$subordinate" ]; then
  1594. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1595. return 1
  1596. fi
  1597. image_or_build_statement="image: $image"
  1598. elif [ -d "$(charm.get_dir "$charm")/build" ]; then
  1599. if [ "$subordinate" ]; then
  1600. err "Subordinate charm can not have a 'build' sub directory."
  1601. return 1
  1602. fi
  1603. image_or_build_statement="build: $charm/build"
  1604. fi
  1605. if [ "$image_or_build_statement" ]; then
  1606. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1607. fi
  1608. echo "$mixin" | tee "$cache_file"
  1609. }
  1610. export -f _get_docker_compose_mixin_from_metadata_cached
  1611. get_docker_compose_mixin_from_metadata() {
  1612. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1613. if [ -e "$cache_file" ]; then
  1614. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1615. cat "$cache_file"
  1616. return 0
  1617. fi
  1618. metadata="$(charm.metadata "$charm")" || return 1
  1619. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$charm" "$metadata") || return 1
  1620. echo "$mixin" | tee "$cache_file"
  1621. }
  1622. export -f get_docker_compose_mixin_from_metadata
  1623. _save() {
  1624. local name="$1"
  1625. cat - | tee -a "$docker_compose_dir/.data/$name"
  1626. }
  1627. export -f _save
  1628. get_default_project_name() {
  1629. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1630. echo "$DEFAULT_PROJECT_NAME"
  1631. return 0
  1632. fi
  1633. compose_yml_location="$(get_compose_yml_location)" || return 1
  1634. if [ "$compose_yml_location" ]; then
  1635. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1636. echo "$(basename "$(dirname "$normalized_path")")"
  1637. return 0
  1638. fi
  1639. fi
  1640. echo "project"
  1641. return 0
  1642. }
  1643. export -f get_default_project_name
  1644. launch_docker_compose() {
  1645. local charm
  1646. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1647. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1648. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1649. # rm -rf \"$docker_compose_tmpdir\""
  1650. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1651. project=$(get_default_project_name)
  1652. mkdir -p "$docker_compose_tmpdir/$project"
  1653. docker_compose_dir="$docker_compose_tmpdir/$project"
  1654. if [ -z "$SERVICE_PACK" ]; then
  1655. export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1656. fi
  1657. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1658. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1659. # debug "Merging some config data in docker-compose.yml:"
  1660. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1661. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1662. fi
  1663. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  1664. die "Generated 'docker-compose.yml' is unexpectedly empty."
  1665. fi
  1666. ## XXXvlab: could be more specific and only link the needed charms
  1667. for charm in $(shyaml keys < "$docker_compose_dir/docker-compose.yml"); do
  1668. if charm.exists "$charm"; then
  1669. ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  1670. fi
  1671. done
  1672. mkdir "$docker_compose_dir/.data"
  1673. {
  1674. {
  1675. cd "$docker_compose_dir"
  1676. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  1677. debug "$(cat "$docker_compose_dir/docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  1678. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1679. docker-compose "$@"
  1680. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1681. } | _save stdout
  1682. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1683. 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
  1684. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1685. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1686. fi
  1687. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  1688. if [ -z "$docker_compose_errlvl" ]; then
  1689. err "Something went wrong before you could gather docker-compose errorlevel."
  1690. return 1
  1691. fi
  1692. return "$docker_compose_errlvl"
  1693. }
  1694. export -f launch_docker_compose
  1695. get_compose_yml_location() {
  1696. parent=$(while ! [ -e "./compose.yml" ]; do
  1697. [ "$PWD" == "/" ] && exit 0
  1698. cd ..
  1699. done; echo "$PWD"
  1700. )
  1701. if [ "$parent" ]; then
  1702. echo "$parent/compose.yml"
  1703. return 0
  1704. fi
  1705. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1706. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1707. err "No 'compose.yml' was found in current or parent dirs," \
  1708. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file."
  1709. die "Please provide a 'compose.yml' file."
  1710. fi
  1711. echo "$DEFAULT_COMPOSE_FILE"
  1712. return 0
  1713. fi
  1714. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1715. die "Please provide a 'compose.yml' file."
  1716. return 1
  1717. }
  1718. export -f get_compose_yml_location
  1719. get_default_target_services() {
  1720. local services=("$@")
  1721. if [ -z "${services[*]}" ]; then
  1722. if [ "$DEFAULT_SERVICES" ]; then
  1723. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1724. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1725. services="$DEFAULT_SERVICES"
  1726. else
  1727. err "No service provided."
  1728. return 1
  1729. fi
  1730. fi
  1731. echo "${services[*]}"
  1732. }
  1733. export -f get_default_target_services
  1734. get_master_services() {
  1735. local loaded master_service
  1736. declare -A loaded
  1737. for service in "$@"; do
  1738. master_service=$(get_top_master_charm_for_service "$service") || return 1
  1739. if [ "${loaded[$master_service]}" ]; then
  1740. continue
  1741. fi
  1742. echo "$master_service"
  1743. loaded["$master_service"]=1
  1744. done | xargs echo
  1745. }
  1746. export -f get_master_services
  1747. _setup_state_dir() {
  1748. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1749. #debug "Creating temporary state directory in '$state_tmpdir'."
  1750. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1751. # rm -rf \"$state_tmpdir\""
  1752. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1753. }
  1754. get_docker_compose_opts_list() {
  1755. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$action"; cat "$(which docker-compose)" | md5_compat)"
  1756. if [ -e "$cache_file" ]; then
  1757. cat "$cache_file"
  1758. return 0
  1759. fi
  1760. docker_compose_help_msg=$(docker-compose "$action" --help 2>/dev/null) || return 1
  1761. echo "$docker_compose_help_msg" | grep '^Options:' -A 20000 |
  1762. tail -n +2 |
  1763. egrep "^\s+-" |
  1764. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1765. tee "$cache_file"
  1766. }
  1767. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  1768. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  1769. get_docker_compose_multi_opts_list() {
  1770. local action="$1" opts_list
  1771. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1772. echo "$opts_list" | egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1773. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  1774. tr ',' "\n" | xargs echo
  1775. }
  1776. get_docker_compose_single_opts_list() {
  1777. local action="$1" opts_list
  1778. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1779. echo "$opts_list" | egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1780. tr ',' "\n" | xargs echo
  1781. }
  1782. _graph_service() {
  1783. local service="$1" base="$1"
  1784. charm=$(get_service_charm "$service") || return 1
  1785. metadata=$(charm.metadata "$charm") || return 1
  1786. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  1787. if [ "$subordinate" == "True" ]; then
  1788. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1789. master_charm=
  1790. while read-0 relation_name relation; do
  1791. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  1792. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1793. if [ -z "$interface" ]; then
  1794. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1795. return 1
  1796. fi
  1797. ## Action provided by relation ?
  1798. target_service=
  1799. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  1800. [ "$interface" == "$relation_name" ] && {
  1801. target_service="$candidate_target_service"
  1802. break
  1803. }
  1804. done < <(get_compose_relations "$service")
  1805. if [ -z "$target_service" ]; then
  1806. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1807. "${DARKYELLOW}$service$NORMAL compose definition."
  1808. return 1
  1809. fi
  1810. master_service="$target_service"
  1811. master_charm=$(get_service_charm "$target_service") || return 1
  1812. break
  1813. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1814. fi
  1815. _graph_node_service "$service" "$base" "$charm"
  1816. _graph_edge_service "$service" "$subordinate" "$master_service"
  1817. }
  1818. _graph_node_service() {
  1819. local service="$1" base="$2" charm="$3"
  1820. cat <<EOF
  1821. "$(_graph_node_service_label ${service})" [
  1822. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  1823. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  1824. color = $([ "$base" ] && echo "blue" || echo "black")
  1825. fillcolor = "white"
  1826. fontname = "Courier New"
  1827. shape = "Mrecord"
  1828. label =<$(_graph_node_service_content "$service")>
  1829. ];
  1830. EOF
  1831. }
  1832. _graph_edge_service() {
  1833. local service="$1" subordinate="$2" master_service="$3"
  1834. while read-0 relation_name target_service relation_config tech_dep; do
  1835. cat <<EOF
  1836. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  1837. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  1838. fontsize = 16
  1839. fontcolor = "black"
  1840. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  1841. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  1842. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  1843. arrowtail = odot
  1844. # arrowhead = dotlicurve
  1845. taillabel = "$relation_name" ];
  1846. EOF
  1847. done < <(get_compose_relations "$service") || return 1
  1848. }
  1849. _graph_node_service_label() {
  1850. local service="$1"
  1851. echo "service_$service"
  1852. }
  1853. _graph_node_service_content() {
  1854. local service="$1"
  1855. charm=$(get_service_charm "$service") || return 1
  1856. cat <<EOF
  1857. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  1858. <tr>
  1859. <td bgcolor="black" align="center" colspan="2">
  1860. <font color="white">$service</font>
  1861. </td>
  1862. </tr>
  1863. $(if [ "$charm" != "$service" ]; then
  1864. cat <<EOF2
  1865. <tr>
  1866. <td align="left" port="r0">charm: $charm</td>
  1867. </tr>
  1868. EOF2
  1869. fi)
  1870. </table>
  1871. EOF
  1872. }
  1873. cla_contains () {
  1874. local e
  1875. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  1876. return 1
  1877. }
  1878. graph() {
  1879. local services=("$@")
  1880. declare -A entries
  1881. cat <<EOF
  1882. digraph g {
  1883. graph [
  1884. fontsize=30
  1885. labelloc="t"
  1886. label=""
  1887. splines=true
  1888. overlap=false
  1889. #rankdir = "LR"
  1890. ];
  1891. ratio = auto;
  1892. EOF
  1893. for target_service in "$@"; do
  1894. services=$(get_ordered_service_dependencies "$target_service")
  1895. for service in $services; do
  1896. [ "${entries[$service]}" ] && continue || entries[$service]=1
  1897. if cla_contains "$service" "${services[@]}"; then
  1898. base=true
  1899. else
  1900. base=
  1901. fi
  1902. _graph_service "$service" "$base"
  1903. done
  1904. done
  1905. echo "}"
  1906. }
  1907. [ "$SOURCED" ] && return 0
  1908. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  1909. if [ -r /etc/default/charm ]; then
  1910. . /etc/default/charm
  1911. fi
  1912. if [ -r "/etc/default/$exname" ]; then
  1913. . "/etc/default/$exname"
  1914. fi
  1915. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  1916. ## userdir ? and global /etc/compose.yml ?
  1917. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  1918. /etc/default/compose /etc/compose/local.conf; do
  1919. [ -e "$cfgfile" ] || continue
  1920. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  1921. done
  1922. fi
  1923. _setup_state_dir
  1924. mkdir -p "$CACHEDIR" || exit 1
  1925. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs echo | cut -f 2 -d " ") || {
  1926. die "Couldn't determine docker host net"
  1927. }
  1928. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  1929. die "Couldn't determine docker host ip"
  1930. }
  1931. export DOCKER_HOST_NET DOCKER_HOST_IP
  1932. ##
  1933. ## Argument parsing
  1934. ##
  1935. remainder_args=()
  1936. compose_opts=()
  1937. action_opts=()
  1938. no_hooks=
  1939. no_init=
  1940. action=
  1941. stage="main" ## switches from 'main', to 'action', 'remainder'
  1942. is_docker_compose_action=
  1943. DC_MATCH_MULTI=
  1944. DC_MATCH_SINGLE=
  1945. while [ "$#" != 0 ]; do
  1946. case "$stage" in
  1947. "main")
  1948. case "$1" in
  1949. --help|-h)
  1950. no_init=true ; no_hooks=true ; no_relations=true
  1951. print_help
  1952. exit 0
  1953. ;;
  1954. --verbose|-v)
  1955. export VERBOSE=true
  1956. ;;
  1957. --version|-V)
  1958. print_version
  1959. exit 0
  1960. ;;
  1961. -f)
  1962. [ -e "$2" ] || die "File $2 doesn't exists"
  1963. export DEFAULT_COMPOSE_FILE="$2"
  1964. shift
  1965. ;;
  1966. -p)
  1967. export DEFAULT_PROJECT_NAME="$2"
  1968. shift
  1969. ;;
  1970. --no-relations)
  1971. export no_relations=true
  1972. ;;
  1973. --no-hooks)
  1974. export no_hooks=true
  1975. ;;
  1976. --no-init)
  1977. export no_init=true
  1978. ;;
  1979. --debug)
  1980. export DEBUG=true
  1981. export VERBOSE=true
  1982. ;;
  1983. --*|-*)
  1984. compose_opts+=("$1")
  1985. ;;
  1986. *)
  1987. action="$1"
  1988. stage="action"
  1989. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  1990. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  1991. if [ "$DC_MATCH_MULTI" ]; then
  1992. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  1993. fi
  1994. is_docker_compose_action=true
  1995. ;;
  1996. esac
  1997. ;;
  1998. "action")
  1999. case "$1" in
  2000. --help|-h)
  2001. no_init=true ; no_hooks=true ; no_relations=true
  2002. action_opts+=("$1")
  2003. ;;
  2004. --*|-*)
  2005. if [ "$is_docker_compose_action" ]; then
  2006. if str_matches "$1" $DC_MATCH_MULTI; then
  2007. action_opts=("$1" "$2")
  2008. shift;
  2009. elif str_matches "$1" $DC_MATCH_SINGLE; then
  2010. action_opts=("$1")
  2011. else
  2012. err "Unknown option '$1'. Please check help."
  2013. docker-compose "$action" --help >&2
  2014. exit 1
  2015. fi
  2016. fi
  2017. ;;
  2018. *)
  2019. action_posargs+=("$1")
  2020. stage="remainder"
  2021. ;;
  2022. esac
  2023. ;;
  2024. "remainder")
  2025. remainder_args+=("$@")
  2026. break 3;;
  2027. esac
  2028. shift
  2029. done
  2030. [ "${compose_opts[*]}" ] && debug "Main docker-compose opts: ${compose_opts[*]}"
  2031. [ "${action_opts[*]}" ] && debug "Action $DARKCYAN$action$NORMAL with opts: ${action_opts[*]}"
  2032. [ "${remainder_args[*]}" ] && debug "Remainder args: ${remainder_args[*]}"
  2033. ##
  2034. ## Actual code
  2035. ##
  2036. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  2037. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2038. export COMPOSE_YML_FILE
  2039. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2040. output=$(shyaml get-value < "$COMPOSE_YML_FILE" 2>&1)
  2041. if [ "$?" != 0 ]; then
  2042. err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2043. while IFS='' read -r line1 && IFS='' read -r line2; do
  2044. echo "$line1 $GRAY($line2)$NORMAL"
  2045. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2046. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2047. prefix " $GRAY|$NORMAL "
  2048. exit 1
  2049. fi
  2050. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  2051. ##
  2052. ## Get services in command line.
  2053. ##
  2054. is_service_action=
  2055. case "$action" in
  2056. up|build|start|stop|config|graph)
  2057. services="$(get_default_target_services "${action_posargs[@]}")" || exit 1
  2058. orig_services="${action_posargs[@]:1}"
  2059. ;;
  2060. run)
  2061. services="${action_posargs[0]}"
  2062. ;;
  2063. "")
  2064. services=
  2065. ;;
  2066. *)
  2067. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  2068. {
  2069. read-0 action_type
  2070. case "$action_type" in
  2071. "relation")
  2072. read-0 _ target_service relation_name
  2073. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  2074. ;;
  2075. "direct")
  2076. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL.$DARKCYAN$action$NORMAL"
  2077. ;;
  2078. esac
  2079. } < <(has_service_action "${action_posargs[0]}" "$action")
  2080. services="${action_posargs[0]}"
  2081. else
  2082. services="$(get_default_target_services "${action_posargs[@]}")"
  2083. fi
  2084. ;;
  2085. esac
  2086. get_docker_compose $services >/dev/null || { ## precalculate variable \$_current_docker_compose
  2087. err "Fails to compile base 'docker-compose.yml'"
  2088. exit 1
  2089. }
  2090. ##
  2091. ## Pre-action
  2092. ##
  2093. full_init=
  2094. case "$action" in
  2095. up|run)
  2096. full_init=true
  2097. ;;
  2098. "")
  2099. full_init=
  2100. ;;
  2101. *)
  2102. if [ "$is_service_action" ]; then
  2103. full_init=true
  2104. fi
  2105. ;;
  2106. esac
  2107. if [ "$full_init" ]; then
  2108. ## init in order
  2109. if [ -z "$no_init" ]; then
  2110. Section setup host resources
  2111. setup_host_resources "$services" || exit 1
  2112. Section initialisation
  2113. run_service_hook "$services" init || exit 1
  2114. fi
  2115. ## Get relations
  2116. if [ -z "$no_relations" ]; then
  2117. run_service_relations "$services" || exit 1
  2118. fi
  2119. fi
  2120. export SERVICE_PACK="$services"
  2121. ##
  2122. ## Docker-compose
  2123. ##
  2124. case "$action" in
  2125. up|start|stop|build)
  2126. master_services=$(get_master_services $SERVICE_PACK) || exit 1
  2127. if [[ "$action" == "up" ]] && ! array_member action_opts -d; then ## force daemon mode for up
  2128. action_opts=("-d" "${action_opts[@]}")
  2129. fi
  2130. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" $master_services
  2131. ;;
  2132. run)
  2133. master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2134. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2135. ;;
  2136. # enter)
  2137. # master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2138. # [ "${remainder_args[*]}" ] || remainder_args=("/bin/bash" "-c" "export TERM=xterm; exec bash")
  2139. # docker exec -ti "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2140. # ;;
  2141. graph)
  2142. graph $SERVICE_PACK
  2143. ;;
  2144. config)
  2145. ## removing the services
  2146. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2147. warn "Runtime configuration modification (from relations) are not included here."
  2148. ;;
  2149. *)
  2150. if [ "$is_service_action" ]; then
  2151. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2152. else
  2153. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2154. fi
  2155. ;;
  2156. esac