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.

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