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.

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