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.

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