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.

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