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.

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