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.

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