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.

2012 lines
66 KiB

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