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.

3205 lines
107 KiB

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