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.

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