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.

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