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.

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