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.

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