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.

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