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.

4029 lines
132 KiB

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