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.

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