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.

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