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.

1994 lines
66 KiB

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