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.

1945 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. cat "$metadata_file"
  1198. }
  1199. export -f get_charm_metadata
  1200. ##
  1201. ## The result is a mixin that is not always a complete valid
  1202. ## docker-compose entry (thinking of subordinates). The result
  1203. ## will be merge with master charms.
  1204. _get_docker_compose_mixin_from_metadata_cached() {
  1205. local charm="$1" metadata="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1206. metadata_file metadata volumes docker_compose subordinate image
  1207. if [ -e "$cache_file" ]; then
  1208. #debug "$FUNCNAME: STATIC cache hit $1"
  1209. cat "$cache_file"
  1210. touch "$cache_file"
  1211. return 0
  1212. fi
  1213. mixin=
  1214. if [ "$metadata" ]; then
  1215. ## resources to volumes
  1216. volumes=$(
  1217. for resource_type in data config; do
  1218. while read-0 resource; do
  1219. eval "echo \" - \$${resource_type^^}STORE/\$charm\$resource:\$resource:rw\""
  1220. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1221. done
  1222. while read-0 resource; do
  1223. if [[ "$resource" == *:* ]]; then
  1224. echo " - $resource:rw"
  1225. else
  1226. echo " - $resource:$resource:rw"
  1227. fi
  1228. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1229. while read-0 resource; do
  1230. echo " - $CHARM_STORE/$charm/resources$resource:$resource:rw"
  1231. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1232. ) || return 1
  1233. if [ "$volumes" ]; then
  1234. mixin=$(echo -en "volumes:\n$volumes")
  1235. fi
  1236. docker_compose=$(echo "$metadata" | shyaml get-value "docker-compose" 2>/dev/null)
  1237. if [ "$docker_compose" ]; then
  1238. mixin=$(merge_yaml_str "$mixin" "$docker_compose")
  1239. fi
  1240. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1241. subordinate=true
  1242. fi
  1243. fi
  1244. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1245. image_or_build_statement=
  1246. if [ "$image" ]; then
  1247. if [ "$subordinate" ]; then
  1248. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1249. return 1
  1250. fi
  1251. image_or_build_statement="image: $image"
  1252. elif [ -d "$CHARM_STORE/$charm/build" ]; then
  1253. if [ "$subordinate" ]; then
  1254. err "Subordinate charm can not have a 'build' sub directory."
  1255. return 1
  1256. fi
  1257. image_or_build_statement="build: $charm/build"
  1258. fi
  1259. if [ "$image_or_build_statement" ]; then
  1260. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1261. fi
  1262. echo "$mixin" | tee "$cache_file"
  1263. }
  1264. export -f _get_docker_compose_mixin_from_metadata_cached
  1265. get_docker_compose_mixin_from_metadata() {
  1266. local charm="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1267. if [ -e "$cache_file" ]; then
  1268. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1269. cat "$cache_file"
  1270. return 0
  1271. fi
  1272. metadata="$(get_charm_metadata "$charm")" || return 1
  1273. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$charm" "$metadata") || return 1
  1274. echo "$mixin" | tee "$cache_file"
  1275. }
  1276. export -f get_docker_compose_mixin_from_metadata
  1277. _save() {
  1278. local name="$1"
  1279. cat - | tee -a "$docker_compose_dir/.data/$name"
  1280. }
  1281. export -f _save
  1282. get_default_project_name() {
  1283. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1284. echo "$DEFAULT_PROJECT_NAME"
  1285. return 0
  1286. fi
  1287. compose_yml_location="$(get_compose_yml_location)" || return 1
  1288. if [ "$compose_yml_location" ]; then
  1289. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1290. echo "$(basename "$(dirname "$normalized_path")")"
  1291. return 0
  1292. fi
  1293. fi
  1294. echo "project"
  1295. return 0
  1296. }
  1297. export -f get_default_project_name
  1298. launch_docker_compose() {
  1299. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1300. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1301. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1302. # rm -rf \"$docker_compose_tmpdir\""
  1303. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1304. project=$(get_default_project_name)
  1305. mkdir -p "$docker_compose_tmpdir/$project"
  1306. docker_compose_dir="$docker_compose_tmpdir/$project"
  1307. if [ -z "$SERVICE_PACK" ]; then
  1308. export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1309. fi
  1310. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1311. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1312. # debug "Merging some config data in docker-compose.yml:"
  1313. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1314. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1315. fi
  1316. ## XXXvlab: could be more specific and only link the needed charms
  1317. ln -sf "$CHARM_STORE/"* "$docker_compose_dir/"
  1318. mkdir "$docker_compose_dir/.data"
  1319. {
  1320. {
  1321. cd "$docker_compose_dir"
  1322. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL"
  1323. debug "$(cat "$docker_compose_dir/docker-compose.yml")"
  1324. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1325. docker-compose "$@"
  1326. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1327. } | _save stdout
  1328. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1329. 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
  1330. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1331. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1332. fi
  1333. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl")"
  1334. if [ -z "docker_compose_dir" ]; then
  1335. err "Something went wrong before you could gather docker-compose errorlevel."
  1336. return 1
  1337. fi
  1338. return "$docker_compose_errlvl"
  1339. }
  1340. export -f launch_docker_compose
  1341. get_compose_yml_location() {
  1342. parent=$(while ! [ -e "./compose.yml" ]; do
  1343. [ "$PWD" == "/" ] && exit 0
  1344. cd ..
  1345. done; echo "$PWD"
  1346. )
  1347. if [ "$parent" ]; then
  1348. echo "$parent/compose.yml"
  1349. return 0
  1350. fi
  1351. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1352. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1353. err "No 'compose.yml' was found in current or parent dirs," \
  1354. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file."
  1355. die "Please provide a 'compose.yml' file."
  1356. fi
  1357. echo "$DEFAULT_COMPOSE_FILE"
  1358. return 0
  1359. fi
  1360. err "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1361. die "Please provide a 'compose.yml' file."
  1362. return 1
  1363. }
  1364. export -f get_compose_yml_location
  1365. get_default_target_services() {
  1366. local services=("$@")
  1367. if [ -z "${services[*]}" ]; then
  1368. if [ "$DEFAULT_SERVICES" ]; then
  1369. info "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1370. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1371. services="$DEFAULT_SERVICES"
  1372. else
  1373. err "No service provided."
  1374. return 1
  1375. fi
  1376. fi
  1377. echo "${services[*]}"
  1378. }
  1379. export -f get_default_target_services
  1380. get_master_services() {
  1381. local loaded master_service
  1382. declare -A loaded
  1383. for service in "$@"; do
  1384. master_service=$(get_top_master_charm_for_service "$service") || return 1
  1385. if [ "${loaded[$master_service]}" ]; then
  1386. continue
  1387. fi
  1388. echo "$master_service"
  1389. loaded["$master_service"]=1
  1390. done | xargs echo
  1391. }
  1392. export -f get_master_services
  1393. _setup_state_dir() {
  1394. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1395. #debug "Creating temporary state directory in '$state_tmpdir'."
  1396. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1397. # rm -rf \"$state_tmpdir\""
  1398. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1399. }
  1400. get_docker_compose_opts_list() {
  1401. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1402. if [ -e "$cache_file" ]; then
  1403. debug "$FUNCNAME: cache hit ($*)"
  1404. cat "$cache_file"
  1405. return 0
  1406. fi
  1407. docker-compose "$@" --help | grep '^Options:' -A 20000 |
  1408. tail -n +2 |
  1409. egrep "^\s+-" |
  1410. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  1411. tee "$cache_file"
  1412. }
  1413. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  1414. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  1415. get_docker_compose_multi_opts_list() {
  1416. opts_list=$(get_docker_compose_opts_list "$@")
  1417. echo "$opts_list" | egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1418. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  1419. tr ',' "\n" | xargs echo
  1420. }
  1421. get_docker_compose_single_opts_list() {
  1422. opts_list=$(get_docker_compose_opts_list "$@")
  1423. echo "$opts_list" | egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  1424. tr ',' "\n" | xargs echo
  1425. }
  1426. clean_cache() {
  1427. local i=0
  1428. for f in $(ls -t "$CACHEDIR/"*.cache.* | tail -n +500); do
  1429. ((i++))
  1430. rm -f "$f"
  1431. done
  1432. if (( i > 0 )); then
  1433. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  1434. fi
  1435. }
  1436. [ "$SOURCED" ] && return 0
  1437. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  1438. if [ -r /etc/default/charm ]; then
  1439. . /etc/default/charm
  1440. fi
  1441. if [ -r "/etc/default/$exname" ]; then
  1442. . "/etc/default/$exname"
  1443. fi
  1444. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  1445. ## userdir ? and global /etc/compose.yml ?
  1446. . /etc/compose.conf || exit 1
  1447. . /etc/compose.local.conf || exit 1
  1448. fi
  1449. _setup_state_dir
  1450. ##
  1451. ## Argument parsing
  1452. ##
  1453. remainder_args=()
  1454. compose_opts=()
  1455. action_opts=()
  1456. no_hooks=
  1457. no_init=
  1458. action=
  1459. stage="main" ## switches from 'main', to 'action', 'remainder'
  1460. # DC_MATCH_MULTI=
  1461. # DC_MATCH_SINGLE=
  1462. while [ "$#" != 0 ]; do
  1463. case "$stage" in
  1464. "main")
  1465. case "$1" in
  1466. --help|-h)
  1467. no_init=true ; no_hooks=true ; no_relations=true
  1468. compose_opts+=("$1")
  1469. ;;
  1470. --verbose|-v)
  1471. export VERBOSE=true
  1472. compose_opts+=("$1")
  1473. ;;
  1474. -f)
  1475. [ -e "$2" ] || die "File $2 doesn't exists"
  1476. export DEFAULT_COMPOSE_FILE="$2"
  1477. shift
  1478. ;;
  1479. -p)
  1480. export DEFAULT_PROJECT_NAME="$2"
  1481. shift
  1482. ;;
  1483. --no-relations)
  1484. export no_relations=true
  1485. ;;
  1486. --no-hooks)
  1487. export no_hooks=true
  1488. ;;
  1489. --no-init)
  1490. export no_init=true
  1491. ;;
  1492. --debug)
  1493. export DEBUG=true
  1494. export VERBOSE=true
  1495. ;;
  1496. --*|-*)
  1497. compose_opts+=("$1")
  1498. ;;
  1499. *)
  1500. action="$1"
  1501. stage="action"
  1502. # DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") || return 1
  1503. # DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action") $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  1504. ;;
  1505. esac
  1506. ;;
  1507. "action")
  1508. case "$1" in
  1509. --help|-h)
  1510. no_init=true ; no_hooks=true ; no_relations=true
  1511. action_opts+=("$1")
  1512. ;;
  1513. --verbose|-v)
  1514. export VERBOSE=true
  1515. action_opts+=("$1")
  1516. ;;
  1517. --*|-*)
  1518. action_opts+=("$1")
  1519. ;;
  1520. *)
  1521. action_posargs+=("$1")
  1522. stage="remainder"
  1523. ;;
  1524. esac
  1525. ;;
  1526. "remainder")
  1527. remainder_args+=("$@")
  1528. break 3;;
  1529. esac
  1530. shift
  1531. done
  1532. [ "${compose_opts[*]}" ] && debug "Main docker-compose opts: ${compose_opts[*]}"
  1533. [ "${action_opts[*]}" ] && debug "Action '$action' opts: ${action_opts[*]}"
  1534. [ "${remainder_args[*]}" ] && debug "Remainder args: ${remainder_args[*]}"
  1535. ##
  1536. ## Actual code
  1537. ##
  1538. export CHARM_STORE=${CHARM_STORE:-/srv/charm-store}
  1539. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  1540. export COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  1541. debug "Found 'compose.yml' file in '$COMPOSE_YML_FILE'."
  1542. output=$(shyaml get-value < "$COMPOSE_YML_FILE" 2>&1)
  1543. if [ "$?" != 0 ]; then
  1544. err "Invalid YAML in '$COMPOSE_YML_FILE':"
  1545. while IFS='' read -r line1 && IFS='' read -r line2; do
  1546. echo "$line1 $GRAY($line2)$NORMAL"
  1547. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  1548. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  1549. prefix " $GRAY|$NORMAL "
  1550. exit 1
  1551. fi
  1552. if ! [ -d "$CHARM_STORE" ]; then
  1553. err "Charm store path $YELLOW$CHARM_STORE$NORMAL does not exists. "
  1554. err "Please check your $YELLOW\$CHARM_STORE$NORMAL variable value."
  1555. exit 1
  1556. fi
  1557. if [ -z "$(cd "$CHARM_STORE"; ls)" ]; then
  1558. err "no available charms in charm store $YELLOW$CHARM_STORE$NORMAL. Either:"
  1559. err " - check $YELLOW\$CHARM_STORE$NORMAL variable value"
  1560. err " - download charms in $CHARM_STORE"
  1561. print_error "Charm store is empty. Cannot continue."
  1562. fi
  1563. ##
  1564. ## Get services in command line.
  1565. ##
  1566. is_service_action=
  1567. case "$action" in
  1568. up|build|start|stop|config)
  1569. services="$(get_default_target_services "${action_posargs[@]}")" || exit 1
  1570. orig_services="${action_posargs[@]:1}"
  1571. ;;
  1572. run)
  1573. services="${action_posargs[0]}"
  1574. ;;
  1575. "")
  1576. services=
  1577. ;;
  1578. *)
  1579. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  1580. debug "Found action $DARKCYAN$action$NORMAL in service $DARKYELLOW${action_posargs[0]}$NORMAL"
  1581. services="${action_posargs[0]}"
  1582. else
  1583. services="$(get_default_target_services "${action_posargs[@]}")"
  1584. fi
  1585. ;;
  1586. esac
  1587. get_docker_compose $services >/dev/null || { ## precalculate variable \$_current_docker_compose
  1588. err "Fails to compile base 'docker-compose.conf'"
  1589. exit 1
  1590. }
  1591. ##
  1592. ## Pre-action
  1593. ##
  1594. full_init=
  1595. case "$action" in
  1596. up|run)
  1597. full_init=true
  1598. ;;
  1599. "")
  1600. full_init=
  1601. ;;
  1602. *)
  1603. if [ "$is_service_action" ]; then
  1604. full_init=true
  1605. fi
  1606. ;;
  1607. esac
  1608. if [ "$full_init" ]; then
  1609. ## init in order
  1610. Section initialisation
  1611. if [ -z "$no_init" ]; then
  1612. run_service_hook "$services" init || exit 1
  1613. fi
  1614. ## Get relations
  1615. if [ -z "$no_relations" ]; then
  1616. run_service_relations "$services" || exit 1
  1617. fi
  1618. ## XXXvlab: to be removed when all relation and service stuff is resolved
  1619. if [ -z "$no_hooks" ]; then
  1620. ordered_services=$(get_ordered_service_dependencies $services) || exit 1
  1621. for service in $ordered_services; do
  1622. charm=$(get_service_charm "$service") || exit 1
  1623. for script in "$CHARM_STORE/$charm/hooks.d/"*.sh; do
  1624. [ -e "$script" ] || continue
  1625. [ -x "$script" ] || { echo "compose: script $script is not executable." >&2; exit 1; }
  1626. (
  1627. debug "Launching '$script'."
  1628. cd "$(dirname "$script)")";
  1629. "$script" "$@"
  1630. ) || { echo "compose: hook $script failed. Stopping." >&2; exit 1; }
  1631. done
  1632. done
  1633. fi
  1634. fi
  1635. export SERVICE_PACK="$services"
  1636. ##
  1637. ## Docker-compose
  1638. ##
  1639. case "$action" in
  1640. up|start|stop|build)
  1641. master_services=$(get_master_services $SERVICE_PACK) || exit 1
  1642. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" $master_services
  1643. ;;
  1644. run)
  1645. master_service=$(get_master_services $SERVICE_PACK) || exit 1
  1646. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  1647. ;;
  1648. # enter)
  1649. # master_service=$(get_master_services $SERVICE_PACK) || exit 1
  1650. # [ "${remainder_args[*]}" ] || remainder_args=("/bin/bash" "-c" "export TERM=xterm; exec bash")
  1651. # docker exec -ti "${action_opts[@]}" "$master_service" "${remainder_args[@]}"
  1652. # ;;
  1653. config)
  1654. ## removing the services
  1655. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  1656. warn "Runtime configuration modification (from relations) are not included here."
  1657. ;;
  1658. *)
  1659. if [ "$is_service_action" ]; then
  1660. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  1661. else
  1662. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  1663. fi
  1664. ;;
  1665. esac