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.

2305 lines
75 KiB

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