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.

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