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.

2523 lines
82 KiB

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