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.

2962 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
  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. parent=$(while ! [ -e "./compose.yml" ]; do
  1858. [ "$PWD" == "/" ] && exit 0
  1859. cd ..
  1860. done; echo "$PWD"
  1861. )
  1862. if [ "$parent" ]; then
  1863. echo "$parent/compose.yml"
  1864. return 0
  1865. fi
  1866. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  1867. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  1868. warn "No 'compose.yml' was found in current or parent dirs," \
  1869. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  1870. "(${DEFAULT_COMPOSE_FILE})"
  1871. return 0
  1872. fi
  1873. echo "$DEFAULT_COMPOSE_FILE"
  1874. return 0
  1875. fi
  1876. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  1877. return 0
  1878. }
  1879. export -f get_compose_yml_location
  1880. get_compose_yml_content() {
  1881. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  1882. if [ -e "$cache_file" ]; then
  1883. cat "$cache_file" &&
  1884. touch "$cache_file" || return 1
  1885. return 0
  1886. fi
  1887. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  1888. export COMPOSE_YML_FILE
  1889. if [ -e "$COMPOSE_YML_FILE" ]; then
  1890. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  1891. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE")
  1892. else
  1893. debug "No compose file found. Using an empty one."
  1894. COMPOSE_YML_CONTENT=""
  1895. fi
  1896. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  1897. if [ "$?" != 0 ]; then
  1898. outputed_something=
  1899. while IFS='' read -r line1 && IFS='' read -r line2; do
  1900. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  1901. outputed_something=true
  1902. echo "$line1 $GRAY($line2)$NORMAL"
  1903. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  1904. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  1905. prefix " $GRAY|$NORMAL "
  1906. [ "$outputed_something" ] || {
  1907. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  1908. echo "$output" | prefix " $GRAY|$NORMAL "
  1909. }
  1910. exit 1
  1911. fi
  1912. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  1913. }
  1914. export -f get_compose_yml_content
  1915. get_default_target_services() {
  1916. local services=("$@")
  1917. if [ -z "${services[*]}" ]; then
  1918. if [ "$DEFAULT_SERVICES" ]; then
  1919. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  1920. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  1921. services="$DEFAULT_SERVICES"
  1922. else
  1923. err "No service provided."
  1924. return 1
  1925. fi
  1926. fi
  1927. echo "${services[*]}"
  1928. }
  1929. export -f get_default_target_services
  1930. get_master_services() {
  1931. local loaded master_service service
  1932. declare -A loaded
  1933. for service in "$@"; do
  1934. master_service=$(get_top_master_service_for_service "$service") || return 1
  1935. if [ "${loaded[$master_service]}" ]; then
  1936. continue
  1937. fi
  1938. echo "$master_service"
  1939. loaded["$master_service"]=1
  1940. done | xargs printf "%s "
  1941. return "${PIPESTATUS[0]}"
  1942. }
  1943. export -f get_master_services
  1944. _setup_state_dir() {
  1945. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  1946. #debug "Creating temporary state directory in '$state_tmpdir'."
  1947. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  1948. # rm -rf \"$state_tmpdir\""
  1949. trap_add EXIT "rm -rf \"$state_tmpdir\""
  1950. }
  1951. get_docker_compose_help_msg() {
  1952. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1953. docker_compose_help_msg
  1954. if [ -e "$cache_file" ]; then
  1955. cat "$cache_file" &&
  1956. touch "$cache_file" || return 1
  1957. return 0
  1958. fi
  1959. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  1960. echo "$docker_compose_help_msg" |
  1961. tee "$cache_file" || return 1
  1962. }
  1963. get_docker_compose_usage() {
  1964. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1965. docker_compose_help_msg
  1966. if [ -e "$cache_file" ]; then
  1967. cat "$cache_file" &&
  1968. touch "$cache_file" || return 1
  1969. return 0
  1970. fi
  1971. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  1972. echo "$docker_compose_help_msg" |
  1973. grep -m 1 "^Usage:" -A 10000 |
  1974. egrep -m 1 "^\$" -B 10000 |
  1975. xargs printf "%s " |
  1976. sed -r 's/^Usage: //g' |
  1977. tee "$cache_file" || return 1
  1978. }
  1979. get_docker_compose_opts_help() {
  1980. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1981. docker_compose_help_msg
  1982. if [ -e "$cache_file" ]; then
  1983. cat "$cache_file" &&
  1984. touch "$cache_file" || return 1
  1985. return 0
  1986. fi
  1987. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  1988. echo "$docker_compose_opts_help" |
  1989. grep '^Options:' -A 20000 |
  1990. tail -n +2 |
  1991. { cat ; echo; } |
  1992. egrep -m 1 "^\S*\$" -B 10000 |
  1993. head -n -1 |
  1994. tee "$cache_file" || return 1
  1995. }
  1996. get_docker_compose_commands_help() {
  1997. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  1998. docker_compose_help_msg
  1999. if [ -e "$cache_file" ]; then
  2000. cat "$cache_file" &&
  2001. touch "$cache_file" || return 1
  2002. return 0
  2003. fi
  2004. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2005. echo "$docker_compose_opts_help" |
  2006. grep '^Commands:' -A 20000 |
  2007. tail -n +2 |
  2008. { cat ; echo; } |
  2009. egrep -m 1 "^\S*\$" -B 10000 |
  2010. head -n -1 |
  2011. tee "$cache_file" || return 1
  2012. }
  2013. get_docker_compose_opts_list() {
  2014. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2015. docker_compose_help_msg
  2016. if [ -e "$cache_file" ]; then
  2017. cat "$cache_file" &&
  2018. touch "$cache_file" || return 1
  2019. return 0
  2020. fi
  2021. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2022. echo "$docker_compose_opts_help" |
  2023. egrep "^\s+-" |
  2024. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2025. tee "$cache_file" || return 1
  2026. }
  2027. options_parser() {
  2028. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2029. printf "\0"
  2030. }
  2031. remove_options_in_option_help_msg() {
  2032. {
  2033. read-0 null
  2034. if [ "$null" ]; then
  2035. err "options parsing error, should start with an option line."
  2036. return 1
  2037. fi
  2038. while read-0 opt full_txt;do
  2039. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2040. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2041. for to_remove in "$@"; do
  2042. str_matches "$to_remove" $multi_opts $single_opts && {
  2043. continue 2
  2044. }
  2045. done
  2046. echo -n "$full_txt"
  2047. done
  2048. } < <(options_parser)
  2049. }
  2050. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2051. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2052. multi_opts_filter() {
  2053. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2054. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2055. tr ',' "\n" | xargs printf "%s "
  2056. }
  2057. single_opts_filter() {
  2058. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2059. tr ',' "\n" | xargs printf "%s "
  2060. }
  2061. get_docker_compose_multi_opts_list() {
  2062. local action="$1" opts_list
  2063. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2064. echo "$opts_list" | multi_opts_filter
  2065. }
  2066. get_docker_compose_single_opts_list() {
  2067. local action="$1" opts_list
  2068. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2069. echo "$opts_list" | single_opts_filter
  2070. }
  2071. display_help() {
  2072. print_help
  2073. echo "${WHITE}Options${NORMAL}:"
  2074. echo " -h, --help Print this message and quit"
  2075. echo " (ignoring any other options)"
  2076. echo " -V, --version Print current version and quit"
  2077. echo " (ignoring any other options)"
  2078. echo " --dirs Display data dirs and quit"
  2079. echo " (ignoring any other options)"
  2080. echo " -v, --verbose Be more verbose"
  2081. echo " -d, --debug Print full debugging information (sets also verbose)"
  2082. echo " --dry-compose-run If docker-compose will be run, only print out what"
  2083. echo " command line will be used."
  2084. echo " --rebuild-relations-to-service, -R SERVICE"
  2085. echo " Will rebuild all relations to given service"
  2086. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  2087. filter_docker_compose_help_message
  2088. echo
  2089. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2090. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2091. }
  2092. _graph_service() {
  2093. local service="$1" base="$1"
  2094. charm=$(get_service_charm "$service") || return 1
  2095. metadata=$(charm.metadata "$charm") || return 1
  2096. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  2097. if [ "$subordinate" == "True" ]; then
  2098. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  2099. master_charm=
  2100. while read-0 relation_name relation; do
  2101. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  2102. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  2103. if [ -z "$interface" ]; then
  2104. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  2105. return 1
  2106. fi
  2107. ## Action provided by relation ?
  2108. target_service=
  2109. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  2110. [ "$interface" == "$relation_name" ] && {
  2111. target_service="$candidate_target_service"
  2112. break
  2113. }
  2114. done < <(get_compose_relations "$service")
  2115. if [ -z "$target_service" ]; then
  2116. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  2117. "${DARKYELLOW}$service$NORMAL compose definition."
  2118. return 1
  2119. fi
  2120. master_service="$target_service"
  2121. master_charm=$(get_service_charm "$target_service") || return 1
  2122. break
  2123. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  2124. fi
  2125. _graph_node_service "$service" "$base" "$charm"
  2126. _graph_edge_service "$service" "$subordinate" "$master_service"
  2127. }
  2128. _graph_node_service() {
  2129. local service="$1" base="$2" charm="$3"
  2130. cat <<EOF
  2131. "$(_graph_node_service_label ${service})" [
  2132. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  2133. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  2134. color = $([ "$base" ] && echo "blue" || echo "black")
  2135. fillcolor = "white"
  2136. fontname = "Courier New"
  2137. shape = "Mrecord"
  2138. label =<$(_graph_node_service_content "$service")>
  2139. ];
  2140. EOF
  2141. }
  2142. _graph_edge_service() {
  2143. local service="$1" subordinate="$2" master_service="$3"
  2144. while read-0 relation_name target_service relation_config tech_dep; do
  2145. cat <<EOF
  2146. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  2147. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  2148. fontsize = 16
  2149. fontcolor = "black"
  2150. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  2151. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  2152. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  2153. arrowtail = odot
  2154. # arrowhead = dotlicurve
  2155. taillabel = "$relation_name" ];
  2156. EOF
  2157. done < <(get_compose_relations "$service") || return 1
  2158. }
  2159. _graph_node_service_label() {
  2160. local service="$1"
  2161. echo "service_$service"
  2162. }
  2163. _graph_node_service_content() {
  2164. local service="$1"
  2165. charm=$(get_service_charm "$service") || return 1
  2166. cat <<EOF
  2167. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  2168. <tr>
  2169. <td bgcolor="black" align="center" colspan="2">
  2170. <font color="white">$service</font>
  2171. </td>
  2172. </tr>
  2173. $(if [ "$charm" != "$service" ]; then
  2174. cat <<EOF2
  2175. <tr>
  2176. <td align="left" port="r0">charm: $charm</td>
  2177. </tr>
  2178. EOF2
  2179. fi)
  2180. </table>
  2181. EOF
  2182. }
  2183. cla_contains () {
  2184. local e
  2185. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  2186. return 1
  2187. }
  2188. filter_docker_compose_help_message() {
  2189. cat - |
  2190. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  2191. s/docker-compose.yml/compose.yml/g;
  2192. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  2193. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  2194. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  2195. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  2196. }
  2197. graph() {
  2198. local services=("$@")
  2199. declare -A entries
  2200. cat <<EOF
  2201. digraph g {
  2202. graph [
  2203. fontsize=30
  2204. labelloc="t"
  2205. label=""
  2206. splines=true
  2207. overlap=false
  2208. #rankdir = "LR"
  2209. ];
  2210. ratio = auto;
  2211. EOF
  2212. for target_service in "$@"; do
  2213. services=$(get_ordered_service_dependencies "$target_service") || return 1
  2214. for service in $services; do
  2215. [ "${entries[$service]}" ] && continue || entries[$service]=1
  2216. if cla_contains "$service" "${services[@]}"; then
  2217. base=true
  2218. else
  2219. base=
  2220. fi
  2221. _graph_service "$service" "$base"
  2222. done
  2223. done
  2224. echo "}"
  2225. }
  2226. [ "$SOURCED" ] && return 0
  2227. # if [[ "$UID" != 0 ]]; then
  2228. # die "'$exname' requires root permissions (for now). Please run as root."
  2229. # fi
  2230. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  2231. if [ -r /etc/default/charm ]; then
  2232. . /etc/default/charm
  2233. fi
  2234. if [ -r "/etc/default/$exname" ]; then
  2235. . "/etc/default/$exname"
  2236. fi
  2237. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  2238. ## userdir ? and global /etc/compose.yml ?
  2239. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  2240. /etc/default/compose /etc/compose/local.conf; do
  2241. [ -e "$cfgfile" ] || continue
  2242. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  2243. done
  2244. fi
  2245. _setup_state_dir
  2246. mkdir -p "$CACHEDIR" || exit 1
  2247. DOCKER_HOST_NET=$(ip addr show docker0 | grep 'inet ' | xargs printf "%s " | cut -f 2 -d " ") || {
  2248. die "Couldn't determine docker host net"
  2249. }
  2250. DOCKER_HOST_IP=$(echo "$DOCKER_HOST_NET" | cut -f 1 -d "/") || {
  2251. die "Couldn't determine docker host ip"
  2252. }
  2253. export DOCKER_HOST_NET DOCKER_HOST_IP
  2254. ##
  2255. ## Argument parsing
  2256. ##
  2257. services=()
  2258. remainder_args=()
  2259. compose_opts=()
  2260. action_opts=()
  2261. services_args=()
  2262. pos_arg_ct=0
  2263. no_hooks=
  2264. no_init=
  2265. action=
  2266. stage="main" ## switches from 'main', to 'action', 'remainder'
  2267. is_docker_compose_action=
  2268. rebuild_relations_to_service=()
  2269. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  2270. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  2271. while [ "$#" != 0 ]; do
  2272. while read-0 arg; do
  2273. case "$stage" in
  2274. "main")
  2275. case "$arg" in
  2276. --help|-h)
  2277. no_init=true ; no_hooks=true ; no_relations=true
  2278. display_help
  2279. exit 0
  2280. ;;
  2281. --verbose|-v)
  2282. export VERBOSE=true
  2283. compose_opts+=("--verbose")
  2284. ;;
  2285. --version|-V)
  2286. print_version
  2287. docker-compose --version
  2288. docker --version
  2289. exit 0
  2290. ;;
  2291. -f|--file)
  2292. read-0 value
  2293. [ -e "$value" ] || die "File $value doesn't exists"
  2294. export DEFAULT_COMPOSE_FILE="$value"
  2295. compose_opts+=("--file $value")
  2296. shift
  2297. ;;
  2298. -p|--project-name)
  2299. read-0 value
  2300. export DEFAULT_PROJECT_NAME="$value"
  2301. compose_opts+=("--project-name $value")
  2302. shift
  2303. ;;
  2304. --no-relations)
  2305. export no_relations=true
  2306. ;;
  2307. --no-hooks)
  2308. export no_hooks=true
  2309. ;;
  2310. --no-init)
  2311. export no_init=true
  2312. ;;
  2313. --rebuild-relations-to-service|-R)
  2314. read-0 value
  2315. rebuild_relations_to_service+=("$value")
  2316. shift
  2317. ;;
  2318. --debug)
  2319. export DEBUG=true
  2320. export VERBOSE=true
  2321. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  2322. ;;
  2323. --dirs)
  2324. echo "CACHEDIR: $CACHEDIR"
  2325. echo "VARDIR: $VARDIR"
  2326. exit 0
  2327. ;;
  2328. --dry-compose-run)
  2329. export DRY_COMPOSE_RUN=true
  2330. ;;
  2331. --*|-*)
  2332. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2333. read-0 value
  2334. compose_opts+=("$arg" "$value")
  2335. shift;
  2336. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2337. compose_opts+=("$arg")
  2338. else
  2339. err "Unknown option '$arg'. Please check help:"
  2340. display_help
  2341. exit 1
  2342. fi
  2343. ;;
  2344. *)
  2345. action="$arg"
  2346. stage="action"
  2347. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  2348. is_docker_compose_action=true
  2349. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  2350. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  2351. if [ "$DC_MATCH_MULTI" ]; then
  2352. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  2353. fi
  2354. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  2355. pos_args=("${pos_args[@]:1}")
  2356. # echo "USAGE: $DC_USAGE"
  2357. # echo "pos_args: ${pos_args[@]}"
  2358. # echo "MULTI: $DC_MATCH_MULTI"
  2359. # echo "SINGLE: $DC_MATCH_SINGLE"
  2360. # exit 1
  2361. else
  2362. stage="remainder"
  2363. fi
  2364. ;;
  2365. esac
  2366. ;;
  2367. "action") ## Only for docker-compose actions
  2368. case "$arg" in
  2369. --help|-h)
  2370. no_init=true ; no_hooks=true ; no_relations=true
  2371. action_opts+=("$arg")
  2372. ;;
  2373. --*|-*)
  2374. if [ "$is_docker_compose_action" ]; then
  2375. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  2376. read-0 value
  2377. action_opts+=("$arg" "$value")
  2378. shift
  2379. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  2380. action_opts+=("$arg")
  2381. else
  2382. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  2383. docker-compose "$action" --help |
  2384. filter_docker_compose_help_message >&2
  2385. exit 1
  2386. fi
  2387. fi
  2388. ;;
  2389. *)
  2390. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  2391. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  2392. services_args+=("$arg")
  2393. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  2394. services_args=("$arg") || exit 1
  2395. stage="remainder"
  2396. else
  2397. action_posargs+=("$arg")
  2398. ((pos_arg_ct++))
  2399. fi
  2400. ;;
  2401. esac
  2402. ;;
  2403. "remainder")
  2404. remainder_args+=("$arg")
  2405. while read-0 arg; do
  2406. remainder_args+=("$arg")
  2407. done
  2408. shift
  2409. remainder_args+=("$@")
  2410. break 3
  2411. ;;
  2412. esac
  2413. shift
  2414. done < <(cla.normalize "$1")
  2415. done
  2416. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  2417. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  2418. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  2419. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  2420. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  2421. ##
  2422. ## Actual code
  2423. ##
  2424. export DOCKER_DATASTORE=${DOCKER_DATASTORE:-/srv/docker-datastore}
  2425. export COMPOSE_YML_CONTENT
  2426. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  2427. ##
  2428. ## Get services in command line.
  2429. ##
  2430. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  2431. if is_service_action=$(has_service_action "${action_posargs[0]}" "$action"); then
  2432. {
  2433. read-0 action_type
  2434. case "$action_type" in
  2435. "relation")
  2436. read-0 _ target_service _target_charm relation_name
  2437. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  2438. ;;
  2439. "direct")
  2440. debug "Found action $DARKYELLOW${action_posargs[0]}$NORMAL.$DARKCYAN$action$NORMAL"
  2441. ;;
  2442. esac
  2443. } < <(has_service_action "${action_posargs[0]}" "$action")
  2444. services=("${action_posargs[0]}")
  2445. else
  2446. die "Unknown command: It doesn't match any docker-compose commands nor inner charm actions."
  2447. fi
  2448. else
  2449. if [[ "$action" =~ (up|ps) && "${#services_args[@]}" == 0 ]]; then
  2450. services_args=($(shyaml keys <"$COMPOSE_YML_FILE"))
  2451. fi
  2452. if [ "$action" == "config" ]; then
  2453. services_args=("${action_posargs[@]}")
  2454. fi
  2455. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  2456. services=($(get_master_services "${services_args[@]}")) || exit 1
  2457. action_posargs+=("${services[@]}")
  2458. fi
  2459. fi
  2460. get_docker_compose "${services[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  2461. err "Fails to compile base 'docker-compose.yml'"
  2462. exit 1
  2463. }
  2464. ##
  2465. ## Pre-action
  2466. ##
  2467. full_init=
  2468. case "$action" in
  2469. up|run)
  2470. full_init=true
  2471. post_hook=true
  2472. ;;
  2473. ""|down|restart|logs|config|ps)
  2474. full_init=
  2475. ;;
  2476. *)
  2477. if [ "$is_service_action" ]; then
  2478. full_init=true
  2479. fi
  2480. ;;
  2481. esac
  2482. if [ "$full_init" ]; then
  2483. ## init in order
  2484. if [ -z "$no_init" ]; then
  2485. Section setup host resources
  2486. setup_host_resources "${services[@]}" || exit 1
  2487. Section initialisation
  2488. run_service_hook init "${services[@]}" || exit 1
  2489. fi
  2490. ## Get relations
  2491. if [ -z "$no_relations" ]; then
  2492. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  2493. rebuild_relations_to_service=(
  2494. $(get_master_services "${rebuild_relations_to_service[@]}"))
  2495. project=$(get_default_project_name) || return 1
  2496. for service in "${rebuild_relations_to_service[@]}"; do
  2497. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  2498. [ -d "$dir" ] && rm -rf "$dir"
  2499. done
  2500. done
  2501. fi
  2502. run_service_relations "${services[@]}" || exit 1
  2503. fi
  2504. run_service_hook pre_deploy "${services[@]}" || exit 1
  2505. fi
  2506. export SERVICE_PACK="${services[*]}"
  2507. ##
  2508. ## Docker-compose
  2509. ##
  2510. case "$action" in
  2511. up|start|stop|build|run)
  2512. if [[ "$action" == "up" ]] && ! array_member action_opts -d; then ## force daemon mode for up
  2513. action_opts+=("-d")
  2514. fi
  2515. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2516. ;;
  2517. logs)
  2518. if ! array_member action_opts --tail; then ## force daemon mode for up
  2519. action_opts+=("--tail" "10")
  2520. fi
  2521. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2522. ;;
  2523. "")
  2524. launch_docker_compose "${compose_opts[@]}"
  2525. ;;
  2526. graph)
  2527. graph $SERVICE_PACK
  2528. ;;
  2529. config)
  2530. ## removing the services
  2531. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  2532. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2533. warn "Runtime configuration modification (from relations) are not included here."
  2534. ;;
  2535. down)
  2536. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  2537. debug "Adding a default argument of '--remove-orphans'"
  2538. action_opts+=("--remove-orphans")
  2539. fi
  2540. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  2541. ;;
  2542. *)
  2543. if [ "$is_service_action" ]; then
  2544. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  2545. else
  2546. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  2547. fi
  2548. ;;
  2549. esac || exit 1
  2550. if [ "$post_hook" -a "${#services[@]}" != 0 ]; then
  2551. run_service_hook post_deploy "${services[@]}" || exit 1
  2552. fi