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.

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