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.

3091 lines
103 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
  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. ## - Be clear about when the SERVICE name is used and the CHARM name is used.
  26. ## - in case of service contained in another container
  27. ## - in normal case
  28. ## - in docker-compose, can't use charm name: if we want 2 instances of the same charm
  29. ## we are stuck. What will be unique is the name of the service.
  30. ## - some relations are configured in compose.yml but should not trigger the loading
  31. ## of necessary component (for instance, apache --> log-rotate), if log-rotate is
  32. ## not there, this link should considered optional.
  33. ## - Could probably allow an unexistent charm to be populated with only "docker-image:"
  34. ## of the same name. Although this should trigger a visible warning.
  35. #:-
  36. [ -e /etc/shlib ] && . /etc/shlib || {
  37. echo "Unsatisfied dependency. Please install 'kal-shlib-core'."
  38. exit 1
  39. }
  40. #:-
  41. include common
  42. include pretty
  43. include parse
  44. include charm
  45. include array
  46. include cla
  47. depends shyaml docker
  48. version=0.1
  49. usage="$exname [COMPOSE_OPTS] [ACTION [ACTION_OPTS]]"
  50. help="\
  51. $WHITE$exname$NORMAL jobs is to run various shell scripts to build
  52. a running orchestrated and configured docker containers. These shell
  53. scripts will have the opportunity to build a 'docker-compose.yml'.
  54. Once init script and relations scripts are executed, $WHITE$exname$NORMAL
  55. delegate the launching to ${WHITE}docker-compose${NORMAL} by providing it
  56. the final 'docker-compose.yml'.
  57. $WHITE$exname$NORMAL also leverage charms to offer some additional custom
  58. actions per charm, which are simply other scripts that can be
  59. run without launching ${WHITE}docker-compose${NORMAL}.
  60. In compose message, color coding is enforced as such:
  61. - ${DARKCYAN}action$NORMAL,
  62. - ${DARKBLUE}relation$NORMAL,
  63. - ${DARKPINK}charm${NORMAL},
  64. - ${DARKYELLOW}service${NORMAL},
  65. - ${WHITE}option-name${NORMAL}/${WHITE}command-name${NORMAL}/${WHITE}Section-Title${NORMAL}
  66. $WHITE$exname$NORMAL reads '/etc/compose.conf' for global variables, and
  67. '/etc/compose.local.conf' for local host adjustements.
  68. "
  69. ## XXXvlab: this doesn't seem to work when 'compose' is called in
  70. ## a hook of a charm.
  71. #[[ "${BASH_SOURCE[0]}" == "" ]] && SOURCED=true
  72. $(return >/dev/null 2>&1) && SOURCED=true
  73. if [ "$UID" == 0 ]; then
  74. CACHEDIR=${CACHEDIR:-/var/cache/compose}
  75. VARDIR=${VARDIR:-/var/lib/compose}
  76. else
  77. [ "$XDG_CONFIG_HOME" ] && CACHEDIR=${CACHEDIR:-$XDG_CONFIG_HOME/compose}
  78. [ "$XDG_DATA_HOME" ] && VARDIR=${VARDIR:-$XDG_DATA_HOME/compose}
  79. CACHEDIR=${CACHEDIR:-$HOME/.cache/compose}
  80. VARDIR=${VARDIR:-$HOME/.local/share/compose}
  81. fi
  82. export VARDIR CACHEDIR
  83. md5_compat() { md5sum | cut -c -32; }
  84. quick_cat_file() { quick_cat_stdin < "$1"; }
  85. quick_cat_stdin() { local IFS=''; while read -r line; do echo "$line"; done ; }
  86. export -f quick_cat_file quick_cat_stdin md5_compat
  87. clean_cache() {
  88. local i=0
  89. for f in $(ls -t "$CACHEDIR/"*.cache.* 2>/dev/null | tail -n +500); do
  90. ((i++))
  91. rm -f "$f"
  92. done
  93. if (( i > 0 )); then
  94. debug "${WHITE}Cleaned cache:${NORMAL} Removed $((i)) elements (current cache size is $(du -sh "$CACHEDIR" | cut -f 1))"
  95. fi
  96. }
  97. usage="$exname SERVICE"'
  98. Deploy and manage a swarm of containers to provide services based on
  99. a ``compose.yml`` definition and charms from a ``charm-store``.
  100. '
  101. export DEFAULT_COMPOSE_FILE
  102. ##
  103. ## Merge YAML files
  104. ##
  105. export _merge_yaml_common_code="
  106. import sys
  107. import yaml
  108. try:
  109. # included in standard lib from Python 2.7
  110. from collections import OrderedDict
  111. except ImportError:
  112. # try importing the backported drop-in replacement
  113. # it's available on PyPI
  114. from ordereddict import OrderedDict
  115. ## Ensure that there are no collision with legacy OrderedDict
  116. ## that could be used for omap for instance.
  117. class MyOrderedDict(OrderedDict):
  118. pass
  119. yaml.add_representer(
  120. MyOrderedDict,
  121. lambda cls, data: cls.represent_dict(data.items()))
  122. yaml.add_constructor(
  123. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  124. lambda cls, node: MyOrderedDict(cls.construct_pairs(node)))
  125. def fc(filename):
  126. with open(filename) as f:
  127. return f.read()
  128. def merge(*args):
  129. # sys.stderr.write('%r\n' % (args, ))
  130. args = [arg for arg in args if arg is not None]
  131. if len(args) == 0:
  132. return None
  133. if len(args) == 1:
  134. return args[0]
  135. if all(isinstance(arg, (int, basestring, bool)) for arg in args):
  136. return args[-1]
  137. elif all(isinstance(arg, list) for arg in args):
  138. res = []
  139. for arg in args:
  140. for elt in arg:
  141. if elt in res:
  142. res.remove(elt)
  143. res.append(elt)
  144. return res
  145. elif all(isinstance(arg, dict) for arg in args):
  146. keys = set()
  147. for arg in args:
  148. keys |= set(arg.keys())
  149. dct = {}
  150. for key in keys:
  151. sub_args = []
  152. for arg in args:
  153. if key in arg:
  154. sub_args.append(arg)
  155. try:
  156. dct[key] = merge(*(a[key] for a in sub_args))
  157. except NotImplementedError as e:
  158. raise NotImplementedError(
  159. e.args[0],
  160. '%s.%s' % (key, e.args[1]) if e.args[1] else key,
  161. e.args[2])
  162. if dct[key] is None:
  163. del dct[key]
  164. return dct
  165. else:
  166. raise NotImplementedError(
  167. 'Unsupported types: %s'
  168. % (', '.join(list(set(arg.__class__.__name__ for arg in args)))), '', args)
  169. return None
  170. def merge_cli(*args):
  171. try:
  172. c = merge(*args)
  173. except NotImplementedError as e:
  174. sys.stderr.write('Merging Failed: %s.\n%s\n'
  175. ' Values are:\n %s\n'
  176. % (e.args[0],
  177. ' Conflicting key is %r.' % e.args[1] if e.args[1] else
  178. ' Conflict at base of structure.',
  179. '\\n '.join('v%d: %r' % (i, a)
  180. for i, a in enumerate(e.args[2]))))
  181. exit(1)
  182. if c is not None:
  183. print '%s' % yaml.dump(c, default_flow_style=False)
  184. "
  185. merge_yaml() {
  186. if ! [ -r "$state_tmpdir/merge_yaml.py" ]; then
  187. cat <<EOF > "$state_tmpdir/merge_yaml.py"
  188. $_merge_yaml_common_code
  189. merge_cli(*(yaml.load(fc(f)) for f in sys.argv[1:]))
  190. EOF
  191. fi
  192. python "$state_tmpdir/merge_yaml.py" "$@"
  193. }
  194. export -f merge_yaml
  195. merge_yaml_str() {
  196. local entries="$@"
  197. if ! [ -r "$state_tmpdir/merge_yaml_str.py" ]; then
  198. cat <<EOF > "$state_tmpdir/merge_yaml_str.py" || return 1
  199. $_merge_yaml_common_code
  200. merge_cli(*(yaml.load(f) for f in sys.argv[1:]))
  201. EOF
  202. fi
  203. python "$state_tmpdir/merge_yaml_str.py" "$@"
  204. }
  205. export -f merge_yaml_str
  206. yaml_key_val_str() {
  207. local entries="$@"
  208. if ! [ -r "$state_tmpdir/yaml_key_val_str.py" ]; then
  209. cat <<EOF > "$state_tmpdir/yaml_key_val_str.py"
  210. $_merge_yaml_common_code
  211. print '%s' % yaml.dump({
  212. yaml.load(sys.argv[1]):
  213. yaml.load(sys.argv[2])}, default_flow_style=False)
  214. EOF
  215. fi
  216. python "$state_tmpdir/yaml_key_val_str.py" "$@"
  217. }
  218. export -f yaml_key_val_str
  219. ##
  220. ## Docker
  221. ##
  222. docker_has_image() {
  223. local image="$1"
  224. images=$(docker images -q "$image" 2>/dev/null) || {
  225. err "docker images call has failed unexpectedly."
  226. return 1
  227. }
  228. [ "$images" ]
  229. }
  230. export -f docker_has_image
  231. cmd_on_base_image() {
  232. local service="$1" base_image
  233. shift
  234. base_image=$(service_base_docker_image "$service") || return 1
  235. docker run -i --entrypoint /bin/bash "$base_image" -c "$*"
  236. }
  237. export -f cmd_on_base_image
  238. cached_cmd_on_base_image() {
  239. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  240. shift
  241. if [ -e "$cache_file" ]; then
  242. # debug "$FUNCNAME: cache hit ($*)"
  243. quick_cat_stdin < "$cache_file"
  244. return 0
  245. fi
  246. result=$(cmd_on_base_image "$service" "$@") || return 1
  247. echo "$result" | tee "$cache_file"
  248. }
  249. export -f cached_cmd_on_base_image
  250. image_exposed_ports_0() {
  251. local image="$1"
  252. docker inspect --format='{{range $p, $conf := .Config.ExposedPorts}}{{$p}}{{"\x00"}}{{end}}' "$image"
  253. }
  254. export -f image_exposed_ports_0
  255. ##
  256. ## Generic
  257. ##
  258. fn.exists() {
  259. declare -F "$1" >/dev/null
  260. }
  261. str_pattern_matches() {
  262. local str="$1"
  263. shift
  264. for pattern in "$@"; do
  265. eval "[[ \"$str\" == $pattern ]]" && return 0
  266. done
  267. return 1
  268. }
  269. str_matches() {
  270. local str="$1"
  271. shift
  272. for pattern in "$@"; do
  273. [[ "$str" == "$pattern" ]] && return 0
  274. done
  275. return 1
  276. }
  277. gen_password() {
  278. local l=( {a..z} {A..Z} {0..9} ) nl="${#l[@]}" size=${1:-16}
  279. while ((size--)); do
  280. echo -n "${l[$((RANDOM * nl / 32768))]}"
  281. done
  282. echo
  283. }
  284. export -f gen_password
  285. file_put() {
  286. local TARGET="$1"
  287. mkdir -p "$(dirname "$TARGET")" &&
  288. cat - > "$TARGET"
  289. }
  290. export -f file_put
  291. file_put_0() {
  292. local TARGET="$1"
  293. mkdir -p "$(dirname "$TARGET")" &&
  294. cat > "$TARGET"
  295. }
  296. export -f file_put_0
  297. fetch_file() {
  298. local src="$1"
  299. case "$src" in
  300. *"://"*)
  301. err "Unsupported target scheme."
  302. return 1
  303. ;;
  304. *)
  305. ## Try direct
  306. if ! [ -r "$src" ]; then
  307. err "File '$src' not found/readable."
  308. return 1
  309. fi
  310. cat "$src" || return 1
  311. ;;
  312. esac
  313. }
  314. export -f fetch_file
  315. ## receives stdin content to decompress on stdout
  316. ## stdout content should be tar format.
  317. uncompress_file() {
  318. local filename="$1"
  319. ## Warning, the content of the file is already as stdin, the filename
  320. ## is there to hint for correct decompression.
  321. case "$filename" in
  322. *".gz")
  323. gunzip
  324. ;;
  325. *".bz2")
  326. bunzip2
  327. ;;
  328. *)
  329. cat
  330. ;;
  331. esac
  332. }
  333. export -f uncompress_file
  334. get_file() {
  335. local src="$1"
  336. fetch_file "$src" | uncompress_file "$src"
  337. }
  338. export -f get_file
  339. ##
  340. ## Common database lib
  341. ##
  342. _clean_docker() {
  343. local _DB_NAME="$1" container_id="$2"
  344. (
  345. set +e
  346. debug "Removing container $_DB_NAME"
  347. docker stop "$container_id"
  348. docker rm "$_DB_NAME"
  349. docker network rm "${_DB_NAME}"
  350. rm -vf "/tmp/${_DB_NAME}.state"
  351. )
  352. }
  353. export -f _clean_docker
  354. get_service_base_image_dir_uid_gid() {
  355. local service="$1" dir="$2" uid_gid
  356. uid_gid=$(cached_cmd_on_base_image "$service" "stat -c '%u %g' '$dir'") || {
  357. debug "Failed to query '$dir' uid in ${DARKYELLOW}$service${NORMAL} base image."
  358. return 1
  359. }
  360. info "uid and gid from ${DARKYELLOW}$service${NORMAL}:$dir is '$uid_gid'"
  361. echo "$uid_gid"
  362. }
  363. export -f get_service_base_image_dir_uid_gid
  364. get_service_type() {
  365. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  366. if [ -z "$service" ]; then
  367. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  368. return 1
  369. fi
  370. if [ -e "$cache_file" ]; then
  371. # debug "$FUNCNAME: cache hit ($*)"
  372. cat "$cache_file"
  373. return 0
  374. fi
  375. charm=$(get_service_charm "$service") || return 1
  376. metadata=$(charm.metadata "$charm") || return 1
  377. printf "%s" "$metadata" | shyaml get-value type service 2>/dev/null |
  378. tee "$cache_file"
  379. }
  380. are_files_locked_in_dir() {
  381. local dir="$1" device hdev ldev
  382. device=$(stat -c %d "$dir") || {
  383. err "Can't stat %d."
  384. return 1
  385. }
  386. device=$(printf "%04x" $device)
  387. hdev=${device:0:2}
  388. ldev=${device:2:2}
  389. inodes=$(find "$dir" -printf ':%i:\n')
  390. found=
  391. while read -r inode; do
  392. debug "try inode:$inode"
  393. if [[ "$inodes" == *":$inode:"* ]]; then
  394. found=1
  395. break
  396. fi
  397. done < <(cat /proc/locks | grep " $hdev:$ldev:" | sed -r "s/^.*$hdev:$ldev:([0-9]+).*$/\1/g")
  398. [ "$found" ]
  399. }
  400. export -f are_files_locked_in_dir
  401. export _PID="$$"
  402. ensure_db_docker_running () {
  403. local _STATE_FILE
  404. _DB_NAME="db_${DB_NAME}_${_PID}"
  405. _STATE_FILE=/tmp/${_DB_NAME}.state
  406. if [ -e "$_STATE_FILE" ]; then
  407. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$(cat "$_STATE_FILE")"
  408. debug "Re-using previous docker/connection '$DOCKER_IP'."
  409. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  410. return 0
  411. fi
  412. if [ -e "/tmp/${_DB_NAME}.working" ]; then
  413. ## avoid recursive calls.
  414. if [ -z "$DOCKER_IP" ]; then
  415. err "Currently figuring up DOCKER_IP, please set it yourself before this call if needed."
  416. return 1
  417. else
  418. debug "ignoring recursive call of 'ensure_db_docker_running'."
  419. fi
  420. return 0
  421. fi
  422. touch "/tmp/${_DB_NAME}.working"
  423. docker rm "$_DB_NAME" 2>/dev/null || true
  424. host_db_working_dir="$DATASTORE/${SERVICE_NAME}$DB_DATADIR"
  425. if is_db_locked; then
  426. info "Some process is using '$host_db_working_dir'. Trying to find a docker that would do this..."
  427. found=
  428. for docker_id in $(docker ps -q); do
  429. has_volume_mounted=$(
  430. docker inspect \
  431. --format "{{range .Mounts}}{{if eq .Destination \"$DB_DATADIR\"}}{{.Source}}{{end}}{{end}}" \
  432. "$docker_id")
  433. if [ "$has_volume_mounted" == "$host_db_working_dir" ]; then
  434. found="$docker_id"
  435. break
  436. fi
  437. done
  438. if [ -z "$found" ]; then
  439. err "Please shutdown any other docker using this directory."
  440. return 1
  441. fi
  442. export container_id="$found"
  443. info "Found docker $docker_id is already running."
  444. else
  445. verb "Database is not locked."
  446. if ! docker_has_image "$DOCKER_BASE_IMAGE"; then
  447. docker pull "$DOCKER_BASE_IMAGE"
  448. fi
  449. docker_opts=
  450. if [ -f "$DB_PASSFILE" ]; then
  451. verb "Found and using '$DB_PASSFILE'."
  452. docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  453. fi
  454. debug docker network create "$_DB_NAME"
  455. if ! network_id=$(docker network create "$_DB_NAME"); then
  456. err "'docker network create' failed !"
  457. _clean_docker "$_DB_NAME" "$container_id"
  458. rm "/tmp/${_DB_NAME}.working"
  459. return 1
  460. fi
  461. debug docker run -d \
  462. --name "$_DB_NAME" \
  463. $docker_opts \
  464. --network "$_DB_NAME" \
  465. -v "$host_db_working_dir:$DB_DATADIR" \
  466. "$DOCKER_BASE_IMAGE"
  467. if ! container_id=$(
  468. docker run -d \
  469. --name "$_DB_NAME" \
  470. $docker_opts \
  471. --network "$_DB_NAME" \
  472. -v "$host_db_working_dir:$DB_DATADIR" \
  473. "$DOCKER_BASE_IMAGE"
  474. ); then
  475. err "'docker run' failed !"
  476. _clean_docker "$_DB_NAME" "$container_id"
  477. rm "/tmp/${_DB_NAME}.working"
  478. return 1
  479. fi
  480. trap_add EXIT,ERR "_clean_docker \"$_DB_NAME\" \"$container_id\""
  481. fi
  482. if docker_ip=$(wait_for_docker_ip "$container_id"); then
  483. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  484. echo "$docker_ip" > "$_STATE_FILE"
  485. debug "written '$_STATE_FILE'"
  486. rm "/tmp/${_DB_NAME}.working"
  487. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  488. return 0
  489. else
  490. errlvl="$?"
  491. err "Db not found (errlvl: $errlvl). Tail of docker logs follows:"
  492. docker logs --tail=5 "$container_id" 2>&1 | prefix " | " >&2
  493. rm "/tmp/${_DB_NAME}.working"
  494. return "$errlvl"
  495. fi
  496. }
  497. export -f ensure_db_docker_running
  498. ## Require to set $db_docker_opts if needed, and $DB_PASSFILE
  499. ##
  500. _dcmd() {
  501. local docker_opts command="$1"
  502. shift
  503. debug "Db> $command $@"
  504. if [ -f "$DB_PASSFILE" ]; then
  505. verb "Found and using '$DB_PASSFILE'."
  506. db_docker_opts="$db_docker_opts -v $SERVER_ROOT_PREFIX$DB_PASSFILE:$DB_PASSFILE"
  507. fi
  508. ## XXXX was here: actualy, we need only connection between this version and the client version
  509. debug docker run -i --rm \
  510. $db_docker_opts \
  511. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  512. docker run -i --rm \
  513. $db_docker_opts \
  514. --entrypoint "$command" "$DOCKER_BASE_IMAGE" $db_cmd_opts "$@"
  515. }
  516. export -f _dcmd
  517. ## Executes code through db
  518. dcmd() {
  519. local fun
  520. [ "$DB_NAME" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_NAME."
  521. [ "$DB_DATADIR" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_DATADIR."
  522. # [ "$DB_PASSFILE" ] || print_syntax_error "$FUNCNAME: You must provide \$DB_PASSFILE."
  523. [ "$_PID" ] || print_syntax_error "$FUNCNAME: You must provide \$_PID."
  524. for fun in is_db_locked _set_db_params ddb; do
  525. [ "$(type -t "$fun")" == "function" ] ||
  526. print_syntax_error "$FUNCNAME: You must provide function '$fun'."
  527. done
  528. ensure_db_docker_running </dev/null || return 1
  529. _dcmd "$@"
  530. }
  531. export -f dcmd
  532. get_docker_ips() {
  533. local name="$1" ip format network_id
  534. if ! docker inspect --format='{{ .NetworkSettings.Networks }}' "$name" >/dev/null 2>&1; then
  535. echo "default:$(docker inspect --format='{{ .NetworkSettings.IPAdress }}' "$name" 2>/dev/null)"
  536. else
  537. format='{{range $name, $conf := .NetworkSettings.Networks}}{{$name}}{{"\x00"}}{{$conf.IPAddress}}{{"\x00"}}{{end}}'
  538. while read-0 network_id ip; do
  539. printf "%s:%s\n" "$network_id" "$ip"
  540. done < <(docker inspect --format="$format" "$name")
  541. fi
  542. }
  543. export -f get_docker_ips
  544. get_docker_ip() {
  545. local name="$1"
  546. get_docker_ips "$name"
  547. }
  548. export -f get_docker_ip
  549. wait_docker_ip() {
  550. local name="$1" timeout="${2:-15}" timeout_count=0 docker_ip=
  551. start=$SECONDS
  552. while [ -z "$docker_ip" ]; do
  553. sleep 0.5
  554. docker_ip=$(get_docker_ip "$name") && break
  555. elapsed=$((SECONDS - start))
  556. if ((elapsed > timeout)); then
  557. err "${RED}timeout error${NORMAL}(${timeout}s):" \
  558. "Could not find '$name' docker container's IP."
  559. return 1
  560. fi
  561. [ "$elapsed" == "$old_elapsed" ] ||
  562. verb "Waiting for docker $name... ($elapsed/$timeout)"
  563. old_elapsed="$elapsed"
  564. done
  565. verb "Found docker $name network and IP: $docker_ip"
  566. echo "$docker_ip"
  567. }
  568. export -f wait_docker_ip
  569. wait_for_tcp_port() {
  570. local host_port=$1 timeout=30 start=$SECONDS
  571. verb "Trying to connect to $host_port"
  572. while true; do
  573. timeout 1 bash -c "</dev/tcp/${host_port/://}" >/dev/null 2>&1 && break
  574. sleep 0.2
  575. if [ "$((SECONDS - start))" -gt "$timeout" ]; then
  576. err "${RED}timeout error${NORMAL}(${timeout}s):"\
  577. "Could not connect to $host_port."
  578. return 1
  579. fi
  580. done
  581. return 0
  582. }
  583. export -f wait_for_tcp_port
  584. ## Warning: requires a ``ddb`` matching current database to be checked
  585. wait_for_docker_ip() {
  586. local name=$1 DOCKER_IP= DOCKER_NETWORK= docker_ips= docker_ip=
  587. docker_ip=$(wait_docker_ip "$name" 5) || return 1
  588. IFS=: read DOCKER_NETWORK DOCKER_IP <<<"$docker_ip"
  589. if ! str_is_ipv4 "$DOCKER_IP"; then
  590. err "internal 'wait_docker_ip' did not return a valid IP. Returned IP is '$DOCKER_IP'."
  591. return 1
  592. fi
  593. _set_db_params "$DOCKER_IP" "$DOCKER_NETWORK"
  594. while read-0 port; do
  595. IFS="/" read port type <<<"$port"
  596. [ "$type" == "tcp" ] || continue
  597. wait_for_tcp_port "$DOCKER_IP:${port}" || return 17
  598. verb "Port $DOCKER_IP:${port} checked open."
  599. done < <(image_exposed_ports_0 "$container_id")
  600. ## Checking direct connection
  601. if ! echo "SELECT 1;" | ddb >/dev/null; then
  602. err "${RED}db connection error${NORMAL}:"\
  603. "Could not connect to db on $DOCKER_IP" \
  604. "container's IP. (IP up, TCP ports is(are) open)"
  605. return 18
  606. fi
  607. echo "${DOCKER_NETWORK}:${DOCKER_IP}"
  608. return 0
  609. }
  610. export -f wait_for_docker_ip
  611. docker_add_host_declaration() {
  612. local src_docker=$1 domain=$2 dst_docker=$3 dst_docker_ip= dst_docker_network
  613. dst_docker_ip=$(wait_docker_ip "$dst_docker") || exit 1
  614. IFS=: read dst_docker_ip dst_docker_network <<<"$dst_docker_ip"
  615. docker exec -i "$src_docker" bash <<EOF
  616. if cat /etc/hosts | grep -E "^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$" > /dev/null 2>&1; then
  617. sed -ri "s/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\s+$domain\$/$dst_docker_ip $domain/g" /etc/hosts
  618. else
  619. echo "$dst_docker_ip $domain" >> /etc/hosts
  620. fi
  621. EOF
  622. }
  623. export -f docker_add_host_declaration
  624. get_running_containers_for_service() {
  625. local service="$1"
  626. docker ps --filter label="compose.service=$service" --format="{{.ID}}"
  627. }
  628. export -f get_running_containers_for_service
  629. ##
  630. ## Internal Process
  631. ##
  632. get_docker_compose_links() {
  633. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  634. deps master_service master_target_service _relation_name \
  635. target_service _relation_config tech_dep
  636. if [ -z "$service" ]; then
  637. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  638. return 1
  639. fi
  640. if [ -e "$cache_file" ]; then
  641. # debug "$FUNCNAME: cache hit ($*)"
  642. cat "$cache_file"
  643. return 0
  644. fi
  645. master_service=$(get_top_master_service_for_service "$service") || return 1
  646. ## XXXvlab: yuck, this make the assumption that next function is cached,
  647. ## and leverage the fact that the result is stored in a file. All this only
  648. ## to catch a failure of ``get_compose_relations``, that would go out silently.
  649. get_compose_relations "$service" >/dev/null || return 1 ## fetch cache and fail if necessary
  650. deps=()
  651. while read-0 _relation_name target_service _relation_config tech_dep; do
  652. master_target_service="$(get_top_master_service_for_service "$target_service")" || return 1
  653. [ "$master_service" == "$master_target_service" ] && continue
  654. type="$(get_service_type "$target_service")" || return 1
  655. [ "$type" == "run-once" ] && continue
  656. if [ "$tech_dep" == "reversed" ]; then
  657. deps+=("$(echo -en "$master_target_service:\n links:\n - $master_service")")
  658. elif [ "$tech_dep" == "True" ]; then
  659. deps+=("$(echo -en "$master_service:\n links:\n - $master_target_service")")
  660. fi
  661. ## XXXvlab: an attempt to add depends_on, but this doesn't work well actually
  662. ## as there's a circular dependency issue. We don't really want the full feature
  663. ## of depends_on, but just to add it as targets when doing an 'up'
  664. # deps+=("$(echo -en "$master_service:\n depends_on:\n - $master_target_service")")
  665. done < <(get_compose_relations "$service")
  666. merge_yaml_str "${deps[@]}" | tee "$cache_file" || return 1
  667. if [ "${PIPESTATUS[0]}" != 0 ]; then
  668. rm "$cache_file"
  669. return 1
  670. fi
  671. }
  672. _get_docker_compose_opts() {
  673. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  674. compose_def master_service docker_compose_opts
  675. if [ -z "$service" ]; then
  676. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  677. return 1
  678. fi
  679. if [ -e "$cache_file" ]; then
  680. # debug "$FUNCNAME: cache hit ($*)"
  681. cat "$cache_file"
  682. return 0
  683. fi
  684. compose_def="$(get_compose_service_def "$service")" || return 1
  685. master_service="$(get_top_master_service_for_service "$service")"
  686. docker_compose_opts=$(echo "$compose_def" | shyaml get-value "docker-compose" 2>/dev/null)
  687. if [ "$docker_compose_opts" ]; then
  688. yaml_key_val_str "$master_service" "$docker_compose_opts"
  689. fi | tee "$cache_file"
  690. if [ "${PIPESTATUS[0]}" != 0 ]; then
  691. rm "$cache_file"
  692. return 1
  693. fi
  694. }
  695. ##
  696. ## By Reading the metadata.yml, we create a docker-compose.yml mixin.
  697. ## Some metadata.yml (of subordinates) will indeed modify other
  698. ## services than themselves.
  699. _get_docker_compose_service_mixin() {
  700. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  701. links_yaml base_mixin links_yaml docker_compose_options \
  702. charm charm_part
  703. if [ -z "$service" ]; then
  704. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  705. return 1
  706. fi
  707. if [ -e "$cache_file" ]; then
  708. # debug "$FUNCNAME: cache hit ($*)"
  709. cat "$cache_file"
  710. return 0
  711. fi
  712. master_service=$(get_top_master_service_for_service "$service") || {
  713. err "Failed to get top master service for service $DARKYELLOW$service$NORMAL"
  714. return 1
  715. }
  716. ## The compose part
  717. base_mixin="$master_service:
  718. labels:
  719. - compose.service=$service
  720. - compose.master-service=${master_service}
  721. - compose.project=$(get_default_project_name)"
  722. links_yaml=$(get_docker_compose_links "$service") || return 1
  723. docker_compose_options=$(_get_docker_compose_opts "$service") || return 1
  724. ## the charm part
  725. charm_part=$(get_docker_compose_mixin_from_metadata "$service") || return 1
  726. ## Merge results
  727. if [ "$charm_part" ]; then
  728. charm_yaml="$(yaml_key_val_str "$master_service" "$charm_part")" || return 1
  729. merge_yaml_str "$base_mixin" "$links_yaml" "$charm_yaml" "$docker_compose_options" || return 1
  730. else
  731. merge_yaml_str "$base_mixin" "$links_yaml" "$docker_compose_options" || return 1
  732. fi | tee "$cache_file"
  733. if [ "${PIPESTATUS[0]}" != 0 ]; then
  734. rm "$cache_file"
  735. return 1
  736. fi
  737. }
  738. export -f _get_docker_compose_service_mixin
  739. ##
  740. ## Get full `docker-compose.yml` format for all listed services (and
  741. ## their deps)
  742. ##
  743. ## @export
  744. ## @cache: !system !nofail +stdout
  745. get_docker_compose () {
  746. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  747. entries services service start docker_compose_services
  748. if [ -e "$cache_file" ]; then
  749. # debug "$FUNCNAME: cache hit ($*)"
  750. cat "$cache_file"
  751. return 0
  752. fi
  753. ##
  754. ## Adding sub services configurations
  755. ##
  756. declare -A entries
  757. start_compilation=$SECONDS
  758. debug "Compiling 'docker-compose.yml' base for ${DARKYELLOW}$*$NORMAL..."
  759. for target_service in "$@"; do
  760. start=$SECONDS
  761. services=$(get_ordered_service_dependencies "$target_service") || {
  762. err "Failed to get dependencies for $DARKYELLOW$target_service$NORMAL"
  763. return 1
  764. }
  765. debug " $DARKYELLOW$target_service$NORMAL deps:$DARKYELLOW" $services "$NORMAL$GRAY(in $((SECONDS - start))s)$NORMAL"
  766. for service in $services; do
  767. if [ "${entries[$service]}" ]; then
  768. ## Prevent double inclusion of same service if this
  769. ## service is deps of two or more of your
  770. ## requirements.
  771. continue
  772. fi
  773. ## mark the service as "loaded" as well as it's containers
  774. ## if this is a subordinate service
  775. start_service=$SECONDS
  776. entries[$service]=$(_get_docker_compose_service_mixin "$service") || {
  777. err "Failed to get service mixin for $DARKYELLOW$service$NORMAL"
  778. return 1
  779. }
  780. debug " Applied $DARKYELLOW$service$NORMAL charm metadata mixins $GRAY(in $((SECONDS - start_service))s)$NORMAL"
  781. done
  782. debug " ..finished all mixins for $DARKYELLOW$target_service$NORMAL $GRAY(in $((SECONDS - start))s)$NORMAL"
  783. done
  784. docker_compose_services=$(merge_yaml_str "${entries[@]}") || return 1
  785. base_v2="version: '2.0'
  786. networks:
  787. static:
  788. driver: bridge
  789. ipam:
  790. driver: default
  791. config:
  792. - subnet: 172.25.1.0/24
  793. "
  794. merge_yaml_str "$(yaml_key_val_str "services" "$docker_compose_services")" \
  795. "$base_v2" > "$cache_file" || return 1
  796. export _current_docker_compose="$(cat "$cache_file")"
  797. echo "$_current_docker_compose"
  798. debug " ..compilation of base 'docker-compose.yml' done $GRAY(in $((SECONDS - start_compilation))s)$NORMAL" || true
  799. # debug " ** ${WHITE}docker-compose.yml${NORMAL}:"
  800. # debug "$_current_docker_compose"
  801. }
  802. export -f get_docker_compose
  803. _get_compose_service_def_cached () {
  804. local service="$1" docker_compose="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  805. if [ -e "$cache_file" ]; then
  806. #debug "$FUNCNAME: STATIC cache hit"
  807. cat "$cache_file" &&
  808. touch "$cache_file" || return 1
  809. return 0
  810. fi
  811. value=$(echo "$docker_compose" | shyaml get-value "$service" 2>/dev/null)
  812. if ! echo "$value" | shyaml get-value "charm" >/dev/null 2>&1; then
  813. if charm.exists "$service"; then
  814. value=$(merge_yaml <(echo "charm: $service") <(echo "$value")) || return 1
  815. else
  816. err "No ${WHITE}charm${NORMAL} value for service $DARKYELLOW$service$NORMAL" \
  817. "in compose, nor same name charm found."
  818. return 1
  819. fi
  820. fi
  821. echo "$value" | tee "$cache_file" || return 1
  822. # if [ "${PIPESTATUS[0]}" != 0 ]; then
  823. # rm "$cache_file"
  824. # return 1
  825. # fi
  826. return 0
  827. # if [ "${PIPESTATUS[0]}" != 0 -o \! -s "$cache_file" ]; then
  828. # rm "$cache_file"
  829. # err "PAS OK $service: $value"
  830. # return 1
  831. # fi
  832. }
  833. export -f _get_compose_service_def_cached
  834. ## XXXvlab: a lot to be done to cache the results
  835. get_compose_service_def () {
  836. local service="$1" docker_compose cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  837. result
  838. if [ -e "$cache_file" ]; then
  839. #debug "$FUNCNAME: SESSION cache hit"
  840. cat "$cache_file" || return 1
  841. return 0
  842. fi
  843. [ -z "$service" ] && print_syntax_error "Missing service as first argument."
  844. docker_compose=$(get_compose_yml_content) || return 1
  845. result=$(_get_compose_service_def_cached "$service" "$docker_compose") || return 1
  846. echo "$result" | tee "$cache_file" || return 1
  847. }
  848. export -f get_compose_service_def
  849. _get_service_charm_cached () {
  850. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  851. if [ -e "$cache_file" ]; then
  852. # debug "$FUNCNAME: cache hit $1"
  853. cat "$cache_file" &&
  854. touch "$cache_file" || return 1
  855. return 0
  856. fi
  857. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  858. if [ -z "$charm" ]; then
  859. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  860. return 1
  861. fi
  862. echo "$charm" | tee "$cache_file" || return 1
  863. }
  864. export -f _get_service_charm_cached
  865. get_service_charm () {
  866. local service="$1"
  867. if [ -z "$service" ]; then
  868. echo ${FUNCNAME[@]} >&2
  869. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  870. return 1
  871. fi
  872. service_def=$(get_compose_service_def "$service") || return 1
  873. _get_service_charm_cached "$service" "$service_def"
  874. }
  875. export -f get_service_charm
  876. ## built above the docker-compose abstraction, so it relies on the
  877. ## full docker-compose.yml to be already built.
  878. get_service_def () {
  879. local service="$1" def
  880. if [ -z "$_current_docker_compose" ]; then
  881. print_syntax_error "$FUNCNAME is meant to be called after"\
  882. "\$_current_docker_compose has been calculated."
  883. fi
  884. def=$(echo "$_current_docker_compose" | shyaml get-value "services.$service" 2>/dev/null)
  885. if [ -z "$def" ]; then
  886. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  887. return 1
  888. fi
  889. echo "$def"
  890. }
  891. export -f get_service_def
  892. ## Return the base docker image name of a service
  893. service_base_docker_image() {
  894. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  895. master_service service_def service_image service_build service_dockerfile
  896. if [ -e "$cache_file" ]; then
  897. # debug "$FUNCNAME: cache hit ($*)"
  898. cat "$cache_file"
  899. return 0
  900. fi
  901. master_service="$(get_top_master_service_for_service "$service")" || {
  902. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  903. return 1
  904. }
  905. service_def="$(get_service_def "$master_service")" || {
  906. err "Could not get docker-compose service definition for $DARKYELLOW$master_service$NORMAL."
  907. return 1
  908. }
  909. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  910. if [ "$?" != 0 ]; then
  911. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  912. if [ "$?" != 0 ]; then
  913. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  914. echo "$service_def" >&2
  915. return 1
  916. fi
  917. service_dockerfile="${service_build}"/Dockerfile
  918. if ! [ -e "$service_dockerfile" ]; then
  919. err "No Dockerfile found in '$service_dockerfile' location."
  920. return 1
  921. fi
  922. grep '^FROM' "$service_dockerfile" | xargs printf "%s " | cut -f 2 -d " "
  923. else
  924. echo "$service_image"
  925. fi | tee "$cache_file"
  926. }
  927. export -f service_base_docker_image
  928. get_charm_relation_def () {
  929. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  930. relation_def metadata
  931. if [ -e "$cache_file" ]; then
  932. # debug "$FUNCNAME: cache hit ($*)"
  933. cat "$cache_file"
  934. return 0
  935. fi
  936. metadata="$(charm.metadata "$charm")" || return 1
  937. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  938. echo "$relation_def" | tee "$cache_file"
  939. }
  940. export -f get_charm_relation_def
  941. get_charm_tech_dep_orientation_for_relation() {
  942. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  943. relation_def value
  944. if [ -e "$cache_file" ]; then
  945. # debug "$FUNCNAME: cache hit ($*)"
  946. cat "$cache_file"
  947. return 0
  948. fi
  949. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  950. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  951. value=${value:-True}
  952. echo "$value" | tee "$cache_file"
  953. }
  954. export -f get_charm_tech_dep_orientation_for_relation
  955. ##
  956. ## Use compose file to get deps, and relation definition in metadata.yml
  957. ## for tech-dep attribute.
  958. get_service_deps() {
  959. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  960. if [ -e "$cache_file" ]; then
  961. # debug "$FUNCNAME: cache hit ($*)"
  962. cat "$cache_file"
  963. return 0
  964. fi
  965. (
  966. set -o pipefail
  967. get_compose_relations "$service" | \
  968. while read-0 relation_name target_service _relation_config tech_dep; do
  969. echo "$target_service"
  970. done | tee "$cache_file"
  971. ) || return 1
  972. }
  973. export -f get_service_deps
  974. _rec_get_depth() {
  975. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  976. [ "${depths[$elt]}" ] && return 0
  977. if [ -e "$cache_file" ]; then
  978. # debug "$FUNCNAME: cache hit ($*)"
  979. depths[$elt]=$(cat "$cache_file")
  980. return 0
  981. fi
  982. visited[$elt]=1
  983. #debug "Setting visited[$elt]"
  984. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  985. deps=$(get_service_deps "$elt") || {
  986. debug "Failed get_service_deps $elt"
  987. return 1
  988. }
  989. # debug "$elt deps are:" $deps
  990. max=0
  991. for dep in $deps; do
  992. [ "${visited[$dep]}" ] && {
  993. #debug "Already computing $dep"
  994. continue
  995. }
  996. _rec_get_depth "$dep" || return 1
  997. #debug "Requesting depth[$dep]"
  998. if (( ${depths[$dep]} > max )); then
  999. max="${depths[$dep]}"
  1000. fi
  1001. done
  1002. # debug "Setting depth[$elt] to $((max + 1))"
  1003. depths[$elt]=$((max + 1))
  1004. echo "${depths[$elt]}" > $cache_file
  1005. }
  1006. export -f _rec_get_depth
  1007. get_ordered_service_dependencies() {
  1008. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1009. if [ -e "$cache_file" ]; then
  1010. # debug "$FUNCNAME: cache hit ($*)"
  1011. cat "$cache_file"
  1012. return 0
  1013. fi
  1014. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  1015. if [ -z "${services[*]}" ]; then
  1016. return 0
  1017. # print_syntax_error "$FUNCNAME: no arguments"
  1018. # return 1
  1019. fi
  1020. declare -A depths
  1021. declare -A visited
  1022. heads=("${services[@]}")
  1023. while [ "${#heads[@]}" != 0 ]; do
  1024. array_pop heads head
  1025. _rec_get_depth "$head" || return 1
  1026. done
  1027. i=0
  1028. while [ "${#depths[@]}" != 0 ]; do
  1029. for key in "${!depths[@]}"; do
  1030. value="${depths[$key]}"
  1031. if [ "$value" == "$i" ]; then
  1032. echo "$key"
  1033. unset depths[$key]
  1034. fi
  1035. done
  1036. i=$((i + 1))
  1037. done | tee "$cache_file"
  1038. }
  1039. export -f get_ordered_service_dependencies
  1040. run_service_hook () {
  1041. local action="$1" service subservice subservices loaded
  1042. shift
  1043. declare -A loaded
  1044. for service in "$@"; do
  1045. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1046. for subservice in $subservices; do
  1047. if [ "${loaded[$subservice]}" ]; then
  1048. ## Prevent double inclusion of same service if this
  1049. ## service is deps of two or more of your
  1050. ## requirements.
  1051. continue
  1052. fi
  1053. charm=$(get_service_charm "$subservice") || return 1
  1054. charm.has_hook "$charm" "$action" >/dev/null || continue
  1055. PROJECT_NAME=$(get_default_project_name) || return 1
  1056. export MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1057. export MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1058. Wrap -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1059. export SERVICE_NAME=$subservice
  1060. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1061. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1062. export CHARM_NAME="$charm"
  1063. export PROJECT_NAME=$PROJECT_NAME
  1064. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$MASTER_BASE_SERVICE_NAME")
  1065. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1066. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1067. charm.run_hook "$charm" "$action"
  1068. EOF
  1069. loaded[$subservice]=1
  1070. done
  1071. done
  1072. return 0
  1073. }
  1074. host_resource_get() {
  1075. local location="$1" cfg="$2"
  1076. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1077. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1078. return 1
  1079. }
  1080. if fn.exists host_resource_get_$type; then
  1081. host_resource_get_$type "$location" "$cfg"
  1082. else
  1083. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1084. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1085. "$DARKYELLOW$subservice$NORMAL config."
  1086. return 1
  1087. fi
  1088. }
  1089. export -f host_resource_get
  1090. host_resource_get_git() {
  1091. local location="$1" cfg="$2" branch parent url
  1092. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1093. branch=${branch:-master}
  1094. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1095. parent="$(dirname "$location")"
  1096. (
  1097. mkdir -p "$parent" && cd "$parent" &&
  1098. git clone -b "$branch" "$url" "$(basename "$location")"
  1099. ) || return 1
  1100. }
  1101. export -f host_resource_get_git
  1102. host_resource_get_git-sub() {
  1103. local location="$1" cfg="$2" branch parent url
  1104. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1105. branch=${branch:-master}
  1106. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1107. parent="$(dirname "$location")"
  1108. (
  1109. mkdir -p "$parent" && cd "$parent" &&
  1110. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1111. ) || return 1
  1112. }
  1113. export -f host_resource_get_git-sub
  1114. setup_host_resource () {
  1115. local subservice="$1" service_def location get cfg
  1116. service_def=$(get_compose_service_def "$subservice") || return 1
  1117. while read-0 location cfg; do
  1118. ## XXXvlab: will it be a git resources always ?
  1119. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1120. err "Hum, location '$location' does not seem to be a git directory."
  1121. return 1
  1122. fi
  1123. if [ -d "$location" ]; then
  1124. info "host resource '$location' already set up."
  1125. continue
  1126. fi
  1127. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1128. if [ -z "$get" ]; then
  1129. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1130. "specified for $DARKYELLOW$subservice$NORMAL."
  1131. return 1
  1132. fi
  1133. host_resource_get "$location" "$get" || return 1
  1134. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1135. }
  1136. export -f setup_host_resource
  1137. setup_host_resources () {
  1138. local service subservices subservice loaded
  1139. declare -A loaded
  1140. for service in "$@"; do
  1141. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1142. for subservice in $subservices; do
  1143. if [ "${loaded[$subservice]}" ]; then
  1144. ## Prevent double inclusion of same service if this
  1145. ## service is deps of two or more of your
  1146. ## requirements.
  1147. continue
  1148. fi
  1149. setup_host_resource "$service"
  1150. loaded[$subservice]=1
  1151. done
  1152. done
  1153. return 0
  1154. }
  1155. export -f setup_host_resources
  1156. relation-get () {
  1157. local key="$1"
  1158. cat "$RELATION_DATA_FILE" | shyaml get-value "$key" 2>/dev/null
  1159. if [ "$?" != 0 ]; then
  1160. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1161. return 1
  1162. fi
  1163. }
  1164. export -f relation-get
  1165. relation-base-compose-get () {
  1166. local key="$1"
  1167. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1168. if [ "$?" != 0 ]; then
  1169. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1170. return 1
  1171. fi
  1172. }
  1173. export -f relation-base-compose-get
  1174. relation-target-compose-get () {
  1175. local key="$1"
  1176. echo "$RELATION_BASE_COMPOSE_DEF" | shyaml get-value "options.$key" 2>/dev/null
  1177. if [ "$?" != 0 ]; then
  1178. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1179. return 1
  1180. fi
  1181. }
  1182. export -f relation-target-compose-get
  1183. relation-set () {
  1184. local key="$1" value="$2"
  1185. if [ -z "$RELATION_DATA_FILE" ]; then
  1186. err "$FUNCNAME: relation does not seems to be correctly setup."
  1187. return 1
  1188. fi
  1189. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1190. err "$FUNCNAME: can't read relation's data." >&2
  1191. return 1
  1192. fi
  1193. _config_merge "$RELATION_DATA_FILE" <(echo "$key: $value")
  1194. }
  1195. export -f relation-set
  1196. _config_merge() {
  1197. local config_filename="$1" merge_to_file="$2"
  1198. touch "$config_filename" &&
  1199. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  1200. mv "$config_filename.tmp" "$config_filename"
  1201. }
  1202. export -f _config_merge
  1203. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1204. config-add() {
  1205. local metadata="$1"
  1206. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1207. }
  1208. export -f config-add
  1209. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1210. init-config-add() {
  1211. local metadata="$1"
  1212. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1213. <(yaml_key_val_str "services" "$metadata")
  1214. }
  1215. export -f init-config-add
  1216. logstdout() {
  1217. local name="$1"
  1218. sed -r 's%^%'"${name}"'> %g'
  1219. }
  1220. export -f logstdout
  1221. logstderr() {
  1222. local name="$1"
  1223. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1224. }
  1225. export -f logstderr
  1226. _run_service_relation () {
  1227. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1228. charm=$(get_service_charm "$service") || return 1
  1229. target_charm=$(get_service_charm "$target_service") || return 1
  1230. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1231. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1232. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1233. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1234. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1235. export BASE_SERVICE_NAME=$service
  1236. export BASE_CHARM_NAME=$charm
  1237. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1238. export TARGET_SERVICE_NAME=$target_service
  1239. export TARGET_CHARM_NAME=$target_charm
  1240. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1241. export RELATION_DATA_FILE
  1242. target_errlvl=0
  1243. if [ -z "$target_script_name" ]; then
  1244. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1245. else
  1246. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1247. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1248. RELATION_CONFIG="$relation_dir/config_provider"
  1249. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1250. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1251. {
  1252. (
  1253. SERVICE_NAME=$target_service
  1254. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1255. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1256. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1257. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1258. echo "$?" > "$relation_dir/target_errlvl"
  1259. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1260. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1261. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1262. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1263. "failed before outputing an errorlevel."
  1264. ((target_errlvl |= "1" ))
  1265. }
  1266. if [ -e "$RELATION_CONFIG" ]; then
  1267. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1268. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1269. rm "$RELATION_CONFIG"
  1270. ((target_errlvl |= "$?"))
  1271. fi
  1272. fi
  1273. if [ "$target_errlvl" == 0 ]; then
  1274. errlvl=0
  1275. if [ "$base_script_name" ]; then
  1276. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1277. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1278. RELATION_CONFIG="$relation_dir/config_providee"
  1279. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1280. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1281. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1282. {
  1283. (
  1284. SERVICE_NAME=$service
  1285. SERVICE_DATASTORE="$DATASTORE/$service"
  1286. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1287. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1288. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1289. echo "$?" > "$relation_dir/errlvl"
  1290. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1291. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1292. errlvl="$(cat "$relation_dir/errlvl")" || {
  1293. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1294. "failed before outputing an errorlevel."
  1295. ((errlvl |= "1" ))
  1296. }
  1297. if [ -e "$RELATION_CONFIG" ]; then
  1298. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1299. rm "$RELATION_CONFIG"
  1300. ((errlvl |= "$?" ))
  1301. fi
  1302. if [ "$errlvl" != 0 ]; then
  1303. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1304. fi
  1305. else
  1306. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1307. fi
  1308. else
  1309. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1310. fi
  1311. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1312. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1313. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1314. return 0
  1315. else
  1316. return 1
  1317. fi
  1318. }
  1319. export -f _run_service_relation
  1320. _get_compose_relations_cached () {
  1321. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1322. relation_name relation_def target_service
  1323. if [ -e "$cache_file" ]; then
  1324. #debug "$FUNCNAME: STATIC cache hit $1"
  1325. cat "$cache_file" &&
  1326. touch "$cache_file" || return 1
  1327. return 0
  1328. fi
  1329. (
  1330. set -o pipefail
  1331. if [ "$compose_service_def" ]; then
  1332. while read-0 relation_name relation_def; do
  1333. ## XXXvlab: could we use braces here instead of parenthesis ?
  1334. (
  1335. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1336. "str")
  1337. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)"
  1338. target_charm=$(get_service_charm "$target_service") || return 1
  1339. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1340. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1341. ;;
  1342. "sequence")
  1343. while read-0 target_service; do
  1344. target_charm=$(get_service_charm "$target_service") || return 1
  1345. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1346. echo -en "$relation_name\0$target_service\0\0$tech_dep\0"
  1347. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1348. ;;
  1349. "struct")
  1350. while read-0 target_service relation_config; do
  1351. target_charm=$(get_service_charm "$target_service") || return 1
  1352. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$target_charm" "$relation_name")"
  1353. echo -en "$relation_name\0$target_service\0$relation_config\0$tech_dep\0"
  1354. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1355. ;;
  1356. esac
  1357. ) </dev/null >> "$cache_file" || return 1
  1358. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1359. fi
  1360. )
  1361. if [ "$?" != 0 ]; then
  1362. err "Error while looking for compose relations."
  1363. rm -f "$cache_file" ## no cache
  1364. return 1
  1365. fi
  1366. [ -e "$cache_file" ] && cat "$cache_file"
  1367. return 0
  1368. }
  1369. export -f _get_compose_relations_cached
  1370. get_compose_relations () {
  1371. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1372. compose_def
  1373. if [ -e "$cache_file" ]; then
  1374. #debug "$FUNCNAME: SESSION cache hit $1"
  1375. cat "$cache_file"
  1376. return 0
  1377. fi
  1378. compose_def="$(get_compose_service_def "$service")" || return 1
  1379. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1380. if [ "$?" != 0 ]; then
  1381. rm -f "$cache_file" ## no cache
  1382. return 1
  1383. fi
  1384. cat "$cache_file"
  1385. }
  1386. export -f get_compose_relations
  1387. get_compose_relation_def() {
  1388. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  1389. while read-0 relation_name target_service relation_config tech_dep; do
  1390. [ "$relation_name" == "$relation" ] || continue
  1391. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  1392. done < <(get_compose_relations "$service") || return 1
  1393. }
  1394. export -f get_compose_relation_def
  1395. run_service_relations () {
  1396. local service services loaded subservices subservice
  1397. PROJECT_NAME=$(get_default_project_name) || return 1
  1398. export PROJECT_NAME
  1399. declare -A loaded
  1400. subservices=$(get_ordered_service_dependencies "$@") || return 1
  1401. for service in $subservices; do
  1402. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  1403. for subservice in $(get_service_deps "$service") "$service"; do
  1404. [ "${loaded[$subservice]}" ] && continue
  1405. export BASE_SERVICE_NAME=$service
  1406. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1407. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1408. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  1409. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  1410. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  1411. while read-0 relation_name target_service relation_config tech_dep; do
  1412. export relation_config
  1413. export TARGET_SERVICE_NAME=$target_service
  1414. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  1415. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  1416. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  1417. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  1418. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  1419. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  1420. EOF
  1421. done < <(get_compose_relations "$subservice") || return 1
  1422. loaded[$subservice]=1
  1423. done
  1424. done
  1425. }
  1426. export -f run_service_relations
  1427. _run_service_action_direct() {
  1428. local service="$1" action="$2" charm _dummy
  1429. shift; shift
  1430. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  1431. if read-0 _dummy || [ "$_dummy" ]; then
  1432. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1433. return 1
  1434. fi
  1435. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1436. export state_tmpdir
  1437. {
  1438. (
  1439. set +e ## Prevents unwanted leaks from parent shell
  1440. export COMPOSE_CONFIG=$(get_compose_yml_content)
  1441. export METADATA_CONFIG=$(charm.metadata "$charm")
  1442. export SERVICE_NAME=$service
  1443. export ACTION_NAME=$action
  1444. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  1445. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1446. export SERVICE_DATASTORE="$DATASTORE/$service"
  1447. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1448. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1449. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  1450. echo "$?" > "$action_errlvl_file"
  1451. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1452. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1453. if ! [ -e "$action_errlvl_file" ]; then
  1454. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1455. "to output an errlvl"
  1456. return 1
  1457. fi
  1458. return "$(cat "$action_errlvl_file")"
  1459. }
  1460. export -f _run_service_action_direct
  1461. _run_service_action_relation() {
  1462. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  1463. shift; shift
  1464. read-0 charm target_service target_charm relation_name relation_config || true
  1465. if read-0 _dummy || [ "$_dummy" ]; then
  1466. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  1467. return 1
  1468. fi
  1469. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  1470. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  1471. export state_tmpdir
  1472. {
  1473. (
  1474. set +e ## Prevents unwanted leaks from parent shell
  1475. export METADATA_CONFIG=$(charm.metadata "$charm")
  1476. export SERVICE_NAME=$service
  1477. export RELATION_TARGET_SERVICE="$target_service"
  1478. export RELATION_TARGET_CHARM="$target_charm"
  1479. export RELATION_BASE_SERVICE="$service"
  1480. export RELATION_BASE_CHARM="$charm"
  1481. export ACTION_NAME=$action
  1482. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  1483. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  1484. export SERVICE_DATASTORE="$DATASTORE/$service"
  1485. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1486. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  1487. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  1488. echo "$?" > "$action_errlvl_file"
  1489. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  1490. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1491. if ! [ -e "$action_errlvl_file" ]; then
  1492. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  1493. "to output an errlvl"
  1494. return 1
  1495. fi
  1496. return "$(cat "$action_errlvl_file")"
  1497. }
  1498. export -f _run_service_action_relation
  1499. get_relation_data_dir() {
  1500. local service="$1" target_service="$2" relation_name="$3" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1501. if [ -e "$cache_file" ]; then
  1502. # debug "$FUNCNAME: cache hit ($*)"
  1503. cat "$cache_file"
  1504. return 0
  1505. fi
  1506. project=$(get_default_project_name) || return 1
  1507. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  1508. if ! [ -d "$relation_dir" ]; then
  1509. mkdir -p "$relation_dir" || return 1
  1510. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  1511. fi
  1512. echo "$relation_dir" || tee "$cache_file"
  1513. }
  1514. export -f get_relation_data_dir
  1515. get_relation_data_file() {
  1516. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  1517. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1518. relation_data_file="$relation_dir/data"
  1519. new=
  1520. if [ -e "$relation_data_file" ]; then
  1521. ## Has reference changed ?
  1522. new_md5=$(echo "$relation_config" | md5_compat)
  1523. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  1524. new=true
  1525. fi
  1526. else
  1527. new=true
  1528. fi
  1529. if [ "$new" ]; then
  1530. echo "$relation_config" > "$relation_data_file"
  1531. chmod go-rwx "$relation_data_file" ## protecting this file
  1532. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  1533. fi
  1534. echo "$relation_data_file"
  1535. }
  1536. export -f get_relation_data_file
  1537. has_service_action () {
  1538. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1539. charm target_charm relation_name target_service relation_config _tech_dep
  1540. if [ -e "$cache_file" ]; then
  1541. # debug "$FUNCNAME: cache hit ($*)"
  1542. cat "$cache_file"
  1543. return 0
  1544. fi
  1545. charm=$(get_service_charm "$service") || return 1
  1546. ## Action directly provided ?
  1547. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  1548. echo -en "direct\0$charm" | tee "$cache_file"
  1549. return 0
  1550. fi
  1551. ## Action provided by relation ?
  1552. while read-0 relation_name target_service relation_config _tech_dep; do
  1553. target_charm=$(get_service_charm "$target_service") || return 1
  1554. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  1555. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  1556. return 0
  1557. fi
  1558. done < <(get_compose_relations "$service")
  1559. return 1
  1560. # master=$(get_top_master_service_for_service "$service")
  1561. # [ "$master" == "$charm" ] && return 1
  1562. # has_service_action "$master" "$action"
  1563. }
  1564. export -f has_service_action
  1565. run_service_action () {
  1566. local service="$1" action="$2"
  1567. shift ; shift
  1568. {
  1569. if ! read-0 action_type; then
  1570. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  1571. info " Add an executable script to 'actions/$action' to implement action."
  1572. return 1
  1573. fi
  1574. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  1575. "_run_service_action_${action_type}" "$service" "$action" "$@"
  1576. } < <(has_service_action "$service" "$action")
  1577. }
  1578. export -f run_service_action
  1579. get_compose_relation_config() {
  1580. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1581. if [ -e "$cache_file" ]; then
  1582. # debug "$FUNCNAME: cache hit ($*)"
  1583. cat "$cache_file"
  1584. return 0
  1585. fi
  1586. compose_service_def=$(get_compose_service_def "$service") || return 1
  1587. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  1588. }
  1589. export -f get_compose_relation_config
  1590. # ## Return key-values-0
  1591. # get_compose_relation_config_for_service() {
  1592. # local service=$1 relation_name=$2 relation_config
  1593. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  1594. # if ! relation_config=$(
  1595. # echo "$compose_service_relations" |
  1596. # shyaml get-value "${relation_name}" 2>/dev/null); then
  1597. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  1598. # "relation config in compose configuration."
  1599. # return 1
  1600. # fi
  1601. # if [ -z "$relation_config" ]; then
  1602. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  1603. # return 1
  1604. # fi
  1605. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  1606. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  1607. # return 1
  1608. # fi
  1609. # }
  1610. # export -f get_compose_relation_config_for_service
  1611. _get_master_service_for_service_cached () {
  1612. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1613. charm requires master_charm target_charm target_service service_def found
  1614. if [ -e "$cache_file" ]; then
  1615. # debug "$FUNCNAME: STATIC cache hit ($1)"
  1616. cat "$cache_file" &&
  1617. touch "$cache_file" || return 1
  1618. return 0
  1619. fi
  1620. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  1621. ## just return service name
  1622. echo "$service" | tee "$cache_file"
  1623. return 0
  1624. fi
  1625. ## fetch the container relation
  1626. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  1627. if [ -z "$requires" ]; then
  1628. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any 'requires' " \
  1629. "section."
  1630. fi
  1631. found=
  1632. while read-0 relation_name relation; do
  1633. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  1634. found=1
  1635. break
  1636. }
  1637. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  1638. if [ -z "$found" ]; then
  1639. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  1640. " ${WHITE}scope${NORMAL} set to 'container'."
  1641. fi
  1642. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  1643. if [ -z "$interface" ]; then
  1644. err "No ${WHITE}interface${NORMAL} set for relation $DARKBLUE$relation_name$NORMAL."
  1645. return 1
  1646. fi
  1647. ## Action provided by relation ?
  1648. found=
  1649. while read-0 relation_name target_service _relation_config _tech_dep; do
  1650. [ "$interface" == "$relation_name" ] && {
  1651. found=1
  1652. break
  1653. }
  1654. done < <(get_compose_relations "$service")
  1655. if [ -z "$found" ]; then
  1656. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  1657. "${DARKYELLOW}$service$NORMAL compose definition."
  1658. return 1
  1659. fi
  1660. echo "$target_service" | tee "$cache_file"
  1661. }
  1662. export -f _get_master_service_for_service_cached
  1663. get_master_service_for_service() {
  1664. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1665. charm metadata result
  1666. if [ -e "$cache_file" ]; then
  1667. # debug "$FUNCNAME: SESSION cache hit ($*)"
  1668. cat "$cache_file" || return 1
  1669. return 0
  1670. fi
  1671. charm=$(get_service_charm "$service") || return 1
  1672. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  1673. metadata=""
  1674. warn "No charm $DARKPINK$charm$NORMAL found."
  1675. }
  1676. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  1677. echo "$result" | tee "$cache_file" || return 1
  1678. }
  1679. export -f get_master_service_for_service
  1680. get_top_master_service_for_service() {
  1681. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1682. current_service
  1683. if [ -e "$cache_file" ]; then
  1684. # debug "$FUNCNAME: cache hit ($*)"
  1685. cat "$cache_file"
  1686. return 0
  1687. fi
  1688. current_service="$service"
  1689. while true; do
  1690. master_service=$(get_master_service_for_service "$current_service") || return 1
  1691. [ "$master_service" == "$current_service" ] && break
  1692. current_service="$master_service"
  1693. done
  1694. echo "$current_service" | tee "$cache_file"
  1695. return 0
  1696. }
  1697. export -f get_top_master_service_for_service
  1698. ##
  1699. ## The result is a mixin that is not always a complete valid
  1700. ## docker-compose entry (thinking of subordinates). The result
  1701. ## will be merge with master charms.
  1702. _get_docker_compose_mixin_from_metadata_cached() {
  1703. local service="$1" charm="$2" metadata="$3" has_build_dir="$4" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1704. metadata_file metadata volumes docker_compose subordinate image
  1705. if [ -e "$cache_file" ]; then
  1706. #debug "$FUNCNAME: STATIC cache hit $1"
  1707. cat "$cache_file" &&
  1708. touch "$cache_file" || return 1
  1709. return 0
  1710. fi
  1711. mixin=$(echo -en "labels:\n- compose.charm=$charm")
  1712. if [ "$metadata" ]; then
  1713. ## resources to volumes
  1714. volumes=$(
  1715. for resource_type in data config; do
  1716. while read-0 resource; do
  1717. eval "echo \" - \$${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  1718. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  1719. done
  1720. while read-0 resource; do
  1721. if [[ "$resource" == /*:/*:* ]]; then
  1722. echo " - $resource"
  1723. elif [[ "$resource" == /*:/* ]]; then
  1724. echo " - $resource:rw"
  1725. elif [[ "$resource" == /*:* ]]; then
  1726. echo " - ${resource%%:*}:$resource"
  1727. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  1728. echo " - $resource:$resource:rw"
  1729. else
  1730. die "Invalid host-resource specified in 'metadata.yml'."
  1731. fi
  1732. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  1733. while read-0 resource; do
  1734. dest="$(charm.get_dir "$charm")/resources$resource"
  1735. if ! [ -e "$dest" ]; then
  1736. die "charm-resource: '$resource' does not exist (file: '$dest')."
  1737. fi
  1738. echo " - $dest:$resource:ro"
  1739. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  1740. ) || return 1
  1741. if [ "$volumes" ]; then
  1742. mixin=$(merge_yaml_str "$mixin" "$(echo -en "volumes:\n$volumes")") || {
  1743. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1744. "from charm ${DARKPINK}$charm$NORMAL."
  1745. return 1
  1746. }
  1747. fi
  1748. docker_compose=$(echo "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null)
  1749. if [ "$docker_compose" ]; then
  1750. mixin=$(merge_yaml_str "$mixin" "$docker_compose") || {
  1751. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  1752. "from charm ${DARKPINK}$charm$NORMAL."
  1753. return 1
  1754. }
  1755. fi
  1756. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  1757. subordinate=true
  1758. fi
  1759. fi
  1760. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  1761. image_or_build_statement=
  1762. if [ "$image" ]; then
  1763. if [ "$subordinate" ]; then
  1764. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  1765. return 1
  1766. fi
  1767. image_or_build_statement="image: $image"
  1768. elif [ "$has_build_dir" ]; then
  1769. if [ "$subordinate" ]; then
  1770. err "Subordinate charm can not have a 'build' sub directory."
  1771. return 1
  1772. fi
  1773. image_or_build_statement="build: $(charm.get_dir "$charm")/build"
  1774. fi
  1775. if [ "$image_or_build_statement" ]; then
  1776. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement")
  1777. fi
  1778. echo "$mixin" | tee "$cache_file"
  1779. }
  1780. export -f _get_docker_compose_mixin_from_metadata_cached
  1781. get_docker_compose_mixin_from_metadata() {
  1782. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1783. if [ -e "$cache_file" ]; then
  1784. #debug "$FUNCNAME: SESSION cache hit ($*)"
  1785. cat "$cache_file"
  1786. return 0
  1787. fi
  1788. charm=$(get_service_charm "$service") || return 1
  1789. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  1790. has_build_dir=
  1791. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  1792. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  1793. echo "$mixin" | tee "$cache_file"
  1794. }
  1795. export -f get_docker_compose_mixin_from_metadata
  1796. _save() {
  1797. local name="$1"
  1798. cat - | tee -a "$docker_compose_dir/.data/$name"
  1799. }
  1800. export -f _save
  1801. get_default_project_name() {
  1802. if [ "$DEFAULT_PROJECT_NAME" ]; then
  1803. echo "$DEFAULT_PROJECT_NAME"
  1804. return 0
  1805. fi
  1806. compose_yml_location="$(get_compose_yml_location)" || return 1
  1807. if [ "$compose_yml_location" ]; then
  1808. if normalized_path=$(readlink -e "$compose_yml_location"); then
  1809. echo "$(basename "$(dirname "$normalized_path")")"
  1810. return 0
  1811. fi
  1812. fi
  1813. echo "orphan"
  1814. return 0
  1815. }
  1816. export -f get_default_project_name
  1817. launch_docker_compose() {
  1818. local charm docker_compose_tmpdir docker_compose_dir
  1819. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1820. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  1821. # trap_add EXIT "debug \"Removing temporary docker-compose directory in $docker_compose_tmpdir.\";\
  1822. # rm -rf \"$docker_compose_tmpdir\""
  1823. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  1824. project=$(get_default_project_name)
  1825. mkdir -p "$docker_compose_tmpdir/$project"
  1826. docker_compose_dir="$docker_compose_tmpdir/$project"
  1827. # if [ -z "$SERVICE_PACK" ]; then
  1828. # export SERVICE_PACK=$(get_default_target_services $SERVICE_PACK)
  1829. # fi
  1830. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  1831. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  1832. # debug "Merging some config data in docker-compose.yml:"
  1833. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  1834. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  1835. fi
  1836. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  1837. die "Generated 'docker-compose.yml' is unexpectedly empty."
  1838. fi
  1839. ## XXXvlab: could be more specific and only link the needed charms
  1840. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  1841. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  1842. # if charm.exists "$charm"; then
  1843. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  1844. # fi
  1845. # done
  1846. mkdir "$docker_compose_dir/.data"
  1847. {
  1848. {
  1849. cd "$docker_compose_dir"
  1850. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  1851. debug "$(cat "$docker_compose_dir/docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  1852. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  1853. if [ "$DRY_COMPOSE_RUN" ]; then
  1854. echo docker-compose "$@"
  1855. else
  1856. docker-compose "$@"
  1857. fi
  1858. echo "$?" > "$docker_compose_dir/.data/errlvl"
  1859. } | _save stdout
  1860. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  1861. 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
  1862. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  1863. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  1864. fi
  1865. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  1866. if [ -z "$docker_compose_errlvl" ]; then
  1867. err "Something went wrong before you could gather docker-compose errorlevel."
  1868. return 1
  1869. fi
  1870. return "$docker_compose_errlvl"
  1871. }
  1872. export -f launch_docker_compose
  1873. get_compose_yml_location() {
  1874. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  1875. echo "$COMPOSE_YML_FILE"
  1876. return 0
  1877. fi
  1878. parent=$(while ! [ -e "./compose.yml" ]; do
  1879. [ "$PWD" == "/" ] && exit 0
  1880. cd ..
  1881. done; echo "$PWD"
  1882. )
  1883. if [ "$parent" ]; then
  1884. echo "$parent/compose.yml"
  1885. return 0
  1886. fi
  1887. ## XXXvlab: do we need this additional environment variable,
  1888. ## COMPOSE_YML_FILE is not sufficient ?
  1889. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1890. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1891. warn "No 'compose.yml' was found in current or parent dirs," \
  1892. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  1893. "(${DEFAULT_COMPOSE_FILE})"
  1894. return 0
  1895. fi
  1896. echo "$DEFAULT_COMPOSE_FILE"
  1897. return 0
  1898. fi
  1899. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1900. return 0
  1901. }
  1902. export -f get_compose_yml_location
  1903. get_compose_yml_content() {
  1904. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  1905. if [ -e "$cache_file" ]; then
  1906. cat "$cache_file" &&
  1907. touch "$cache_file" || return 1
  1908. return 0
  1909. fi
  1910. if [ -z "$COMPOSE_YML_FILE" ]; then
  1911. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  1912. fi
  1913. if [ -e "$COMPOSE_YML_FILE" ]; then
  1914. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  1915. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE")
  1916. else
  1917. debug "No compose file found. Using an empty one."
  1918. COMPOSE_YML_CONTENT=""
  1919. fi
  1920. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  1921. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  1922. if [ "$?" != 0 ]; then
  1923. outputed_something=
  1924. while IFS='' read -r line1 && IFS='' read -r line2; do
  1925. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  1926. outputed_something=true
  1927. echo "$line1 $GRAY($line2)$NORMAL"
  1928. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  1929. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  1930. prefix " $GRAY|$NORMAL "
  1931. [ "$outputed_something" ] || {
  1932. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  1933. echo "$output" | prefix " $GRAY|$NORMAL "
  1934. }
  1935. exit 1
  1936. fi
  1937. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  1938. }
  1939. export -f get_compose_yml_content
  1940. get_default_target_services() {
  1941. local services=("$@")
  1942. if [ -z "${services[*]}" ]; then
  1943. if [ "$DEFAULT_SERVICES" ]; then
  1944. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1945. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1946. services="$DEFAULT_SERVICES"
  1947. else
  1948. err "No service provided."
  1949. return 1
  1950. fi
  1951. fi
  1952. echo "${services[*]}"
  1953. }
  1954. export -f get_default_target_services
  1955. get_master_services() {
  1956. local loaded master_service service
  1957. declare -A loaded
  1958. for service in "$@"; do
  1959. master_service=$(get_top_master_service_for_service "$service") || return 1
  1960. if [ "${loaded[$master_service]}" ]; then
  1961. continue
  1962. fi
  1963. echo "$master_service"
  1964. loaded["$master_service"]=1
  1965. done | xargs printf "%s "
  1966. return "${PIPESTATUS[0]}"
  1967. }
  1968. export -f get_master_services
  1969. _setup_state_dir() {
  1970. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1971. #debug "Creating temporary state directory in '$state_tmpdir'."
  1972. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1973. # rm -rf \"$state_tmpdir\""
  1974. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1975. }
  1976. get_docker_compose_help_msg() {
  1977. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1978. docker_compose_help_msg
  1979. if [ -e "$cache_file" ]; then
  1980. cat "$cache_file" &&
  1981. touch "$cache_file" || return 1
  1982. return 0
  1983. fi
  1984. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  1985. echo "$docker_compose_help_msg" |
  1986. tee "$cache_file" || return 1
  1987. }
  1988. get_docker_compose_usage() {
  1989. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1990. docker_compose_help_msg
  1991. if [ -e "$cache_file" ]; then
  1992. cat "$cache_file" &&
  1993. touch "$cache_file" || return 1
  1994. return 0
  1995. fi
  1996. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  1997. echo "$docker_compose_help_msg" |
  1998. grep -m 1 "^Usage:" -A 10000 |
  1999. egrep -m 1 "^\$" -B 10000 |
  2000. xargs printf "%s " |
  2001. sed -r 's/^Usage: //g' |
  2002. tee "$cache_file" || return 1
  2003. }
  2004. get_docker_compose_opts_help() {
  2005. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2006. docker_compose_help_msg
  2007. if [ -e "$cache_file" ]; then
  2008. cat "$cache_file" &&
  2009. touch "$cache_file" || return 1
  2010. return 0
  2011. fi
  2012. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2013. echo "$docker_compose_opts_help" |
  2014. grep '^Options:' -A 20000 |
  2015. tail -n +2 |
  2016. { cat ; echo; } |
  2017. egrep -m 1 "^\S*\$" -B 10000 |
  2018. head -n -1 |
  2019. tee "$cache_file" || return 1
  2020. }
  2021. get_docker_compose_commands_help() {
  2022. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2023. docker_compose_help_msg
  2024. if [ -e "$cache_file" ]; then
  2025. cat "$cache_file" &&
  2026. touch "$cache_file" || return 1
  2027. return 0
  2028. fi
  2029. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2030. echo "$docker_compose_opts_help" |
  2031. grep '^Commands:' -A 20000 |
  2032. tail -n +2 |
  2033. { cat ; echo; } |
  2034. egrep -m 1 "^\S*\$" -B 10000 |
  2035. head -n -1 |
  2036. tee "$cache_file" || return 1
  2037. }
  2038. get_docker_compose_opts_list() {
  2039. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2040. docker_compose_help_msg
  2041. if [ -e "$cache_file" ]; then
  2042. cat "$cache_file" &&
  2043. touch "$cache_file" || return 1
  2044. return 0
  2045. fi
  2046. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2047. echo "$docker_compose_opts_help" |
  2048. egrep "^\s+-" |
  2049. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2050. tee "$cache_file" || return 1
  2051. }
  2052. options_parser() {
  2053. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2054. printf "\0"
  2055. }
  2056. remove_options_in_option_help_msg() {
  2057. {
  2058. read-0 null
  2059. if [ "$null" ]; then
  2060. err "options parsing error, should start with an option line."
  2061. return 1
  2062. fi
  2063. while read-0 opt full_txt;do
  2064. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2065. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2066. for to_remove in "$@"; do
  2067. str_matches "$to_remove" $multi_opts $single_opts && {
  2068. continue 2
  2069. }
  2070. done
  2071. echo -n "$full_txt"
  2072. done
  2073. } < <(options_parser)
  2074. }
  2075. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2076. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2077. multi_opts_filter() {
  2078. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2079. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2080. tr ',' "\n" | xargs printf "%s "
  2081. }
  2082. single_opts_filter() {
  2083. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2084. tr ',' "\n" | xargs printf "%s "
  2085. }
  2086. get_docker_compose_multi_opts_list() {
  2087. local action="$1" opts_list
  2088. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2089. echo "$opts_list" | multi_opts_filter
  2090. }
  2091. get_docker_compose_single_opts_list() {
  2092. local action="$1" opts_list
  2093. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2094. echo "$opts_list" | single_opts_filter
  2095. }
  2096. display_help() {
  2097. print_help
  2098. echo "${WHITE}Options${NORMAL}:"
  2099. echo " -h, --help Print this message and quit"
  2100. echo " (ignoring any other options)"
  2101. echo " -V, --version Print current version and quit"
  2102. echo " (ignoring any other options)"
  2103. echo " --dirs Display data dirs and quit"
  2104. echo " (ignoring any other options)"
  2105. echo " -v, --verbose Be more verbose"
  2106. echo " -d, --debug Print full debugging information (sets also verbose)"
  2107. echo " --dry-compose-run If docker-compose will be run, only print out what"
  2108. echo " command line will be used."
  2109. echo " --rebuild-relations-to-service, -R SERVICE"
  2110. echo " Will rebuild all relations to given service"
  2111. echo " --add-compose-content, -Y YAML"
  2112. echo " Will merge some direct YAML with the current compose"
  2113. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  2114. filter_docker_compose_help_message
  2115. echo
  2116. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2117. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2118. }
  2119. _graph_service() {
  2120. local service="$1" base="$1"
  2121. charm=$(get_service_charm "$service") || return 1
  2122. metadata=$(charm.metadata "$charm") || return 1
  2123. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  2124. if [ "$subordinate" == "True" ]; then
  2125. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  2126. master_charm=
  2127. while read-0 relation_name relation; do
  2128. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  2129. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  2130. if [ -z "$interface" ]; then
  2131. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  2132. return 1
  2133. fi
  2134. ## Action provided by relation ?
  2135. target_service=
  2136. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  2137. [ "$interface" == "$relation_name" ] && {
  2138. target_service="$candidate_target_service"
  2139. break
  2140. }
  2141. done < <(get_compose_relations "$service")
  2142. if [ -z "$target_service" ]; then
  2143. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  2144. "${DARKYELLOW}$service$NORMAL compose definition."
  2145. return 1
  2146. fi
  2147. master_service="$target_service"
  2148. master_charm=$(get_service_charm "$target_service") || return 1
  2149. break
  2150. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  2151. fi
  2152. _graph_node_service "$service" "$base" "$charm"
  2153. _graph_edge_service "$service" "$subordinate" "$master_service"
  2154. }
  2155. _graph_node_service() {
  2156. local service="$1" base="$2" charm="$3"
  2157. cat <<EOF
  2158. "$(_graph_node_service_label ${service})" [
  2159. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  2160. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  2161. color = $([ "$base" ] && echo "blue" || echo "black")
  2162. fillcolor = "white"
  2163. fontname = "Courier New"
  2164. shape = "Mrecord"
  2165. label =<$(_graph_node_service_content "$service")>
  2166. ];
  2167. EOF
  2168. }
  2169. _graph_edge_service() {
  2170. local service="$1" subordinate="$2" master_service="$3"
  2171. while read-0 relation_name target_service relation_config tech_dep; do
  2172. cat <<EOF
  2173. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  2174. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  2175. fontsize = 16
  2176. fontcolor = "black"
  2177. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  2178. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  2179. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  2180. arrowtail = odot
  2181. # arrowhead = dotlicurve
  2182. taillabel = "$relation_name" ];
  2183. EOF
  2184. done < <(get_compose_relations "$service") || return 1
  2185. }
  2186. _graph_node_service_label() {
  2187. local service="$1"
  2188. echo "service_$service"
  2189. }
  2190. _graph_node_service_content() {
  2191. local service="$1"
  2192. charm=$(get_service_charm "$service") || return 1
  2193. cat <<EOF
  2194. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  2195. <tr>
  2196. <td bgcolor="black" align="center" colspan="2">
  2197. <font color="white">$service</font>
  2198. </td>
  2199. </tr>
  2200. $(if [ "$charm" != "$service" ]; then
  2201. cat <<EOF2
  2202. <tr>
  2203. <td align="left" port="r0">charm: $charm</td>
  2204. </tr>
  2205. EOF2
  2206. fi)
  2207. </table>
  2208. EOF
  2209. }
  2210. cla_contains () {
  2211. local e
  2212. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  2213. return 1
  2214. }
  2215. filter_docker_compose_help_message() {
  2216. cat - |
  2217. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  2218. s/docker-compose.yml/compose.yml/g;
  2219. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  2220. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  2221. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  2222. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  2223. }
  2224. graph() {
  2225. local services=("$@")
  2226. declare -A entries
  2227. cat <<EOF
  2228. digraph g {
  2229. graph [
  2230. fontsize=30
  2231. labelloc="t"
  2232. label=""
  2233. splines=true
  2234. overlap=false
  2235. #rankdir = "LR"
  2236. ];
  2237. ratio = auto;
  2238. EOF
  2239. for target_service in "$@"; do
  2240. services=$(get_ordered_service_dependencies "$target_service") || return 1
  2241. for service in $services; do
  2242. [ "${entries[$service]}" ] && continue || entries[$service]=1
  2243. if cla_contains "$service" "${services[@]}"; then
  2244. base=true
  2245. else
  2246. base=
  2247. fi
  2248. _graph_service "$service" "$base"
  2249. done
  2250. done
  2251. echo "}"
  2252. }
  2253. cached_wget() {
  2254. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2255. url="$1"
  2256. if [ -e "$cache_file" ]; then
  2257. cat "$cache_file"
  2258. touch "$cache_file"
  2259. return 0
  2260. fi
  2261. wget -O- "${url}" |
  2262. tee "$cache_file"
  2263. if [ "${PIPESTATUS[0]}" != 0 ]; then
  2264. rm "$cache_file"
  2265. die "Unable to fetch '$url'."
  2266. return 1
  2267. fi
  2268. }
  2269. export -f cached_wget
  2270. [ "$SOURCED" ] && return 0
  2271. trap_add "EXIT" clean_cache
  2272. # if [[ "$UID" != 0 ]]; then
  2273. # die "'$exname' requires root permissions (for now). Please run as root."
  2274. # fi
  2275. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  2276. if [ -r /etc/default/charm ]; then
  2277. . /etc/default/charm
  2278. fi
  2279. if [ -r "/etc/default/$exname" ]; then
  2280. . "/etc/default/$exname"
  2281. fi
  2282. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  2283. ## userdir ? and global /etc/compose.yml ?
  2284. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  2285. /etc/default/compose /etc/compose/local.conf; do
  2286. [ -e "$cfgfile" ] || continue
  2287. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  2288. done
  2289. fi
  2290. _setup_state_dir
  2291. mkdir -p "$CACHEDIR" || exit 1
  2292. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs printf "%s " | cut -f 2 -d " ") || {
  2293. die "Couldn't determine docker host net"
  2294. }
  2295. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  2296. die "Couldn't determine docker host ip"
  2297. }
  2298. export DOCKER_HOST_NET DOCKER_HOST_IP
  2299. ##
  2300. ## Argument parsing
  2301. ##
  2302. services=()
  2303. remainder_args=()
  2304. compose_opts=()
  2305. compose_contents=()
  2306. action_opts=()
  2307. services_args=()
  2308. pos_arg_ct=0
  2309. no_hooks=
  2310. no_init=
  2311. action=
  2312. stage="main" ## switches from 'main', to 'action', 'remainder'
  2313. is_docker_compose_action=
  2314. rebuild_relations_to_service=()
  2315. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  2316. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  2317. while read-0 arg; do
  2318. case "$stage" in
  2319. "main")
  2320. case "$arg" in
  2321. --help|-h)
  2322. no_init=true ; no_hooks=true ; no_relations=true
  2323. display_help
  2324. exit 0
  2325. ;;
  2326. --verbose|-v)
  2327. export VERBOSE=true
  2328. compose_opts+=("--verbose")
  2329. ;;
  2330. --version|-V)
  2331. print_version
  2332. docker-compose --version
  2333. docker --version
  2334. exit 0
  2335. ;;
  2336. -f|--file)
  2337. read-0 value
  2338. [ -e "$value" ] || die "File $value doesn't exists"
  2339. export DEFAULT_COMPOSE_FILE="$value"
  2340. compose_opts+=("--file $value")
  2341. shift
  2342. ;;
  2343. -p|--project-name)
  2344. read-0 value
  2345. export DEFAULT_PROJECT_NAME="$value"
  2346. compose_opts+=("--project-name $value")
  2347. shift
  2348. ;;
  2349. --no-relations)
  2350. export no_relations=true
  2351. ;;
  2352. --no-hooks)
  2353. export no_hooks=true
  2354. ;;
  2355. --no-init)
  2356. export no_init=true
  2357. ;;
  2358. --rebuild-relations-to-service|-R)
  2359. read-0 value
  2360. rebuild_relations_to_service+=("$value")
  2361. shift
  2362. ;;
  2363. --debug)
  2364. export DEBUG=true
  2365. export VERBOSE=true
  2366. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  2367. ;;
  2368. --add-compose-content|-Y)
  2369. read-0 value
  2370. compose_contents+=("$value")
  2371. shift
  2372. ;;
  2373. --dirs)
  2374. echo "CACHEDIR: $CACHEDIR"
  2375. echo "VARDIR: $VARDIR"
  2376. exit 0
  2377. ;;
  2378. --dry-compose-run)
  2379. export DRY_COMPOSE_RUN=true
  2380. ;;
  2381. --*|-*)
  2382. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2383. read-0 value
  2384. compose_opts+=("$arg" "$value")
  2385. shift;
  2386. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2387. compose_opts+=("$arg")
  2388. else
  2389. err "Unknown option '$arg'. Please check help:"
  2390. display_help
  2391. exit 1
  2392. fi
  2393. ;;
  2394. *)
  2395. action="$arg"
  2396. stage="action"
  2397. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  2398. is_docker_compose_action=true
  2399. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  2400. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  2401. if [ "$DC_MATCH_MULTI" ]; then
  2402. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  2403. fi
  2404. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  2405. pos_args=("${pos_args[@]:1}")
  2406. # echo "USAGE: $DC_USAGE"
  2407. # echo "pos_args: ${pos_args[@]}"
  2408. # echo "MULTI: $DC_MATCH_MULTI"
  2409. # echo "SINGLE: $DC_MATCH_SINGLE"
  2410. # exit 1
  2411. else
  2412. stage="remainder"
  2413. fi
  2414. ;;
  2415. esac
  2416. ;;
  2417. "action") ## Only for docker-compose actions
  2418. case "$arg" in
  2419. --help|-h)
  2420. no_init=true ; no_hooks=true ; no_relations=true
  2421. action_opts+=("$arg")
  2422. ;;
  2423. --*|-*)
  2424. if [ "$is_docker_compose_action" ]; then
  2425. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2426. read-0 value
  2427. action_opts+=("$arg" "$value")
  2428. shift
  2429. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2430. action_opts+=("$arg")
  2431. else
  2432. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  2433. docker-compose "$action" --help |
  2434. filter_docker_compose_help_message >&2
  2435. exit 1
  2436. fi
  2437. fi
  2438. ;;
  2439. *)
  2440. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  2441. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  2442. services_args+=("$arg")
  2443. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  2444. services_args=("$arg") || exit 1
  2445. stage="remainder"
  2446. else
  2447. action_posargs+=("$arg")
  2448. ((pos_arg_ct++))
  2449. fi
  2450. ;;
  2451. esac
  2452. ;;
  2453. "remainder")
  2454. remainder_args+=("$arg")
  2455. while read-0 arg; do
  2456. remainder_args+=("$arg")
  2457. done
  2458. break 3
  2459. ;;
  2460. esac
  2461. shift
  2462. done < <(cla.normalize "$@")
  2463. export compose_contents
  2464. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  2465. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  2466. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  2467. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  2468. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  2469. aexport remainder_args
  2470. ##
  2471. ## Actual code
  2472. ##
  2473. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  2474. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2475. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  2476. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  2477. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  2478. ##
  2479. ## Get services in command line.
  2480. ##
  2481. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  2482. action_service=${remainder_args[0]}
  2483. remainder_args=("${remainder_args[@]:1}")
  2484. if is_service_action=$(has_service_action "$action_service" "$action"); then
  2485. {
  2486. read-0 action_type
  2487. case "$action_type" in
  2488. "relation")
  2489. read-0 _ target_service _target_charm relation_name
  2490. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  2491. ;;
  2492. "direct")
  2493. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  2494. ;;
  2495. esac
  2496. } < <(has_service_action "$action_service" "$action")
  2497. services_args=("$action_service")
  2498. else
  2499. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  2500. fi
  2501. else
  2502. case "$action" in
  2503. ps)
  2504. if [ "${#services_args[@]}" == 0 ]; then
  2505. services_args=($(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys 2>/dev/null)) || true
  2506. fi
  2507. ;;
  2508. up)
  2509. if [ "${#services_args[@]}" == 0 ]; then
  2510. while read-0 service; do
  2511. type="$(get_service_type "$service")" || exit 1
  2512. if [ "$type" != "run-once" ]; then
  2513. services_args+=("$service")
  2514. fi
  2515. done < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  2516. fi
  2517. ;;
  2518. config)
  2519. services_args=("${action_posargs[@]}")
  2520. ;;
  2521. esac
  2522. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  2523. services=($(get_master_services "${services_args[@]}")) || exit 1
  2524. action_posargs+=("${services[@]}")
  2525. fi
  2526. fi
  2527. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  2528. err "Fails to compile base 'docker-compose.yml'"
  2529. exit 1
  2530. }
  2531. ##
  2532. ## Pre-action
  2533. ##
  2534. full_init=
  2535. case "$action" in
  2536. up|run)
  2537. full_init=true
  2538. post_hook=true
  2539. ;;
  2540. ""|down|restart|logs|config|ps)
  2541. full_init=
  2542. ;;
  2543. *)
  2544. if [ "$is_service_action" ]; then
  2545. full_init=true
  2546. fi
  2547. ;;
  2548. esac
  2549. if [ "$full_init" ]; then
  2550. ## init in order
  2551. if [ -z "$no_init" ]; then
  2552. Section setup host resources
  2553. setup_host_resources "${services_args[@]}" || exit 1
  2554. Section initialisation
  2555. run_service_hook init "${services_args[@]}" || exit 1
  2556. fi
  2557. ## Get relations
  2558. if [ -z "$no_relations" ]; then
  2559. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  2560. rebuild_relations_to_service=(
  2561. $(get_master_services "${rebuild_relations_to_service[@]}"))
  2562. project=$(get_default_project_name) || return 1
  2563. for service in "${rebuild_relations_to_service[@]}"; do
  2564. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  2565. [ -d "$dir" ] && {
  2566. debug rm -rf "$dir"
  2567. rm -rf "$dir"
  2568. }
  2569. done
  2570. done
  2571. fi
  2572. run_service_relations "${services_args[@]}" || exit 1
  2573. fi
  2574. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  2575. fi
  2576. if [ "$action" == "run" ]; then
  2577. charm=$(get_service_charm "${services_args[0]}") || exit 1
  2578. metadata=$(charm.metadata "$charm") || exit 1
  2579. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  2580. if [ "$type" == "run-once" ]; then
  2581. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  2582. fi
  2583. fi
  2584. export SERVICE_PACK="${services_args[*]}"
  2585. ##
  2586. ## Docker-compose
  2587. ##
  2588. case "$action" in
  2589. up|start|stop|build|run)
  2590. ## force daemon mode for up
  2591. if [[ "$action" == "up" ]] && ! array_member action_opts -d; then
  2592. action_opts+=("-d")
  2593. fi
  2594. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2595. ;;
  2596. logs)
  2597. if ! array_member action_opts --tail; then ## force daemon mode for up
  2598. action_opts+=("--tail" "10")
  2599. fi
  2600. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2601. ;;
  2602. "")
  2603. launch_docker_compose "${compose_opts[@]}"
  2604. ;;
  2605. graph)
  2606. graph $SERVICE_PACK
  2607. ;;
  2608. config)
  2609. ## removing the services
  2610. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  2611. ## forcing docker-compose config to output the config file to stdout and not stderr
  2612. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  2613. echo "$out"
  2614. exit 1
  2615. }
  2616. echo "$out"
  2617. warn "Runtime configuration modification (from relations) are not included here."
  2618. ;;
  2619. down)
  2620. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  2621. debug "Adding a default argument of '--remove-orphans'"
  2622. action_opts+=("--remove-orphans")
  2623. fi
  2624. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2625. ;;
  2626. *)
  2627. if [ "$is_service_action" ]; then
  2628. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2629. else
  2630. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2631. fi
  2632. ;;
  2633. esac || exit 1
  2634. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  2635. run_service_hook post_deploy "${services_args[@]}" || exit 1
  2636. fi