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.

2556 lines
83 KiB

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