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.

1789 lines
58 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
  1. #!/bin/bash
  2. #:-
  3. . /etc/shlib
  4. #:-
  5. include pretty
  6. include parse
  7. depends shyaml docker
  8. [[ "${BASH_SOURCE[0]}" != "${0}" ]] && SOURCED=true
  9. export VARDIR=/var/lib/compose
  10. usage="$exname CHARM"'
  11. Deploy and manage a swarm of containers to provide services based on
  12. a ``compose.yml`` definition and charms from a ``charm-store``.
  13. '
  14. export DEFAULT_COMPOSE_FILE
  15. ##
  16. ## Merge YAML files
  17. ##
  18. _merge_yaml_common_code="
  19. import sys
  20. import yaml
  21. try:
  22. # included in standard lib from Python 2.7
  23. from collections import OrderedDict
  24. except ImportError:
  25. # try importing the backported drop-in replacement
  26. # it's available on PyPI
  27. from ordereddict import OrderedDict
  28. ## Ensure that there are no collision with legacy OrderedDict
  29. ## that could be used for omap for instance.
  30. class MyOrderedDict(OrderedDict):
  31. pass
  32. yaml.add_representer(
  33. MyOrderedDict,
  34. lambda cls, data: cls.represent_dict(data.items()))
  35. yaml.add_constructor(
  36. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  37. lambda cls, node: MyOrderedDict(cls.construct_pairs(node)))
  38. def fc(filename):
  39. with open(filename) as f:
  40. return f.read()
  41. def merge(*args):
  42. # sys.stderr.write('%r\n' % (args, ))
  43. args = [arg for arg in args if arg is not None]
  44. if len(args) == 0:
  45. return None
  46. if len(args) == 1:
  47. return args[0]
  48. if all(isinstance(arg, (int, basestring, bool)) for arg in args):
  49. return args[-1]
  50. elif all(isinstance(arg, list) for arg in args):
  51. res = []
  52. for arg in args:
  53. res.extend(arg)
  54. return res
  55. elif all(isinstance(arg, dict) for arg in args):
  56. keys = set()
  57. for arg in args:
  58. keys |= set(arg.keys())
  59. dct = {}
  60. for key in keys:
  61. sub_args = []
  62. for arg in args:
  63. if key in arg:
  64. sub_args.append(arg)
  65. try:
  66. dct[key] = merge(*(a[key] for a in sub_args))
  67. except NotImplementedError as e:
  68. raise NotImplementedError(
  69. e.args[0],
  70. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  71. e.args[2])
  72. if dct[key] is None:
  73. del dct[key]
  74. return dct
  75. else:
  76. raise NotImplementedError(
  77. 'Unsupported types: %s'
  78. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  79. return None
  80. def merge_cli(*args):
  81. try:
  82. c = merge(*args)
  83. except NotImplementedError as e:
  84. sys.stderr.write('%s. Conflicting key is %r. Values are:\n%s\n' % (e.args[0], e.args[1], e.args[2]))
  85. exit(1)
  86. if c is not None:
  87. print '%s' % yaml.dump(c, default_flow_style=False)
  88. "
  89. merge_yaml() {
  90. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  91. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  92. $_merge_yaml_common_code
  93. merge_cli(*(yaml.load(fc(f)) for f in sys.argv[1:]))
  94. EOF
  95. fi
  96. python "$state_tmpdir/merge_yaml.py" "$@"
  97. }
  98. export -f merge_yaml
  99. merge_yaml_str() {
  100. local entries="$@"
  101. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  102. cat <<EOF > "$state_tmpdir/merge_yaml_str.py"
  103. $_merge_yaml_common_code
  104. merge_cli(*(yaml.load(f) for f in sys.argv[1:]))
  105. EOF
  106. fi
  107. python "$state_tmpdir/merge_yaml_str.py" "$@"
  108. }
  109. export -f merge_yaml_str
  110. yaml_key_val_str() {
  111. local entries="$@"
  112. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  113. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  114. $_merge_yaml_common_code
  115. print '%s' % yaml.dump({
  116. yaml.load(sys.argv[1]):
  117. yaml.load(sys.argv[2])}, default_flow_style=False)
  118. EOF
  119. fi
  120. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  121. }
  122. export -f yaml_key_val_str
  123. ##
  124. ## Functions
  125. ##
  126. docker_has_image() {
  127. local image="$1"
  128. images=$(docker images -q "$image" 2>/dev/null) || {
  129. err "docker images call has failled unexpectedly."
  130. return 1
  131. }
  132. [ "$images" ]
  133. }
  134. export -f docker_has_image
  135. gen_password() {
  136. python -c 'import random; \
  137. xx = "azertyuiopqsdfghjklmwxcvbn1234567890AZERTYUIOPQSDFGHJKLMWXCVBN+_-"; \
  138. print "".join([xx[random.randint(0, len(xx)-1)] for x in range(0, 14)])'
  139. }
  140. export -f gen_password
  141. file_put() {
  142. local TARGET="$1"
  143. mkdir -p "$(dirname "$TARGET")" &&
  144. cat - > "$TARGET"
  145. }
  146. export -f file_put
  147. _get_docker_compose_links() {
  148. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  149. links charm charm_part master_charm
  150. if [ -z "$service" ]; then
  151. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  152. return 1
  153. fi
  154. if [ -e "$cache_file" ]; then
  155. # debug "$FUNCNAME: cache hit ($*)"
  156. cat "$cache_file"
  157. return 0
  158. fi
  159. master_charm=$(_get_top_master_charm_for_service "$service") || return 1
  160. deps=()
  161. while read-0 relation_name target_service relation_config reverse; do
  162. master_target_charm="$(_get_top_master_charm_for_service "$target_service")"
  163. [ "$master_charm" == "$master_target_charm" ] && continue
  164. if [ "$reverse" ]; then
  165. deps+=("$(echo -en "$master_target_charm:\n links:\n - $master_charm")")
  166. else
  167. deps+=("$(echo -en "$master_charm:\n links:\n - $master_target_charm")")
  168. fi
  169. done < <(get_compose_relations "$service") || return 1
  170. merge_yaml_str "${deps[@]}" | tee "$cache_file"
  171. }
  172. ##
  173. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  174. ## Some metadata.yml (of subordinates) will indeed modify other
  175. ## services than themselves.
  176. _get_docker_compose_service_mixin() {
  177. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" links charm charm_part
  178. if [ -z "$service" ]; then
  179. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  180. return 1
  181. fi
  182. if [ -e "$cache_file" ]; then
  183. # debug "$FUNCNAME: cache hit ($*)"
  184. cat "$cache_file"
  185. return 0
  186. fi
  187. master_charm=$(_get_top_master_charm_for_service "$service") || return 1
  188. ## The compose part
  189. links_yaml=$(_get_docker_compose_links "$service") || return 1
  190. ## the charm part
  191. #debug "Get charm name from service name $DARKYELLOW$service$NORMAL."
  192. charm=$(get_service_charm "$service") || return 1
  193. charm_part=$(get_docker_compose_mixin_from_metadata "$charm") || return 1
  194. ## Merge results
  195. if [ "$charm_part" ]; then
  196. charm_yaml="$(yaml_key_val_str "$master_charm" "$charm_part")" || return 1
  197. merge_yaml_str "$links_yaml" "$charm_yaml"
  198. else
  199. echo "$links_yaml"
  200. fi > "$cache_file"
  201. cat "$cache_file"
  202. }
  203. export -f _get_docker_compose_service_mixin
  204. ##
  205. ## Get full `docker-compose.yml` format for all listed services (and
  206. ## their deps)
  207. ##
  208. ## @export
  209. ## @cache: !system !nofail +stdout
  210. get_docker_compose () {
  211. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" entries services service
  212. if [ -e "$cache_file" ]; then
  213. # debug "$FUNCNAME: cache hit ($*)"
  214. cat "$cache_file"
  215. return 0
  216. fi
  217. ##
  218. ## Adding sub services configurations
  219. ##
  220. declare -A entries
  221. debug "Compiling 'docker-compose.conf' for $DARKYELLOW$@$NORMAL..."
  222. for target_service in "$@"; do
  223. services=$(get_ordered_service_dependencies "$target_service") || return 1
  224. debug "$DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" $services "$NORMAL"
  225. for service in $services; do
  226. if [ "${entries[$service]}" ]; then
  227. ## Prevent double inclusion of same service if this
  228. ## service is deps of two or more of your
  229. ## requirements.
  230. continue
  231. fi
  232. ## mark the service as "loaded" as well as it's containers
  233. ## if this is a subordinate service
  234. entries[$service]=$(_get_docker_compose_service_mixin "$service") || return 1
  235. done
  236. done
  237. merge_yaml_str "${entries[@]}" > "$cache_file"
  238. export _current_docker_compose="$(cat "$cache_file")"
  239. echo "$_current_docker_compose"
  240. debug " ... Compilation of base 'docker-compose.conf' done." || true
  241. # debug " ** ${WHITE}docker-compose.conf${NORMAL}:"
  242. # debug "$_current_docker_compose"
  243. }
  244. export -f get_docker_compose
  245. ## XXXvlab: a lot to be done to cache the results
  246. get_compose_service_def () {
  247. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  248. if [ -e "$cache_file" ]; then
  249. # debug "$FUNCNAME: cache hit ($*)"
  250. cat "$cache_file"
  251. return 0
  252. fi
  253. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  254. service_def_base=
  255. if [ -d "$CHARM_STORE/$service" ]; then
  256. service_def_base="charm: $service"
  257. fi
  258. value=
  259. if [ -r "$COMPOSE_YML_FILE" ]; then
  260. value=$(shyaml get-value "$service" 2>/dev/null < "$COMPOSE_YML_FILE")
  261. fi
  262. if [ -z "$service_def_base" -a -z "$value" ]; then
  263. err "Invalid service $DARKYELLOW$service$NORMAL: no definition in" \
  264. "compose file nor charm with same name."
  265. return 1
  266. fi
  267. merge_yaml <(echo "$service_def_base") <(echo "$value") > "$cache_file"
  268. cat "$cache_file"
  269. }
  270. export -f get_compose_service_def
  271. get_service_charm () {
  272. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  273. if [ -e "$cache_file" ]; then
  274. # debug "$FUNCNAME: cache hit ($*)"
  275. cat "$cache_file"
  276. return 0
  277. fi
  278. if [ -z "$service" ]; then
  279. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  280. return 1
  281. fi
  282. service_def=$(get_compose_service_def "$service") || return 1
  283. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  284. if [ -z "$charm" ]; then
  285. err "Missing charm in service $DARKYELLOW$service$NORMAL definition."
  286. return 1
  287. fi
  288. echo "$charm" | tee "$cache_file"
  289. }
  290. export -f get_service_charm
  291. ## built above the docker-compose abstraction, so it relies on the
  292. ## full docker-compose.yml to be already built.
  293. get_service_def () {
  294. local service="$1" def
  295. if [ -z "$_current_docker_compose" ]; then
  296. print_syntax_error "$FUNCNAME is meant to be called after"\
  297. "\$_current_docker_compose has been calculated."
  298. fi
  299. def=$(echo "$_current_docker_compose" | shyaml get-value "$service" 2>/dev/null)
  300. if [ -z "$def" ]; then
  301. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.conf'."
  302. return 1
  303. fi
  304. echo "$def"
  305. }
  306. export -f get_service_def
  307. ## Return the base docker image name of a service
  308. service_base_docker_image() {
  309. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  310. master_charm charm service_image service_build service_dockerfile
  311. if [ -e "$cache_file" ]; then
  312. # debug "$FUNCNAME: cache hit ($*)"
  313. cat "$cache_file"
  314. return 0
  315. fi
  316. master_charm="$(_get_top_master_charm_for_service "$service")" || {
  317. err "Could not compute base charm for service $DARKYELLOW$service$NORMAL."
  318. return 1
  319. }
  320. service_def="$(get_service_def "$master_charm")" || {
  321. err "Could not get docker-compose service definition for $DARKYELLOW$master_charm$NORMAL."
  322. return 1
  323. }
  324. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  325. if [ "$?" != 0 ]; then
  326. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  327. if [ "$?" != 0 ]; then
  328. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  329. echo "$service_def" >&2
  330. return 1
  331. fi
  332. service_dockerfile="$CHARM_STORE/${service_build}/Dockerfile"
  333. if ! [ -e "$service_dockerfile" ]; then
  334. err "No Dockerfile found in '$service_dockerfile' location."
  335. return 1
  336. fi
  337. grep '^FROM' "$service_dockerfile" | xargs echo | cut -f 2 -d " "
  338. else
  339. echo "$service_image"
  340. fi | tee "$cache_file"
  341. }
  342. export -f service_base_docker_image
  343. ## XXXvlab: provided in shlib/common
  344. # read-0() {
  345. # local eof
  346. # eof=
  347. # while [ "$1" ]; do
  348. # IFS='' read -r -d '' "$1" || eof=true
  349. # shift
  350. # done
  351. # test "$eof" != true
  352. # }
  353. # export -f read-0
  354. fetch_file() {
  355. local src="$1"
  356. case "$src" in
  357. *"://"*)
  358. err "Unsupported target scheme."
  359. return 1
  360. ;;
  361. *)
  362. ## Try direct
  363. if ! [ -r "$src" ]; then
  364. err "File '$src' not found/readable."
  365. return 1
  366. fi
  367. cat "$src" || return 1
  368. ;;
  369. esac
  370. }
  371. export -f fetch_file
  372. ## receives stdin content to decompress on stdout
  373. ## stdout content should be tar format.
  374. uncompress_file() {
  375. local filename="$1"
  376. ## Warning, the content of the file is already as stdin, the filename
  377. ## is there to hint for correct decompression.
  378. case "$filename" in
  379. *".gz")
  380. gunzip
  381. ;;
  382. *".bz2")
  383. bunzip2
  384. ;;
  385. *)
  386. cat
  387. ;;
  388. esac
  389. }
  390. export -f uncompress_file
  391. get_file() {
  392. local src="$1"
  393. fetch_file "$src" | uncompress_file "$src"
  394. }
  395. export -f get_file
  396. cmd_on_base_image() {
  397. local charm="$1"
  398. shift
  399. base_image=$(service_base_docker_image "$charm") || return 1
  400. docker run -i --entrypoint /bin/bash "$base_image" -c "$*"
  401. }
  402. export -f cmd_on_base_image
  403. cached_cmd_on_base_image() {
  404. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  405. shift
  406. if [ -e "$cache_file" ]; then
  407. # debug "$FUNCNAME: cache hit ($*)"
  408. cat "$cache_file"
  409. return 0
  410. fi
  411. base_image=$(service_base_docker_image "$charm") || return 1
  412. result=$(cmd_on_base_image "$charm" "$@") || return 1
  413. echo "$result" | tee "$cache_file"
  414. }
  415. export -f cached_cmd_on_base_image
  416. array_values_to_stdin() {
  417. local e
  418. if [ "$#" -ne "1" ]; then
  419. print_syntax_warning "$FUNCNAME: need one argument."
  420. return 1
  421. fi
  422. var="$1"
  423. eval "for e in \"\${$var[@]}\"; do echo -en \"\$e\\0\"; done"
  424. }
  425. array_keys_to_stdin() {
  426. local e
  427. if [ "$#" -ne "1" ]; then
  428. print_syntax_warning "$FUNCNAME: need one argument."
  429. return 1
  430. fi
  431. var="$1"
  432. eval "for e in \"\${!$var[@]}\"; do echo -en \"\$e\\0\"; done"
  433. }
  434. array_kv_to_stdin() {
  435. local e
  436. if [ "$#" -ne "1" ]; then
  437. print_syntax_warning "$FUNCNAME: need one argument."
  438. return 1
  439. fi
  440. var="$1"
  441. eval "for e in \"\${!$var[@]}\"; do echo -n \"\$e\"; echo -en '\0'; echo -n \"\${$var[\$e]}\"; echo -en '\0'; done"
  442. }
  443. array_pop() {
  444. local narr="$1" nres="$2"
  445. for key in $(eval "echo \${!$narr[@]}"); do
  446. eval "$nres=\${$narr[\"\$key\"]}"
  447. eval "unset $narr[\"\$key\"]"
  448. return 0
  449. done
  450. }
  451. export -f array_pop
  452. array_member() {
  453. local src elt
  454. src="$1"
  455. elt="$2"
  456. while read-0 key; do
  457. if [ "$(eval "echo -n \"\${$src[\$key]}\"")" == "$elt" ]; then
  458. return 0
  459. fi
  460. done < <(array_keys_to_stdin "$src")
  461. return 1
  462. }
  463. export -f array_member
  464. get_charm_relation_def () {
  465. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  466. relation_def metadata
  467. if [ -e "$cache_file" ]; then
  468. # debug "$FUNCNAME: cache hit ($*)"
  469. cat "$cache_file"
  470. return 0
  471. fi
  472. metadata="$(get_charm_metadata "$charm")" || return 1
  473. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  474. echo "$relation_def" | tee "$cache_file"
  475. }
  476. export -f get_charm_relation_def
  477. get_charm_reverse_tech_dep_relation() {
  478. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  479. relation_def metadata value
  480. if [ -e "$cache_file" ]; then
  481. # debug "$FUNCNAME: cache hit ($*)"
  482. cat "$cache_file"
  483. return 0
  484. fi
  485. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  486. value=$(echo "$relation_def" | shyaml get-value 'reverse-tech-dep' 2>/dev/null)
  487. echo "$value" | tee "$cache_file"
  488. }
  489. export -f get_charm_reverse_tech_dep_relation
  490. ##
  491. ## Use compose file to get deps, and relation definition in metadata.yml
  492. ## for reverse-tech-dep attribute.
  493. get_service_deps() {
  494. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  495. if [ -e "$cache_file" ]; then
  496. # debug "$FUNCNAME: cache hit ($*)"
  497. cat "$cache_file"
  498. return 0
  499. fi
  500. (
  501. set -o pipefail
  502. get_compose_relations "$service" | \
  503. while read-0 relation_name target_service _relation_config reverse; do
  504. echo "$target_service"
  505. done | tee "$cache_file"
  506. ) || return 1
  507. }
  508. export -f get_service_deps
  509. _rec_get_depth() {
  510. local elt=$1
  511. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  512. if [ "${depths[$elt]}" ]; then
  513. return 0
  514. fi
  515. deps=$(get_service_deps "$elt") || return 1
  516. if [ -z "$deps" ]; then
  517. depths[$elt]=0
  518. fi
  519. max=0
  520. for dep in $deps; do
  521. _rec_get_depth "$dep" || return 1
  522. if (( "${depths[$dep]}" > "$max" )); then
  523. max="${depths[$dep]}"
  524. fi
  525. done
  526. depths[$elt]=$((max + 1))
  527. }
  528. export -f _rec_get_depth
  529. get_ordered_service_dependencies() {
  530. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  531. if [ -e "$cache_file" ]; then
  532. # debug "$FUNCNAME: cache hit ($*)"
  533. cat "$cache_file"
  534. return 0
  535. fi
  536. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  537. if [ -z "${services[*]}" ]; then
  538. print_syntax_error "$FUNCNAME: no arguments"
  539. return 1
  540. fi
  541. declare -A depths
  542. visited=()
  543. heads=("${services[@]}")
  544. while [ "${#heads[@]}" != 0 ]; do
  545. array_pop heads head
  546. visited+=("$head")
  547. _rec_get_depth "$head" || return 1
  548. done
  549. i=0
  550. while [ "${#depths[@]}" != 0 ]; do
  551. for key in "${!depths[@]}"; do
  552. value="${depths[$key]}"
  553. if [ "$value" == "$i" ]; then
  554. echo "$key"
  555. unset depths[$key]
  556. fi
  557. done
  558. i=$((i + 1))
  559. done > "$cache_file"
  560. cat "$cache_file"
  561. }
  562. export -f get_ordered_service_dependencies
  563. run_service_hook () {
  564. local services="$1" action="$2" loaded
  565. declare -A loaded
  566. for service in $services; do
  567. for subservice in $(get_ordered_service_dependencies "$service"); do
  568. if [ "${loaded[$subservice]}" ]; then
  569. ## Prevent double inclusion of same service if this
  570. ## service is deps of two or more of your
  571. ## requirements.
  572. continue
  573. fi
  574. charm=$(get_service_charm "$subservice") || return 1
  575. TARGET_SCRIPT="$CHARM_STORE/$charm/hooks/$action"
  576. [ -e "$TARGET_SCRIPT" ] || continue
  577. PROJECT_NAME=$(get_default_project_name) || return 1
  578. Wrap -d "$YELLOW$action$NORMAL hook of charm $DARKYELLOW$charm$NORMAL" <<EOF || return 1
  579. cd "$CHARM_STORE/$charm"
  580. SERVICE_NAME=$subservice \
  581. PROJECT_NAME=$PROJECT_NAME \
  582. DOCKER_BASE_IMAGE=$(service_base_docker_image "$charm") \
  583. SERVICE_DATASTORE="$DATASTORE/$charm" \
  584. SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm" \
  585. "$TARGET_SCRIPT"
  586. EOF
  587. loaded[$subservice]=1
  588. done
  589. done
  590. return 0
  591. }
  592. relation-get () {
  593. local key="$1"
  594. cat "$RELATION_DATA_FILE" | shyaml get-value "$key" 2>/dev/null
  595. if [ "$?" != 0 ]; then
  596. err "The key $WHITE$key$NORMAL was not found in relation's data."
  597. return 1
  598. fi
  599. }
  600. export -f relation-get
  601. relation-base-compose-get () {
  602. local key="$1"
  603. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  604. if [ "$?" != 0 ]; then
  605. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  606. return 1
  607. fi
  608. }
  609. export -f relation-base-compose-get
  610. relation-target-compose-get () {
  611. local key="$1"
  612. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  613. if [ "$?" != 0 ]; then
  614. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  615. return 1
  616. fi
  617. }
  618. export -f relation-base-compose-get
  619. relation-set () {
  620. local key="$1" value="$2"
  621. if [ -z "$RELATION_DATA_FILE" ]; then
  622. err "$FUNCNAME: relation does not seems to be correctly setup."
  623. return 1
  624. fi
  625. if ! [ -r "$RELATION_DATA_FILE" ]; then
  626. err "$FUNCNAME: can't read relation's data." >&2
  627. return 1
  628. fi
  629. _config_merge "$RELATION_DATA_FILE" <(echo "$key: $value")
  630. }
  631. export -f relation-set
  632. _config_merge() {
  633. local config_filename="$1" merge_to_file="$2"
  634. touch "$config_filename" &&
  635. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  636. mv "$config_filename.tmp" "$config_filename"
  637. }
  638. export -f _config_merge
  639. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  640. config-add() {
  641. local metadata="$1"
  642. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  643. }
  644. export -f config-add
  645. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  646. init-config-add() {
  647. local metadata="$1"
  648. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" <(echo "$metadata")
  649. }
  650. export -f init-config-add
  651. logstdout() {
  652. local name="$1"
  653. sed -r 's%^%'"${name}"'> %g'
  654. }
  655. export -f logstdout
  656. logstderr() {
  657. local name="$1"
  658. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  659. }
  660. export -f logstderr
  661. _run_service_relation () {
  662. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  663. charm=$(get_service_charm "$service") || return 1
  664. target_charm=$(get_service_charm "$target_service") || return 1
  665. base_script_name=$(echo "$relation_name" | tr "-" "_" )-relation-joined
  666. script_name="hooks/${base_script_name}"
  667. [ ! -e "$CHARM_STORE/$target_charm/$script_name" -a ! -e "$CHARM_STORE/$charm/$script_name" ] &&
  668. return 0
  669. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  670. RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config") || return 1
  671. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$service") || return 1
  672. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  673. export BASE_SERVICE_NAME=$service
  674. export TARGET_SERVICE_NAME=$target_service
  675. export BASE_CHARM_NAME=$charm
  676. export TARGET_CHARM_NAME=$target_charm
  677. PROJECT_NAME=$(get_default_project_name) || return 1
  678. MASTER_BASE_CHARM_NAME=$(_get_top_master_charm_for_service "$service") || return 1
  679. MASTER_TARGET_CHARM_NAME=$(_get_top_master_charm_for_service "$target_service") || return 1
  680. export RELATION_DATA_FILE RELATION_BASE_COMPOSE_DEF RELATION_TARGET_COMPOSE_DEF
  681. export MASTER_BASE_CHARM_NAME MASTER_TARGET_CHARM_NAME PROJECT_NAME
  682. target_errlvl=0
  683. if ! [ -e "$CHARM_STORE/$target_charm/$script_name" ]; then
  684. verb "No relation script '$script_name' in $DARKYELLOW$target_charm$NORMAL."
  685. else
  686. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  687. "for target charm $DARKYELLOW$target_charm$NORMAL"
  688. RELATION_CONFIG="$relation_dir/config_provider"
  689. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  690. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  691. {
  692. (
  693. cd "$CHARM_STORE/$target_charm"
  694. SERVICE_NAME=$target_service
  695. SERVICE_DATASTORE="$DATASTORE/$target_charm"
  696. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_charm"
  697. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  698. "$script_name"
  699. echo "$?" > "$relation_dir/target_errlvl"
  700. ) | logstdout "$DARKYELLOW$target_charm$NORMAL/$base_script_name ${GREEN}@${NORMAL}"
  701. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_charm$NORMAL/$base_script_name ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  702. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  703. err "Relation script '$script_name' in $DARKYELLOW$target_charm$NORMAL" \
  704. "failed before outputing an errorlevel."
  705. ((target_errlvl |= "1" ))
  706. }
  707. if [ -e "$RELATION_CONFIG" ]; then
  708. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  709. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  710. rm "$RELATION_CONFIG"
  711. ((target_errlvl |= "$?"))
  712. fi
  713. fi
  714. if [ "$target_errlvl" == 0 ]; then
  715. errlvl=0
  716. if [ -e "$CHARM_STORE/$charm/$script_name" ]; then
  717. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  718. "for charm $DARKYELLOW$charm$NORMAL"
  719. RELATION_CONFIG="$relation_dir/config_providee"
  720. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  721. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  722. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  723. {
  724. (
  725. cd "$CHARM_STORE/$charm"
  726. SERVICE_NAME=$service
  727. SERVICE_DATASTORE="$DATASTORE/$charm"
  728. SERVICE_CONFIGSTORE="$CONFIGSTORE/$charm"
  729. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  730. "$script_name"
  731. echo "$?" > "$relation_dir/errlvl"
  732. ) | logstdout "$DARKYELLOW$charm$NORMAL/$base_script_name ${GREEN}@${NORMAL}"
  733. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/$base_script_name ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  734. errlvl="$(cat "$relation_dir/errlvl")" || {
  735. err "Relation script '$script_name' in $DARKYELLOW$charm$NORMAL" \
  736. "failed before outputing an errorlevel."
  737. ((errlvl |= "1" ))
  738. }
  739. if [ -e "$RELATION_CONFIG" ]; then
  740. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  741. rm "$RELATION_CONFIG"
  742. ((errlvl |= "$?" ))
  743. fi
  744. if [ "$errlvl" != 0 ]; then
  745. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$charm$NORMAL failed to run properly."
  746. fi
  747. else
  748. verb "No relation script '$script_name' in charm $DARKYELLOW$charm$NORMAL. Ignoring."
  749. fi
  750. else
  751. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_charm$NORMAL failed to run properly."
  752. fi
  753. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  754. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  755. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  756. return 0
  757. else
  758. return 1
  759. fi
  760. }
  761. export -f _run_service_relation
  762. get_compose_relations () {
  763. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" relation_name relation_def
  764. if [ -e "$cache_file" ]; then
  765. # debug "$FUNCNAME: cache hit ($*)"
  766. cat "$cache_file"
  767. return 0
  768. fi
  769. compose_def="$(get_compose_service_def "$service")" || return 1
  770. (
  771. set -o pipefail
  772. if [ "$compose_def" ]; then
  773. while read-0 relation_name relation_def; do
  774. (
  775. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  776. "str")
  777. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)"
  778. reverse="$(get_charm_reverse_tech_dep_relation "$target_service" "$relation_name")"
  779. echo -en "$relation_name\0$target_service\0\0$reverse\0"
  780. ;;
  781. "sequence")
  782. while read-0 target_service; do
  783. reverse="$(get_charm_reverse_tech_dep_relation "$target_service" "$relation_name")"
  784. echo -en "$relation_name\0$target_service\0\0$reverse\0"
  785. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  786. ;;
  787. "struct")
  788. while read-0 target_service relation_config; do
  789. reverse="$(get_charm_reverse_tech_dep_relation "$target_service" "$relation_name")"
  790. echo -en "$relation_name\0$target_service\0$relation_config\0$reverse\0"
  791. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  792. ;;
  793. esac
  794. ) </dev/null >> "$cache_file"
  795. done < <(echo "$compose_def" | shyaml key-values-0 relations 2>/dev/null)
  796. fi
  797. )
  798. if [ "$?" != 0 ]; then
  799. err "Error while looking for compose relations."
  800. rm -f "$cache_file" ## no cache
  801. return 1
  802. fi
  803. [ -e "$cache_file" ] && cat "$cache_file"
  804. return 0
  805. }
  806. export -f get_compose_relations
  807. run_service_relations () {
  808. local services="$1" loaded
  809. declare -A loaded
  810. for service in $(get_ordered_service_dependencies $services); do
  811. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  812. for subservice in $(get_service_deps "$service") "$service"; do
  813. [ "${loaded[$subservice]}" ] && continue
  814. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  815. while read-0 relation_name target_service relation_config reverse; do
  816. export relation_config
  817. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  818. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  819. EOF
  820. done < <(get_compose_relations "$subservice") || return 1
  821. loaded[$subservice]=1
  822. done
  823. done
  824. }
  825. export -f run_service_relations
  826. _run_service_action_direct() {
  827. local service="$1" action="$2" charm script _dummy
  828. shift; shift
  829. read-0 charm script || true ## against 'set -e' that could be setup in parent scripts
  830. if read-0 _dummy || [ "$_dummy" ]; then
  831. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  832. return 1
  833. fi
  834. compose_file=$(get_compose_yml_location) || return 1
  835. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  836. export state_tmpdir
  837. {
  838. (
  839. set +e ## Prevents unwanted leaks from parent shell
  840. cd "$CHARM_STORE/$charm"
  841. export COMPOSE_CONFIG=$(cat "$compose_file")
  842. export METADATA_CONFIG=$(cat "$CHARM_STORE/$charm/metadata.yml")
  843. export SERVICE_NAME=$service
  844. export ACTION_NAME=$action
  845. export CONTAINER_NAME=$(_get_top_master_charm_for_service "$service")
  846. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  847. export SERVICE_DATASTORE="$DATASTORE/$service"
  848. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  849. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  850. stdbuf -oL -eL "$script" "$@"
  851. echo "$?" > "$action_errlvl_file"
  852. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  853. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  854. if ! [ -e "$action_errlvl_file" ]; then
  855. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  856. "to output an errlvl"
  857. return 1
  858. fi
  859. return "$(cat "$action_errlvl_file")"
  860. }
  861. export -f _run_service_action_direct
  862. _run_service_action_relation() {
  863. local service="$1" action="$2" charm target_charm relation_name target_script relation_config _dummy
  864. shift; shift
  865. read-0 charm target_charm relation_name target_script relation_config || true
  866. if read-0 _dummy || [ "$_dummy" ]; then
  867. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  868. return 1
  869. fi
  870. export RELATION_DATA_FILE=$(get_relation_data_file "$charm" "$target_charm" "$relation_name" "$relation_config")
  871. compose_file=$(get_compose_yml_location) || return 1
  872. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  873. export state_tmpdir
  874. {
  875. (
  876. set +e ## Prevents unwanted leaks from parent shell
  877. cd "$CHARM_STORE/$charm"
  878. export METADATA_CONFIG=$(cat "$CHARM_STORE/$charm/metadata.yml")
  879. export SERVICE_NAME=$service
  880. export RELATION_TARGET_CHARM="$target_charm"
  881. export RELATION_CHARM="$charm"
  882. export ACTION_NAME=$action
  883. export CONTAINER_NAME=$(_get_top_master_charm_for_service "$service")
  884. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  885. export SERVICE_DATASTORE="$DATASTORE/$service"
  886. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  887. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  888. stdbuf -oL -eL "$target_script" "$@"
  889. echo "$?" > "$action_errlvl_file"
  890. ) | logstdout "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  891. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$charm$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  892. if ! [ -e "$action_errlvl_file" ]; then
  893. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  894. "to output an errlvl"
  895. return 1
  896. fi
  897. return "$(cat "$action_errlvl_file")"
  898. }
  899. export -f _run_service_action_relation
  900. get_relation_data_dir() {
  901. local charm="$1" target_charm="$2" relation_name="$3" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  902. if [ -e "$cache_file" ]; then
  903. # debug "$FUNCNAME: cache hit ($*)"
  904. cat "$cache_file"
  905. return 0
  906. fi
  907. project=$(get_default_project_name) || return 1
  908. relation_dir="$VARDIR/relations/$project/$charm-$target_charm/$relation_name"
  909. if ! [ -d "$relation_dir" ]; then
  910. mkdir -p "$relation_dir" || return 1
  911. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  912. fi
  913. echo "$relation_dir" || tee "$cache_file"
  914. }
  915. export -f get_relation_data_dir
  916. get_relation_data_file() {
  917. local charm="$1" target_charm="$2" relation_name="$3" relation_config="$4"
  918. relation_dir=$(get_relation_data_dir "$charm" "$target_charm" "$relation_name") || return 1
  919. relation_data_file="$relation_dir/data"
  920. new=
  921. if [ -e "$relation_data_file" ]; then
  922. ## Has reference changed ?
  923. new_md5=$(echo "$relation_config" | md5_compat)
  924. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  925. new=true
  926. fi
  927. else
  928. new=true
  929. fi
  930. if [ "$new" ]; then
  931. echo "$relation_config" > "$relation_data_file"
  932. chmod go-rwx "$relation_data_file" ## protecting this file
  933. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  934. fi
  935. echo "$relation_data_file"
  936. }
  937. export -f get_relation_data_file
  938. has_service_action () {
  939. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  940. target_script charm target_charm
  941. if [ -e "$cache_file" ]; then
  942. # debug "$FUNCNAME: cache hit ($*)"
  943. cat "$cache_file"
  944. return 0
  945. fi
  946. charm=$(get_service_charm "$service") || return 1
  947. ## Action directly provided ?
  948. target_script="$CHARM_STORE/$charm/actions/$action"
  949. if [ -x "$target_script" ]; then
  950. echo -en "direct\0$charm\0$target_script" | tee "$cache_file"
  951. return 0
  952. fi
  953. ## Action provided by relation ?
  954. while read-0 relation_name target_service relation_config reverse; do
  955. target_charm=$(get_service_charm "$target_service") || return 1
  956. target_script="$CHARM_STORE/$target_charm/actions/relations/$relation_name/$action"
  957. if [ -x "$target_script" ]; then
  958. echo -en "relation\0$charm\0$target_charm\0$relation_name\0$target_script\0$relation_config" | tee "$cache_file"
  959. return 0
  960. fi
  961. done < <(get_compose_relations "$service")
  962. master=$(_get_top_master_charm_for_service "$charm")
  963. [ "$master" == "$charm" ] && return 1
  964. has_service_action "$master" "$action"
  965. }
  966. export -f has_service_action
  967. run_service_action () {
  968. local service="$1" action="$2"
  969. shift ; shift
  970. {
  971. if ! read-0 action_type; then
  972. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  973. info " Add an executable script to '$CHARM_STORE/$charm/actions/$action' to implement action."
  974. return 1
  975. fi
  976. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  977. "_run_service_action_${action_type}" "$service" "$action" "$@"
  978. } < <(has_service_action "$service" "$action")
  979. }
  980. export -f run_service_action
  981. get_compose_relation_config() {
  982. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  983. if [ -e "$cache_file" ]; then
  984. # debug "$FUNCNAME: cache hit ($*)"
  985. cat "$cache_file"
  986. return 0
  987. fi
  988. compose_service_def=$(get_compose_service_def "$service") || return 1
  989. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  990. }
  991. export -f get_compose_relation_config
  992. # ## Return key-values-0
  993. # get_compose_relation_config_for_service() {
  994. # local service=$1 relation_name=$2 relation_config
  995. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  996. # if ! relation_config=$(
  997. # echo "$compose_service_relations" |
  998. # shyaml get-value "${relation_name}" 2>/dev/null); then
  999. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  1000. # "relation config in compose configuration."
  1001. # return 1
  1002. # fi
  1003. # if [ -z "$relation_config" ]; then
  1004. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  1005. # return 1
  1006. # fi
  1007. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  1008. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  1009. # return 1
  1010. # fi
  1011. # }
  1012. # export -f get_compose_relation_config_for_service
  1013. _get_master_charm_for_service() {
  1014. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1015. charm metadata requires master_charm target_charm target_service service_def
  1016. if [ -e "$cache_file" ]; then
  1017. # debug "$FUNCNAME: cache hit ($*)"
  1018. cat "$cache_file"
  1019. return 0
  1020. fi
  1021. charm=$(get_service_charm "$service") || return 1
  1022. metadata=$(get_charm_metadata "$charm") || return 1
  1023. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  1024. ## just return charm name
  1025. echo "$charm" > "$cache_file"
  1026. echo "$charm"
  1027. return 0
  1028. fi
  1029. ## fetch the container relation
  1030. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1031. if [ -z "$requires" ]; then
  1032. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any 'requires' " \
  1033. "section."
  1034. fi
  1035. master_charm=
  1036. while read-0 relation_name relation; do
  1037. if [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ]; then
  1038. # debug "$DARKYELLOW$service$NORMAL's relation" \
  1039. # "$DARKBLUE${relation_name}$NORMAL is a container."
  1040. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1041. if [ -z "$interface" ]; then
  1042. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  1043. return 1
  1044. fi
  1045. ## Action provided by relation ?
  1046. target_service=
  1047. while read-0 relation_name candidate_target_service _relation_config _reverse; do
  1048. [ "$interface" == "$relation_name" ] && {
  1049. target_service="$candidate_target_service"
  1050. break
  1051. }
  1052. done < <(get_compose_relations "$service")
  1053. if [ -z "$target_service" ]; then
  1054. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1055. "${DARKYELLOW}$service$NORMAL compose definition."
  1056. return 1
  1057. fi
  1058. master_charm=$(get_service_charm "$target_service") || return 1
  1059. break
  1060. fi
  1061. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1062. if [ -z "$master_charm" ]; then
  1063. die "Charm $DARKYELLOW$charm$NORMAL is a subordinate but does not have any relation with" \
  1064. " ${WHITE}scope${NORMAL} set to 'container'."
  1065. fi
  1066. echo "$master_charm" > "$cache_file"
  1067. echo "$master_charm"
  1068. return 0
  1069. }
  1070. export -f _get_master_charm_for_service
  1071. _get_top_master_charm_for_service() {
  1072. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1073. current_service
  1074. if [ -e "$cache_file" ]; then
  1075. # debug "$FUNCNAME: cache hit ($*)"
  1076. cat "$cache_file"
  1077. return 0
  1078. fi
  1079. current_service="$service"
  1080. while true; do
  1081. master_service=$(_get_master_charm_for_service "$current_service") || return 1
  1082. [ "$master_service" == "$current_service" ] && break
  1083. current_service="$master_service"
  1084. done
  1085. echo "$current_service" | tee "$cache_file"
  1086. return 0
  1087. }
  1088. export -f _get_top_master_charm_for_service
  1089. get_charm_metadata() {
  1090. local charm="$1" metadata_file
  1091. metadata_file="$CHARM_STORE/$charm/metadata.yml"
  1092. if ! [ -e "$metadata_file" ]; then
  1093. return 0 ## No metadata file is as if metadata was empty
  1094. fi
  1095. cat "$metadata_file"
  1096. }
  1097. export -f get_charm_metadata
  1098. ##
  1099. ## The result is a mixin that is not always a complete valid
  1100. ## docker-compose entry (thinking of subordinates). The result
  1101. ## will be merge with master charms.
  1102. get_docker_compose_mixin_from_metadata() {
  1103. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1104. metadata_file metadata volumes docker_compose subordinate image
  1105. if [ -e "$cache_file" ]; then
  1106. debug "$FUNCNAME: cache hit ($*)"
  1107. cat "$cache_file"
  1108. return 0
  1109. fi
  1110. mixin=
  1111. metadata="$(get_charm_metadata "$charm")"
  1112. if [ "$metadata" ]; then
  1113. ## resources to volumes
  1114. volumes=$(
  1115. for resource_type in data config; do
  1116. while read-0 resource; do
  1117. eval "echo \" - \$${resource_type^^}STORE/\$charm\$resource:\$resource:rw\""
  1118. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1119. done
  1120. while read-0 resource; do
  1121. if [[ "$resource" == *:* ]]; then
  1122. echo " - $resource:rw"
  1123. else
  1124. echo " - $resource:$resource:rw"
  1125. fi
  1126. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1127. )
  1128. if [ "$volumes" ]; then
  1129. mixin=$(echo -en "volumes:\n$volumes")
  1130. fi
  1131. docker_compose=$(echo "$metadata" | shyaml get-value "docker-compose" 2>/dev/null)
  1132. if [ "$docker_compose" ]; then
  1133. mixin=$(merge_yaml_str "$mixin" "$docker_compose")
  1134. fi
  1135. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1136. subordinate=true
  1137. fi
  1138. fi
  1139. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1140. image_or_build_statement=
  1141. if [ "$image" ]; then
  1142. if [ "$subordinate" ]; then
  1143. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1144. return 1
  1145. fi
  1146. image_or_build_statement="image: $image"
  1147. elif [ -d "$CHARM_STORE/$charm/build" ]; then
  1148. if [ "$subordinate" ]; then
  1149. err "Subordinate charm can not have a 'build' sub directory."
  1150. return 1
  1151. fi
  1152. image_or_build_statement="build: $charm/build"
  1153. fi
  1154. if [ "$image_or_build_statement" ]; then
  1155. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1156. fi
  1157. echo "$mixin" > "$cache_file"
  1158. echo "$mixin"
  1159. }
  1160. export -f get_docker_compose_mixin_from_metadata
  1161. _save() {
  1162. local name="$1"
  1163. cat - | tee -a "$docker_compose_dir/.data/$name"
  1164. }
  1165. export -f _save
  1166. get_default_project_name() {
  1167. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1168. echo "$DEFAULT_PROJECT_NAME"
  1169. return 0
  1170. fi
  1171. compose_yml_location="$(get_compose_yml_location)"
  1172. if [ "$compose_yml_location" ]; then
  1173. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1174. echo "$(basename "$(dirname "$normalized_path")")"
  1175. return 0
  1176. fi
  1177. fi
  1178. echo "project"
  1179. return 0
  1180. }
  1181. export -f get_default_project_name
  1182. launch_docker_compose() {
  1183. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1184. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1185. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1186. # rm -rf \"$docker_compose_tmpdir\""
  1187. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1188. project=$(get_default_project_name)
  1189. mkdir -p "$docker_compose_tmpdir/$project"
  1190. docker_compose_dir="$docker_compose_tmpdir/$project"
  1191. if [ -z "$SERVICE_PACK" ]; then
  1192. export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1193. fi
  1194. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1195. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1196. # debug "Merging some config data in docker-compose.yml:"
  1197. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1198. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1199. fi
  1200. ## XXXvlab: could be more specific and only link the needed charms
  1201. ln -sf "$CHARM_STORE/"* "$docker_compose_dir/"
  1202. mkdir "$docker_compose_dir/.data"
  1203. {
  1204. {
  1205. cd "$docker_compose_dir"
  1206. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL"
  1207. debug "$(cat "$docker_compose_dir/docker-compose.yml")"
  1208. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1209. docker-compose "$@"
  1210. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1211. } | _save stdout
  1212. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1213. 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
  1214. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1215. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1216. fi
  1217. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl")"
  1218. if [ -z "docker_compose_dir" ]; then
  1219. err "Something went wrong before you could gather docker-compose errorlevel."
  1220. return 1
  1221. fi
  1222. return "$docker_compose_errlvl"
  1223. }
  1224. export -f launch_docker_compose
  1225. get_compose_yml_location() {
  1226. parent=$(while ! [ -e "./compose.yml" ]; do
  1227. [ "$PWD" == "/" ] && exit 0
  1228. cd ..
  1229. done; echo "$PWD"
  1230. )
  1231. if [ "$parent" ]; then
  1232. echo "$parent/compose.yml"
  1233. return 0
  1234. fi
  1235. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1236. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1237. err "No 'compose.yml' was found in current or parent dirs," \
  1238. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file."
  1239. die "Please provide a 'compose.yml' file."
  1240. fi
  1241. echo "$DEFAULT_COMPOSE_FILE"
  1242. return 0
  1243. fi
  1244. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1245. die "Please provide a 'compose.yml' file."
  1246. return 1
  1247. }
  1248. export -f get_compose_yml_location
  1249. get_default_target_services() {
  1250. local services=("$@")
  1251. if [ -z "${services[*]}" ]; then
  1252. if [ "$DEFAULT_SERVICES" ]; then
  1253. info "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1254. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1255. services="$DEFAULT_SERVICES"
  1256. else
  1257. err "No service provided."
  1258. return 1
  1259. fi
  1260. fi
  1261. echo "${services[*]}"
  1262. }
  1263. export -f get_default_target_services
  1264. get_master_services() {
  1265. local loaded master_service
  1266. declare -A loaded
  1267. for service in "$@"; do
  1268. master_service=$(_get_top_master_charm_for_service "$service") || return 1
  1269. if [ "${loaded[$master_service]}" ]; then
  1270. continue
  1271. fi
  1272. echo "$master_service"
  1273. loaded["$master_service"]=1
  1274. done | xargs echo
  1275. }
  1276. export -f get_master_services
  1277. _setup_state_dir() {
  1278. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1279. #debug "Creating temporary state directory in '$state_tmpdir'."
  1280. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1281. # rm -rf \"$state_tmpdir\""
  1282. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1283. }
  1284. get_docker_compose_opts_list() {
  1285. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1286. if [ -e "$cache_file" ]; then
  1287. debug "$FUNCNAME: cache hit ($*)"
  1288. cat "$cache_file"
  1289. return 0
  1290. fi
  1291. docker-compose "$@" --help | grep '^Options:' -A 20000 |
  1292. tail -n +2 |
  1293. egrep "^\s+-" |
  1294. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1295. tee "$cache_file"
  1296. }
  1297. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  1298. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  1299. get_docker_compose_multi_opts_list() {
  1300. opts_list=$(get_docker_compose_opts_list "$@")
  1301. echo "$opts_list" | egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1302. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  1303. tr ',' "\n" | xargs echo
  1304. }
  1305. get_docker_compose_single_opts_list() {
  1306. opts_list=$(get_docker_compose_opts_list "$@")
  1307. echo "$opts_list" | egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1308. tr ',' "\n" | xargs echo
  1309. }
  1310. [ "$SOURCED" ] && return 0
  1311. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  1312. if [ -r /etc/default/charm ]; then
  1313. . /etc/default/charm
  1314. fi
  1315. if [ -r "/etc/default/$exname" ]; then
  1316. . "/etc/default/$exname"
  1317. fi
  1318. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  1319. ## userdir ? and global /etc/compose.yml ?
  1320. . /etc/compose.conf
  1321. . /etc/compose.local.conf
  1322. fi
  1323. _setup_state_dir
  1324. ##
  1325. ## Argument parsing
  1326. ##
  1327. remainder_args=()
  1328. compose_opts=()
  1329. action_opts=()
  1330. no_hooks=
  1331. no_init=
  1332. action=
  1333. stage="main" ## switches from 'main', to 'action', 'remainder'
  1334. # DC_MATCH_MULTI=
  1335. # DC_MATCH_SINGLE=
  1336. while [ "$#" != 0 ]; do
  1337. case "$stage" in
  1338. "main")
  1339. case "$1" in
  1340. --help|-h)
  1341. no_init=true ; no_hooks=true ; no_relations=true
  1342. compose_opts+=("$1")
  1343. ;;
  1344. --verbose|-v)
  1345. export VERBOSE=true
  1346. compose_opts+=("$1")
  1347. ;;
  1348. -f)
  1349. [ -e "$2" ] || die "File $2 doesn't exists"
  1350. export DEFAULT_COMPOSE_FILE="$2"
  1351. shift
  1352. ;;
  1353. -p)
  1354. export DEFAULT_PROJECT_NAME="$2"
  1355. shift
  1356. ;;
  1357. --no-relations)
  1358. export no_relations=true
  1359. ;;
  1360. --no-hooks)
  1361. export no_hooks=true
  1362. ;;
  1363. --no-init)
  1364. export no_init=true
  1365. ;;
  1366. --debug)
  1367. export DEBUG=true
  1368. export VERBOSE=true
  1369. ;;
  1370. --*|-*)
  1371. compose_opts+=("$1")
  1372. ;;
  1373. *)
  1374. action="$1"
  1375. stage="action"
  1376. # DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") || return 1
  1377. # DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action") $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  1378. ;;
  1379. esac
  1380. ;;
  1381. "action")
  1382. case "$1" in
  1383. --help|-h)
  1384. no_init=true ; no_hooks=true ; no_relations=true
  1385. action_opts+=("$1")
  1386. ;;
  1387. --verbose|-v)
  1388. export VERBOSE=true
  1389. action_opts+=("$1")
  1390. ;;
  1391. --*|-*)
  1392. action_opts+=("$1")
  1393. ;;
  1394. *)
  1395. action_posargs+=("$1")
  1396. stage="remainder"
  1397. ;;
  1398. esac
  1399. ;;
  1400. "remainder")
  1401. remainder_args+=("$@")
  1402. break 3;;
  1403. esac
  1404. shift
  1405. done
  1406. [ "${compose_opts[*]}" ] && debug "Main docker-compose opts: ${compose_opts[*]}"
  1407. [ "${action_opts[*]}" ] && debug "Action '$action' opts: ${action_opts[*]}"
  1408. [ "${remainder_args[*]}" ] && debug "Remainder args: ${remainder_args[*]}"
  1409. ##
  1410. ## Actual code
  1411. ##
  1412. export CHARM_STORE=${CHARM_STORE:-/srv/charm-store}
  1413. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  1414. export COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  1415. debug "Found 'compose.yml' file in '$COMPOSE_YML_FILE'."
  1416. if ! [ -d "$CHARM_STORE" ]; then
  1417. err "Charm store path $YELLOW$CHARM_STORE$NORMAL does not exists. "
  1418. err "Please check your $YELLOW\$CHARM_STORE$NORMAL variable value."
  1419. exit 1
  1420. fi
  1421. if [ -z "$(cd "$CHARM_STORE"; ls)" ]; then
  1422. err "no available charms in charm store $YELLOW$CHARM_STORE$NORMAL. Either:"
  1423. err " - check $YELLOW\$CHARM_STORE$NORMAL variable value"
  1424. err " - download charms in $CHARM_STORE"
  1425. print_error "Charm store is empty. Cannot continue."
  1426. fi
  1427. ##
  1428. ## Get services in command line.
  1429. ##
  1430. is_service_action=
  1431. case "$action" in
  1432. up|build|start|stop|config)
  1433. services="$(get_default_target_services "${action_posargs[@]}")" || exit 1
  1434. orig_services="${action_posargs[@]:1}"
  1435. ;;
  1436. run)
  1437. services="${action_posargs[0]}"
  1438. ;;
  1439. "")
  1440. services=
  1441. ;;
  1442. *)
  1443. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  1444. debug "Found action $DARKCYAN$action$NORMAL in service $DARKYELLOW${action_posargs[0]}$NORMAL"
  1445. services="${action_posargs[0]}"
  1446. else
  1447. services="$(get_default_target_services "${action_posargs[@]}")"
  1448. fi
  1449. ;;
  1450. esac
  1451. get_docker_compose $services >/dev/null || { ## precalculate variable \$_current_docker_compose
  1452. err "Fails to compile base 'docker-conmpose.conf'"
  1453. exit 1
  1454. }
  1455. ##
  1456. ## Pre-action
  1457. ##
  1458. full_init=
  1459. case "$action" in
  1460. up|run)
  1461. full_init=true
  1462. ;;
  1463. "")
  1464. full_init=
  1465. ;;
  1466. *)
  1467. if [ "$is_service_action" ]; then
  1468. full_init=true
  1469. fi
  1470. ;;
  1471. esac
  1472. if [ "$full_init" ]; then
  1473. ## init in order
  1474. Section initialisation
  1475. if [ -z "$no_init" ]; then
  1476. run_service_hook "$services" init || exit 1
  1477. fi
  1478. ## Get relations
  1479. if [ -z "$no_relations" ]; then
  1480. run_service_relations "$services" || exit 1
  1481. fi
  1482. ## XXXvlab: to be removed when all relation and service stuff is resolved
  1483. if [ -z "$no_hooks" ]; then
  1484. ordered_services=$(get_ordered_service_dependencies $services) || exit 1
  1485. for service in $ordered_services; do
  1486. charm=$(get_service_charm "$service") || exit 1
  1487. for script in "$CHARM_STORE/$charm/hooks.d/"*.sh; do
  1488. [ -e "$script" ] || continue
  1489. [ -x "$script" ] || { echo "compose: script $script is not executable." >&2; exit 1; }
  1490. (
  1491. debug "Launching '$script'."
  1492. cd "$(dirname "$script)")";
  1493. "$script" "$@"
  1494. ) || { echo "compose: hook $script failed. Stopping." >&2; exit 1; }
  1495. done
  1496. done
  1497. fi
  1498. fi
  1499. export SERVICE_PACK="$services"
  1500. ##
  1501. ## Docker-compose
  1502. ##
  1503. case "$action" in
  1504. up|start|stop|build)
  1505. master_services=$(get_master_services $SERVICE_PACK) || exit 1
  1506. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" $master_services
  1507. ;;
  1508. run)
  1509. master_service=$(get_master_services $SERVICE_PACK) || exit 1
  1510. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  1511. ;;
  1512. # enter)
  1513. # master_service=$(get_master_services $SERVICE_PACK) || exit 1
  1514. # [ "${remainder_args[*]}" ] || remainder_args=("/bin/bash" "-c" "export TERM=xterm; exec bash")
  1515. # docker exec -ti "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  1516. # ;;
  1517. config)
  1518. ## removing the services
  1519. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  1520. warn "Runtime configuration modification (from relations) are not included here."
  1521. ;;
  1522. *)
  1523. if [ "$is_service_action" ]; then
  1524. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  1525. else
  1526. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  1527. fi
  1528. ;;
  1529. esac