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.

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