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.

3318 lines
110 KiB

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