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.

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