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.

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