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.

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