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.

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