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.

3243 lines
107 KiB

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