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.

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