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
86 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. ## 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. master_charm=
  1528. while read-0 relation_name relation; do
  1529. if [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ]; then
  1530. # debug "$DARKYELLOW$service$NORMAL's relation" \
  1531. # "$DARKBLUE${relation_name}$NORMAL is a container."
  1532. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1533. if [ -z "$interface" ]; then
  1534. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1535. return 1
  1536. fi
  1537. ## Action provided by relation ?
  1538. target_service=
  1539. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  1540. [ "$interface" == "$relation_name" ] && {
  1541. target_service="$candidate_target_service"
  1542. break
  1543. }
  1544. done < <(get_compose_relations "$service")
  1545. if [ -z "$target_service" ]; then
  1546. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1547. "${DARKYELLOW}$service$NORMAL compose definition."
  1548. return 1
  1549. fi
  1550. master_charm=$(get_service_charm "$target_service") || return 1
  1551. break
  1552. fi
  1553. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1554. if [ -z "$master_charm" ]; then
  1555. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any relation with" \
  1556. " ${WHITE}scope${NORMAL} set to 'container'."
  1557. fi
  1558. echo "$master_charm" | tee "$cache_file"
  1559. }
  1560. export -f _get_master_charm_for_service_cached
  1561. get_master_charm_for_service() {
  1562. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1563. charm metadata result
  1564. if [ -e "$cache_file" ]; then
  1565. # debug "$FUNCNAME: SESSION cache hit ($*)"
  1566. cat "$cache_file"
  1567. return 0
  1568. fi
  1569. charm=$(get_service_charm "$service") || return 1
  1570. metadata=$(charm.metadata "$charm") || {
  1571. err "Failed to access metadata of charm $DARKYELLOW$charm$NORMAL"
  1572. return 1
  1573. }
  1574. result=$(_get_master_charm_for_service_cached "$service" "$charm" "$metadata") || return 1
  1575. echo "$result" | tee "$cache_file"
  1576. }
  1577. export -f get_master_charm_for_service
  1578. get_top_master_charm_for_service() {
  1579. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1580. current_service
  1581. if [ -e "$cache_file" ]; then
  1582. # debug "$FUNCNAME: cache hit ($*)"
  1583. cat "$cache_file"
  1584. return 0
  1585. fi
  1586. current_service="$service"
  1587. while true; do
  1588. master_service=$(get_master_charm_for_service "$current_service") || return 1
  1589. [ "$master_service" == "$current_service" ] && break
  1590. current_service="$master_service"
  1591. done
  1592. echo "$current_service" | tee "$cache_file"
  1593. return 0
  1594. }
  1595. export -f get_top_master_charm_for_service
  1596. ##
  1597. ## The result is a mixin that is not always a complete valid
  1598. ## docker-compose entry (thinking of subordinates). The result
  1599. ## will be merge with master charms.
  1600. _get_docker_compose_mixin_from_metadata_cached() {
  1601. local charm="$1" metadata="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1602. metadata_file metadata volumes docker_compose subordinate image
  1603. if [ -e "$cache_file" ]; then
  1604. #debug "$FUNCNAME: STATIC cache hit $1"
  1605. cat "$cache_file"
  1606. touch "$cache_file"
  1607. return 0
  1608. fi
  1609. mixin=$(echo -en "labels:\n - \"compose.charm=$charm\"")
  1610. if [ "$metadata" ]; then
  1611. ## resources to volumes
  1612. volumes=$(
  1613. for resource_type in data config; do
  1614. while read-0 resource; do
  1615. eval "echo \" - \$${resource_type^^}STORE/\$charm\$resource:\$resource:rw\""
  1616. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1617. done
  1618. while read-0 resource; do
  1619. if [[ "$resource" == *:* ]]; then
  1620. echo " - $resource:rw"
  1621. else
  1622. echo " - $resource:$resource:rw"
  1623. fi
  1624. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1625. while read-0 resource; do
  1626. dest="$(charm.get_dir "$charm")/resources$resource"
  1627. if ! [ -e "$dest" ]; then
  1628. die "charm-resource: '$resource' does not exist (file: '$dest')."
  1629. fi
  1630. echo " - $dest:$resource:rw"
  1631. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1632. ) || return 1
  1633. if [ "$volumes" ]; then
  1634. mixin=$(merge_yaml_str "$mixin" "$(echo -en "volumes:\n$volumes")") || {
  1635. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1636. "from charm ${DARKYELLOW}$charm$NORMAL."
  1637. return 1
  1638. }
  1639. fi
  1640. docker_compose=$(echo "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null)
  1641. if [ "$docker_compose" ]; then
  1642. mixin=$(merge_yaml_str "$mixin" "$docker_compose") || {
  1643. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1644. "from charm ${DARKYELLOW}$charm$NORMAL."
  1645. return 1
  1646. }
  1647. fi
  1648. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1649. subordinate=true
  1650. fi
  1651. fi
  1652. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1653. image_or_build_statement=
  1654. if [ "$image" ]; then
  1655. if [ "$subordinate" ]; then
  1656. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1657. return 1
  1658. fi
  1659. image_or_build_statement="image: $image"
  1660. elif [ -d "$(charm.get_dir "$charm")/build" ]; then
  1661. if [ "$subordinate" ]; then
  1662. err "Subordinate charm can not have a 'build' sub directory."
  1663. return 1
  1664. fi
  1665. image_or_build_statement="build: $charm/build"
  1666. fi
  1667. if [ "$image_or_build_statement" ]; then
  1668. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1669. fi
  1670. echo "$mixin" | tee "$cache_file"
  1671. }
  1672. export -f _get_docker_compose_mixin_from_metadata_cached
  1673. get_docker_compose_mixin_from_metadata() {
  1674. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1675. if [ -e "$cache_file" ]; then
  1676. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1677. cat "$cache_file"
  1678. return 0
  1679. fi
  1680. metadata="$(charm.metadata "$charm")" || return 1
  1681. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$charm" "$metadata") || return 1
  1682. echo "$mixin" | tee "$cache_file"
  1683. }
  1684. export -f get_docker_compose_mixin_from_metadata
  1685. _save() {
  1686. local name="$1"
  1687. cat - | tee -a "$docker_compose_dir/.data/$name"
  1688. }
  1689. export -f _save
  1690. get_default_project_name() {
  1691. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1692. echo "$DEFAULT_PROJECT_NAME"
  1693. return 0
  1694. fi
  1695. compose_yml_location="$(get_compose_yml_location)" || return 1
  1696. if [ "$compose_yml_location" ]; then
  1697. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1698. echo "$(basename "$(dirname "$normalized_path")")"
  1699. return 0
  1700. fi
  1701. fi
  1702. echo "project"
  1703. return 0
  1704. }
  1705. export -f get_default_project_name
  1706. launch_docker_compose() {
  1707. local charm
  1708. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1709. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1710. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1711. # rm -rf \"$docker_compose_tmpdir\""
  1712. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1713. project=$(get_default_project_name)
  1714. mkdir -p "$docker_compose_tmpdir/$project"
  1715. docker_compose_dir="$docker_compose_tmpdir/$project"
  1716. if [ -z "$SERVICE_PACK" ]; then
  1717. export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1718. fi
  1719. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1720. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1721. # debug "Merging some config data in docker-compose.yml:"
  1722. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1723. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1724. fi
  1725. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  1726. die "Generated 'docker-compose.yml' is unexpectedly empty."
  1727. fi
  1728. ## XXXvlab: could be more specific and only link the needed charms
  1729. for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  1730. if charm.exists "$charm"; then
  1731. ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  1732. fi
  1733. done
  1734. mkdir "$docker_compose_dir/.data"
  1735. {
  1736. {
  1737. cd "$docker_compose_dir"
  1738. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  1739. debug "$(cat "$docker_compose_dir/docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  1740. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1741. docker-compose "$@"
  1742. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1743. } | _save stdout
  1744. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1745. 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
  1746. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1747. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1748. fi
  1749. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  1750. if [ -z "$docker_compose_errlvl" ]; then
  1751. err "Something went wrong before you could gather docker-compose errorlevel."
  1752. return 1
  1753. fi
  1754. return "$docker_compose_errlvl"
  1755. }
  1756. export -f launch_docker_compose
  1757. get_compose_yml_location() {
  1758. parent=$(while ! [ -e "./compose.yml" ]; do
  1759. [ "$PWD" == "/" ] && exit 0
  1760. cd ..
  1761. done; echo "$PWD"
  1762. )
  1763. if [ "$parent" ]; then
  1764. echo "$parent/compose.yml"
  1765. return 0
  1766. fi
  1767. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1768. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1769. err "No 'compose.yml' was found in current or parent dirs," \
  1770. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file."
  1771. die "Please provide a 'compose.yml' file."
  1772. fi
  1773. echo "$DEFAULT_COMPOSE_FILE"
  1774. return 0
  1775. fi
  1776. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1777. die "Please provide a 'compose.yml' file."
  1778. return 1
  1779. }
  1780. export -f get_compose_yml_location
  1781. get_default_target_services() {
  1782. local services=("$@")
  1783. if [ -z "${services[*]}" ]; then
  1784. if [ "$DEFAULT_SERVICES" ]; then
  1785. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1786. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1787. services="$DEFAULT_SERVICES"
  1788. else
  1789. err "No service provided."
  1790. return 1
  1791. fi
  1792. fi
  1793. echo "${services[*]}"
  1794. }
  1795. export -f get_default_target_services
  1796. get_master_services() {
  1797. local loaded master_service
  1798. declare -A loaded
  1799. for service in "$@"; do
  1800. master_service=$(get_top_master_charm_for_service "$service") || return 1
  1801. if [ "${loaded[$master_service]}" ]; then
  1802. continue
  1803. fi
  1804. echo "$master_service"
  1805. loaded["$master_service"]=1
  1806. done | xargs echo
  1807. }
  1808. export -f get_master_services
  1809. _setup_state_dir() {
  1810. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1811. #debug "Creating temporary state directory in '$state_tmpdir'."
  1812. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1813. # rm -rf \"$state_tmpdir\""
  1814. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1815. }
  1816. get_docker_compose_opts_list() {
  1817. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$action"; cat "$(which docker-compose)" | md5_compat)"
  1818. if [ -e "$cache_file" ]; then
  1819. cat "$cache_file"
  1820. return 0
  1821. fi
  1822. docker_compose_help_msg=$(docker-compose "$action" --help 2>/dev/null) || return 1
  1823. echo "$docker_compose_help_msg" | grep '^Options:' -A 20000 |
  1824. tail -n +2 |
  1825. egrep "^\s+-" |
  1826. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1827. tee "$cache_file"
  1828. }
  1829. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  1830. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  1831. get_docker_compose_multi_opts_list() {
  1832. local action="$1" opts_list
  1833. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1834. echo "$opts_list" | egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1835. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  1836. tr ',' "\n" | xargs echo
  1837. }
  1838. get_docker_compose_single_opts_list() {
  1839. local action="$1" opts_list
  1840. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  1841. echo "$opts_list" | egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1842. tr ',' "\n" | xargs echo
  1843. }
  1844. _graph_service() {
  1845. local service="$1" base="$1"
  1846. charm=$(get_service_charm "$service") || return 1
  1847. metadata=$(charm.metadata "$charm") || return 1
  1848. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  1849. if [ "$subordinate" == "True" ]; then
  1850. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1851. master_charm=
  1852. while read-0 relation_name relation; do
  1853. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  1854. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1855. if [ -z "$interface" ]; then
  1856. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1857. return 1
  1858. fi
  1859. ## Action provided by relation ?
  1860. target_service=
  1861. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  1862. [ "$interface" == "$relation_name" ] && {
  1863. target_service="$candidate_target_service"
  1864. break
  1865. }
  1866. done < <(get_compose_relations "$service")
  1867. if [ -z "$target_service" ]; then
  1868. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1869. "${DARKYELLOW}$service$NORMAL compose definition."
  1870. return 1
  1871. fi
  1872. master_service="$target_service"
  1873. master_charm=$(get_service_charm "$target_service") || return 1
  1874. break
  1875. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1876. fi
  1877. _graph_node_service "$service" "$base" "$charm"
  1878. _graph_edge_service "$service" "$subordinate" "$master_service"
  1879. }
  1880. _graph_node_service() {
  1881. local service="$1" base="$2" charm="$3"
  1882. cat <<EOF
  1883. "$(_graph_node_service_label ${service})" [
  1884. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  1885. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  1886. color = $([ "$base" ] && echo "blue" || echo "black")
  1887. fillcolor = "white"
  1888. fontname = "Courier New"
  1889. shape = "Mrecord"
  1890. label =<$(_graph_node_service_content "$service")>
  1891. ];
  1892. EOF
  1893. }
  1894. _graph_edge_service() {
  1895. local service="$1" subordinate="$2" master_service="$3"
  1896. while read-0 relation_name target_service relation_config tech_dep; do
  1897. cat <<EOF
  1898. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  1899. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  1900. fontsize = 16
  1901. fontcolor = "black"
  1902. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  1903. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  1904. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  1905. arrowtail = odot
  1906. # arrowhead = dotlicurve
  1907. taillabel = "$relation_name" ];
  1908. EOF
  1909. done < <(get_compose_relations "$service") || return 1
  1910. }
  1911. _graph_node_service_label() {
  1912. local service="$1"
  1913. echo "service_$service"
  1914. }
  1915. _graph_node_service_content() {
  1916. local service="$1"
  1917. charm=$(get_service_charm "$service") || return 1
  1918. cat <<EOF
  1919. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  1920. <tr>
  1921. <td bgcolor="black" align="center" colspan="2">
  1922. <font color="white">$service</font>
  1923. </td>
  1924. </tr>
  1925. $(if [ "$charm" != "$service" ]; then
  1926. cat <<EOF2
  1927. <tr>
  1928. <td align="left" port="r0">charm: $charm</td>
  1929. </tr>
  1930. EOF2
  1931. fi)
  1932. </table>
  1933. EOF
  1934. }
  1935. cla_contains () {
  1936. local e
  1937. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  1938. return 1
  1939. }
  1940. graph() {
  1941. local services=("$@")
  1942. declare -A entries
  1943. cat <<EOF
  1944. digraph g {
  1945. graph [
  1946. fontsize=30
  1947. labelloc="t"
  1948. label=""
  1949. splines=true
  1950. overlap=false
  1951. #rankdir = "LR"
  1952. ];
  1953. ratio = auto;
  1954. EOF
  1955. for target_service in "$@"; do
  1956. services=$(get_ordered_service_dependencies "$target_service")
  1957. for service in $services; do
  1958. [ "${entries[$service]}" ] && continue || entries[$service]=1
  1959. if cla_contains "$service" "${services[@]}"; then
  1960. base=true
  1961. else
  1962. base=
  1963. fi
  1964. _graph_service "$service" "$base"
  1965. done
  1966. done
  1967. echo "}"
  1968. }
  1969. [ "$SOURCED" ] && return 0
  1970. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  1971. if [ -r /etc/default/charm ]; then
  1972. . /etc/default/charm
  1973. fi
  1974. if [ -r "/etc/default/$exname" ]; then
  1975. . "/etc/default/$exname"
  1976. fi
  1977. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  1978. ## userdir ? and global /etc/compose.yml ?
  1979. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  1980. /etc/default/compose /etc/compose/local.conf; do
  1981. [ -e "$cfgfile" ] || continue
  1982. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  1983. done
  1984. fi
  1985. _setup_state_dir
  1986. mkdir -p "$CACHEDIR" || exit 1
  1987. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs echo | cut -f 2 -d " ") || {
  1988. die "Couldn't determine docker host net"
  1989. }
  1990. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  1991. die "Couldn't determine docker host ip"
  1992. }
  1993. export DOCKER_HOST_NET DOCKER_HOST_IP
  1994. ##
  1995. ## Argument parsing
  1996. ##
  1997. remainder_args=()
  1998. compose_opts=()
  1999. action_opts=()
  2000. no_hooks=
  2001. no_init=
  2002. action=
  2003. stage="main" ## switches from 'main', to 'action', 'remainder'
  2004. is_docker_compose_action=
  2005. DC_MATCH_MULTI=
  2006. DC_MATCH_SINGLE=
  2007. while [ "$#" != 0 ]; do
  2008. case "$stage" in
  2009. "main")
  2010. case "$1" in
  2011. --help|-h)
  2012. no_init=true ; no_hooks=true ; no_relations=true
  2013. print_help
  2014. exit 0
  2015. ;;
  2016. --verbose|-v)
  2017. export VERBOSE=true
  2018. ;;
  2019. --version|-V)
  2020. print_version
  2021. exit 0
  2022. ;;
  2023. -f)
  2024. [ -e "$2" ] || die "File $2 doesn't exists"
  2025. export DEFAULT_COMPOSE_FILE="$2"
  2026. shift
  2027. ;;
  2028. -p)
  2029. export DEFAULT_PROJECT_NAME="$2"
  2030. shift
  2031. ;;
  2032. --no-relations)
  2033. export no_relations=true
  2034. ;;
  2035. --no-hooks)
  2036. export no_hooks=true
  2037. ;;
  2038. --no-init)
  2039. export no_init=true
  2040. ;;
  2041. --debug)
  2042. export DEBUG=true
  2043. export VERBOSE=true
  2044. ;;
  2045. --*|-*)
  2046. compose_opts+=("$1")
  2047. ;;
  2048. *)
  2049. action="$1"
  2050. stage="action"
  2051. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  2052. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  2053. if [ "$DC_MATCH_MULTI" ]; then
  2054. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  2055. fi
  2056. is_docker_compose_action=true
  2057. ;;
  2058. esac
  2059. ;;
  2060. "action")
  2061. case "$1" in
  2062. --help|-h)
  2063. no_init=true ; no_hooks=true ; no_relations=true
  2064. action_opts+=("$1")
  2065. ;;
  2066. --*|-*)
  2067. if [ "$is_docker_compose_action" ]; then
  2068. if str_matches "$1" $DC_MATCH_MULTI; then
  2069. action_opts=("$1" "$2")
  2070. shift;
  2071. elif str_matches "$1" $DC_MATCH_SINGLE; then
  2072. action_opts=("$1")
  2073. else
  2074. err "Unknown option '$1'. Please check help."
  2075. docker-compose "$action" --help >&2
  2076. exit 1
  2077. fi
  2078. fi
  2079. ;;
  2080. *)
  2081. action_posargs+=("$1")
  2082. stage="remainder"
  2083. ;;
  2084. esac
  2085. ;;
  2086. "remainder")
  2087. remainder_args+=("$@")
  2088. break 3;;
  2089. esac
  2090. shift
  2091. done
  2092. [ "${compose_opts[*]}" ] && debug "Main docker-compose opts: ${compose_opts[*]}"
  2093. [ "${action_opts[*]}" ] && debug "Action $DARKCYAN$action$NORMAL with opts: ${action_opts[*]}"
  2094. [ "${remainder_args[*]}" ] && debug "Remainder args: ${remainder_args[*]}"
  2095. ##
  2096. ## Actual code
  2097. ##
  2098. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  2099. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2100. export COMPOSE_YML_FILE
  2101. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2102. output=$(shyaml get-value < "$COMPOSE_YML_FILE" 2>&1)
  2103. if [ "$?" != 0 ]; then
  2104. outputed_something=
  2105. while IFS='' read -r line1 && IFS='' read -r line2; do
  2106. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2107. outputed_something=true
  2108. echo "$line1 $GRAY($line2)$NORMAL"
  2109. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2110. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2111. prefix " $GRAY|$NORMAL "
  2112. [ "$outputed_something" ] || {
  2113. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2114. echo "$output" | prefix " $GRAY|$NORMAL "
  2115. }
  2116. exit 1
  2117. fi
  2118. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  2119. ##
  2120. ## Get services in command line.
  2121. ##
  2122. is_service_action=
  2123. case "$action" in
  2124. up|build|start|stop|config|graph)
  2125. services="$(get_default_target_services "${action_posargs[@]}" "${remainder_args[@]}")" || exit 1
  2126. orig_services="${action_posargs[@]:1}"
  2127. ;;
  2128. run)
  2129. services="${action_posargs[0]}"
  2130. ;;
  2131. "")
  2132. services=
  2133. ;;
  2134. *)
  2135. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  2136. {
  2137. read-0 action_type
  2138. case "$action_type" in
  2139. "relation")
  2140. read-0 _ target_service relation_name
  2141. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  2142. ;;
  2143. "direct")
  2144. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL.$DARKCYAN$action$NORMAL"
  2145. ;;
  2146. esac
  2147. } < <(has_service_action "${action_posargs[0]}" "$action")
  2148. services="${action_posargs[0]}"
  2149. else
  2150. services="$(get_default_target_services "${action_posargs[@]}")"
  2151. fi
  2152. ;;
  2153. esac
  2154. get_docker_compose $services >/dev/null || { ## precalculate variable \$_current_docker_compose
  2155. err "Fails to compile base 'docker-compose.yml'"
  2156. exit 1
  2157. }
  2158. ##
  2159. ## Pre-action
  2160. ##
  2161. full_init=
  2162. case "$action" in
  2163. up|run)
  2164. full_init=true
  2165. post_hook=true
  2166. ;;
  2167. "")
  2168. full_init=
  2169. ;;
  2170. *)
  2171. if [ "$is_service_action" ]; then
  2172. full_init=true
  2173. fi
  2174. ;;
  2175. esac
  2176. if [ "$full_init" ]; then
  2177. ## init in order
  2178. if [ -z "$no_init" ]; then
  2179. Section setup host resources
  2180. setup_host_resources "$services" || exit 1
  2181. Section initialisation
  2182. run_service_hook "$services" init || exit 1
  2183. fi
  2184. ## Get relations
  2185. if [ -z "$no_relations" ]; then
  2186. run_service_relations "$services" || exit 1
  2187. fi
  2188. fi
  2189. export SERVICE_PACK="$services"
  2190. ##
  2191. ## Docker-compose
  2192. ##
  2193. case "$action" in
  2194. up|start|stop|build)
  2195. master_services=$(get_master_services $SERVICE_PACK) || exit 1
  2196. if [[ "$action" == "up" ]] && ! array_member action_opts -d; then ## force daemon mode for up
  2197. action_opts=("-d" "${action_opts[@]}")
  2198. fi
  2199. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" $master_services
  2200. ;;
  2201. run)
  2202. master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2203. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2204. ;;
  2205. # enter)
  2206. # master_service=$(get_master_services $SERVICE_PACK) || exit 1
  2207. # [ "${remainder_args[*]}" ] || remainder_args=("/bin/bash" "-c" "export TERM=xterm; exec bash")
  2208. # docker exec -ti "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  2209. # ;;
  2210. graph)
  2211. graph $SERVICE_PACK
  2212. ;;
  2213. config)
  2214. ## removing the services
  2215. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2216. warn "Runtime configuration modification (from relations) are not included here."
  2217. ;;
  2218. *)
  2219. if [ "$is_service_action" ]; then
  2220. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2221. else
  2222. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2223. fi
  2224. ;;
  2225. esac
  2226. if [ "$post_hook" ]; then
  2227. run_service_hook "$services" post_deploy || exit 1
  2228. fi