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.

3102 lines
104 KiB

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