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.

4034 lines
133 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. charm=$(echo "$result" |shyaml get-value charm 2>/dev/null) || return 1
  949. if default_options=$(printf "%s" "$metadata" | shyaml -y -q get-value default-options); then
  950. default_options=$(yaml_key_val_str "options" "$default_options") || return 1
  951. result=$(merge_yaml_str "$default_options" "$result") || return 1
  952. fi
  953. echo "$result" | tee "$cache_file" || return 1
  954. }
  955. export -f get_compose_service_def
  956. _get_service_charm_cached () {
  957. local service="$1" service_def="$2" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  958. if [ -e "$cache_file" ]; then
  959. # debug "$FUNCNAME: cache hit $1"
  960. cat "$cache_file" &&
  961. touch "$cache_file" || return 1
  962. return 0
  963. fi
  964. charm=$(echo "$service_def" | shyaml get-value charm 2>/dev/null)
  965. if [ -z "$charm" ]; then
  966. err "Missing ${WHITE}charm${NORMAL} value in service $DARKYELLOW$service$NORMAL definition."
  967. return 1
  968. fi
  969. echo "$charm" | tee "$cache_file" || return 1
  970. }
  971. export -f _get_service_charm_cached
  972. get_service_charm () {
  973. local service="$1"
  974. if [ -z "$service" ]; then
  975. echo ${FUNCNAME[@]} >&2
  976. print_syntax_error "$FUNCNAME: Please specify a service as first argument."
  977. return 1
  978. fi
  979. service_def=$(get_compose_service_def "$service") || return 1
  980. _get_service_charm_cached "$service" "$service_def"
  981. }
  982. export -f get_service_charm
  983. ## built above the docker-compose abstraction, so it relies on the
  984. ## full docker-compose.yml to be already built.
  985. get_service_def () {
  986. local service="$1" def
  987. if [ -z "$_current_docker_compose" ]; then
  988. print_syntax_error "$FUNCNAME is meant to be called after"\
  989. "\$_current_docker_compose has been calculated."
  990. fi
  991. def=$(echo "$_current_docker_compose" | shyaml get-value "services.${service//./\\.}" 2>/dev/null)
  992. if [ -z "$def" ]; then
  993. err "No definition for service $DARKYELLOW$service$NORMAL in compiled 'docker-compose.yml'."
  994. return 1
  995. fi
  996. echo "$def"
  997. }
  998. export -f get_service_def
  999. ## Return the base docker image name of a service
  1000. service_base_docker_image() {
  1001. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1002. master_service service_def service_image service_build service_dockerfile
  1003. if [ -e "$cache_file" ]; then
  1004. # debug "$FUNCNAME: cache hit ($*)"
  1005. cat "$cache_file"
  1006. return 0
  1007. fi
  1008. master_service="$(get_top_master_service_for_service "$service")" || {
  1009. err "Could not compute master service for service $DARKYELLOW$service$NORMAL."
  1010. return 1
  1011. }
  1012. service_def="$(get_service_def "$master_service")" || {
  1013. err "Could not get docker-compose service definition for $DARKYELLOW$master_service$NORMAL."
  1014. return 1
  1015. }
  1016. service_image=$(echo "$service_def" | shyaml get-value image 2>/dev/null)
  1017. if [ "$?" != 0 ]; then
  1018. ## According to https://stackoverflow.com/questions/32230577 , if there's a build,
  1019. ## then the builded image will get name ${project}_${service}
  1020. project=$(get_default_project_name) || return 1
  1021. image_name="${project}_${service}"
  1022. if ! docker_has_image "$image_name"; then
  1023. service_build=$(echo "$service_def" | shyaml get-value build 2>/dev/null)
  1024. if [ "$?" != 0 ]; then
  1025. err "Service $DARKYELLOW$service$NORMAL has no ${WHITE}image${NORMAL} nor ${WHITE}build${NORMAL} parameter."
  1026. echo "$service_def" >&2
  1027. return 1
  1028. fi
  1029. docker build "$service_build" -t "${project}_${service}" >&2 || {
  1030. err "Failed to build image for ${DARKYELLOW}$service${NORMAL}."
  1031. return 1
  1032. }
  1033. fi
  1034. printf "%s" "${project}_${service}"
  1035. else
  1036. printf "%s" "${service_image}"
  1037. fi | tee "$cache_file"
  1038. if [ "${PIPESTATUS[0]}" != 0 ]; then
  1039. rm "$cache_file"
  1040. return 1
  1041. fi
  1042. }
  1043. export -f service_base_docker_image
  1044. get_charm_relation_def () {
  1045. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1046. relation_def metadata
  1047. if [ -e "$cache_file" ]; then
  1048. # debug "$FUNCNAME: cache hit ($*)"
  1049. cat "$cache_file"
  1050. return 0
  1051. fi
  1052. metadata="$(charm.metadata "$charm")" || return 1
  1053. relation_def="$(echo "$metadata" | shyaml get-value "provides.${relation_name}" 2>/dev/null)"
  1054. echo "$relation_def" | tee "$cache_file"
  1055. }
  1056. export -f get_charm_relation_def
  1057. get_charm_tech_dep_orientation_for_relation() {
  1058. local charm="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1059. relation_def value
  1060. if [ -e "$cache_file" ]; then
  1061. # debug "$FUNCNAME: cache hit ($*)"
  1062. cat "$cache_file"
  1063. return 0
  1064. fi
  1065. relation_def=$(get_charm_relation_def "$charm" "$relation_name" 2>/dev/null)
  1066. value=$(echo "$relation_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1067. value=${value:-True}
  1068. printf "%s" "$value" | tee "$cache_file"
  1069. }
  1070. export -f get_charm_tech_dep_orientation_for_relation
  1071. get_service_relation_tech_dep() {
  1072. local service="$1" relation_name="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1.$2" \
  1073. charm tech_dep
  1074. if [ -e "$cache_file" ]; then
  1075. # debug "$FUNCNAME: cache hit ($*)"
  1076. cat "$cache_file"
  1077. return 0
  1078. fi
  1079. charm=$(get_service_charm "$service") || return 1
  1080. tech_dep="$(get_charm_tech_dep_orientation_for_relation "$charm" "$relation_name")" || return 1
  1081. printf "%s" "$tech_dep" | tee "$cache_file"
  1082. }
  1083. export -f get_service_relation_tech_dep
  1084. ##
  1085. ## Use compose file to get deps, and relation definition in metadata.yml
  1086. ## for tech-dep attribute.
  1087. get_service_deps() {
  1088. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1089. if [ -e "$cache_file" ]; then
  1090. # debug "$FUNCNAME: cache hit ($*)"
  1091. cat "$cache_file"
  1092. return 0
  1093. fi
  1094. (
  1095. set -o pipefail
  1096. get_service_relations "$service" | \
  1097. while read-0 relation_name target_service _relation_config tech_dep; do
  1098. echo "$target_service"
  1099. done | tee "$cache_file"
  1100. ) || return 1
  1101. }
  1102. export -f get_service_deps
  1103. _rec_get_depth() {
  1104. local elt=$1 dep deps max cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  1105. [ "${depths[$elt]}" ] && return 0
  1106. if [ -e "$cache_file" ]; then
  1107. # debug "$FUNCNAME: cache hit ($*)"
  1108. depths[$elt]=$(cat "$cache_file")
  1109. return 0
  1110. fi
  1111. visited[$elt]=1
  1112. #debug "Setting visited[$elt]"
  1113. #debug "Asking for $DARKYELLOW$elt$NORMAL dependencies"
  1114. deps=$(get_service_deps "$elt") || {
  1115. debug "Failed get_service_deps $elt"
  1116. return 1
  1117. }
  1118. # debug "$elt deps are:" $deps
  1119. max=0
  1120. for dep in $deps; do
  1121. [ "${visited[$dep]}" ] && {
  1122. #debug "Already computing $dep"
  1123. continue
  1124. }
  1125. _rec_get_depth "$dep" || return 1
  1126. #debug "Requesting depth[$dep]"
  1127. if (( ${depths[$dep]} > max )); then
  1128. max="${depths[$dep]}"
  1129. fi
  1130. done
  1131. # debug "Setting depth[$elt] to $((max + 1))"
  1132. depths[$elt]=$((max + 1))
  1133. echo "${depths[$elt]}" > $cache_file
  1134. }
  1135. export -f _rec_get_depth
  1136. get_ordered_service_dependencies() {
  1137. local services=("$@") cache_file="$state_tmpdir/$FUNCNAME.cache.$(echo "$*" | md5_compat)"
  1138. if [ -e "$cache_file" ]; then
  1139. # debug "$FUNCNAME: cache hit ($*)"
  1140. cat "$cache_file"
  1141. return 0
  1142. fi
  1143. #debug "Figuring ordered deps of $DARKYELLOW$services$NORMAL"
  1144. if [ -z "${services[*]}" ]; then
  1145. return 0
  1146. # print_syntax_error "$FUNCNAME: no arguments"
  1147. # return 1
  1148. fi
  1149. declare -A depths
  1150. declare -A visited
  1151. heads=("${services[@]}")
  1152. while [ "${#heads[@]}" != 0 ]; do
  1153. array_pop heads head
  1154. _rec_get_depth "$head" || return 1
  1155. done
  1156. i=0
  1157. while [ "${#depths[@]}" != 0 ]; do
  1158. for key in "${!depths[@]}"; do
  1159. value="${depths[$key]}"
  1160. if [ "$value" == "$i" ]; then
  1161. echo "$key"
  1162. unset depths[$key]
  1163. fi
  1164. done
  1165. i=$((i + 1))
  1166. done | tee "$cache_file"
  1167. }
  1168. export -f get_ordered_service_dependencies
  1169. run_service_hook () {
  1170. local action="$1" service subservice subservices loaded
  1171. shift
  1172. declare -A loaded
  1173. for service in "$@"; do
  1174. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1175. for subservice in $subservices; do
  1176. if [ "${loaded[$subservice]}" ]; then
  1177. ## Prevent double inclusion of same service if this
  1178. ## service is deps of two or more of your
  1179. ## requirements.
  1180. continue
  1181. fi
  1182. charm=$(get_service_charm "$subservice") || return 1
  1183. charm.has_hook "$charm" "$action" >/dev/null || continue
  1184. PROJECT_NAME=$(get_default_project_name) || return 1
  1185. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  1186. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  1187. DOCKER_BASE_IMAGE=$(service_base_docker_image "$MASTER_BASE_SERVICE_NAME") || return 1
  1188. Wrap -d "running $YELLOW$action$NORMAL hook of $DARKYELLOW$subservice$NORMAL in charm $DARKPINK$charm$NORMAL" <<EOF || return 1
  1189. export DOCKER_BASE_IMAGE="$DOCKER_BASE_IMAGE"
  1190. export SERVICE_NAME=$subservice
  1191. export IMAGE_NAME=$(echo "${PROJECT_NAME}" | tr -d "_-")_\${SERVICE_NAME}
  1192. export CONTAINER_NAME=\${IMAGE_NAME}_1
  1193. export CHARM_NAME="$charm"
  1194. export PROJECT_NAME="$PROJECT_NAME"
  1195. export SERVICE_DATASTORE="$DATASTORE/$subservice"
  1196. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$subservice"
  1197. export MASTER_BASE_SERVICE_NAME="$MASTER_BASE_SERVICE_NAME"
  1198. export MASTER_BASE_CHARM_NAME="$MASTER_BASE_CHARM_NAME"
  1199. charm.run_hook "$charm" "$action"
  1200. EOF
  1201. loaded[$subservice]=1
  1202. done
  1203. done
  1204. return 0
  1205. }
  1206. host_resource_get() {
  1207. local location="$1" cfg="$2"
  1208. type=$(echo "$cfg" | shyaml get-value type 2>/dev/null) || {
  1209. err "Missing ${WHITE}type$NORMAL option in ${WHITE}get$NORMAL config for location '$location'"
  1210. return 1
  1211. }
  1212. if fn.exists host_resource_get_$type; then
  1213. host_resource_get_$type "$location" "$cfg"
  1214. else
  1215. err "Source ${WHITE}source$NORMAL type '$type' unknown for" \
  1216. "${WHITE}host-resource$NORMAL '$location' defined in" \
  1217. "$DARKYELLOW$subservice$NORMAL config."
  1218. return 1
  1219. fi
  1220. }
  1221. export -f host_resource_get
  1222. host_resource_get_git() {
  1223. local location="$1" cfg="$2" branch parent url
  1224. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1225. branch=${branch:-master}
  1226. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1227. parent="$(dirname "$location")"
  1228. (
  1229. mkdir -p "$parent" && cd "$parent" &&
  1230. git clone -b "$branch" "$url" "$(basename "$location")"
  1231. ) || return 1
  1232. }
  1233. export -f host_resource_get_git
  1234. host_resource_get_git-sub() {
  1235. local location="$1" cfg="$2" branch parent url
  1236. branch=$(echo "$cfg" | shyaml get-value branch 2>/dev/null)
  1237. branch=${branch:-master}
  1238. url=$(echo "$cfg" | shyaml get-value url 2>/dev/null)
  1239. parent="$(dirname "$location")"
  1240. (
  1241. mkdir -p "$parent" && cd "$parent" &&
  1242. git sub clone -b "$branch" "$url" "$(basename "$location")"
  1243. ) || return 1
  1244. }
  1245. export -f host_resource_get_git-sub
  1246. setup_host_resource () {
  1247. local subservice="$1" service_def location get cfg
  1248. service_def=$(get_compose_service_def "$subservice") || return 1
  1249. while read-0 location cfg; do
  1250. ## XXXvlab: will it be a git resources always ?
  1251. if [ -d "$location" -a ! -d "$location/.git" ]; then
  1252. err "Hum, location '$location' does not seem to be a git directory."
  1253. return 1
  1254. fi
  1255. if [ -d "$location" ]; then
  1256. info "host resource '$location' already set up."
  1257. continue
  1258. fi
  1259. get=$(echo "$cfg" | shyaml get-value get 2>/dev/null)
  1260. if [ -z "$get" ]; then
  1261. err "No host directory '$location' found, and no ${WHITE}source$NORMAL" \
  1262. "specified for $DARKYELLOW$subservice$NORMAL."
  1263. return 1
  1264. fi
  1265. host_resource_get "$location" "$get" || return 1
  1266. done < <(echo "$service_def" | shyaml key-values-0 host-resources 2>/dev/null)
  1267. }
  1268. export -f setup_host_resource
  1269. setup_host_resources () {
  1270. local service subservices subservice loaded
  1271. declare -A loaded
  1272. for service in "$@"; do
  1273. subservices=$(get_ordered_service_dependencies "$service") || return 1
  1274. for subservice in $subservices; do
  1275. if [ "${loaded[$subservice]}" ]; then
  1276. ## Prevent double inclusion of same service if this
  1277. ## service is deps of two or more of your
  1278. ## requirements.
  1279. continue
  1280. fi
  1281. setup_host_resource "$service"
  1282. loaded[$subservice]=1
  1283. done
  1284. done
  1285. return 0
  1286. }
  1287. export -f setup_host_resources
  1288. relation-get () {
  1289. local key="$1" out
  1290. if ! out=$(cat "$RELATION_DATA_FILE" | shyaml -y get-value "$key" 2>/dev/null); then
  1291. err "The key $WHITE$key$NORMAL was not found in relation's data."
  1292. return 1
  1293. fi
  1294. echo "$out" | yaml_get_interpret
  1295. }
  1296. export -f relation-get
  1297. expand_vars() {
  1298. local unlikely_prefix="UNLIKELY_PREFIX"
  1299. content=$(cat -)
  1300. ## find first identifier not in content
  1301. remaining_lines=$(echo "$content" | grep "^$unlikely_prefix")
  1302. while [ "$(echo "$remaining_lines" | grep "^$unlikely_prefix$")" ]; do
  1303. size_prefix="${#unlikely_prefix}"
  1304. first_matching=$(echo "$remaining_lines" |
  1305. grep -v "^$unlikely_prefix$" |
  1306. uniq -w "$((size_prefix + 1))" -c |
  1307. sort -rn |
  1308. head -n 1)
  1309. first_matching=${first_matching#"${x%%[![:space:]]*}"}
  1310. first_matching="${first_matching#* }"
  1311. next_char=${first_matching:$size_prefix:1}
  1312. if [ "$next_char" != "0" ]; then
  1313. unlikely_prefix+="0"
  1314. else
  1315. unlikely_prefix+="1"
  1316. fi
  1317. remaining_lines=$(echo "$remaining_lines" | grep "^$unlikely_prefix")
  1318. done
  1319. eval "cat <<$unlikely_prefix
  1320. $content
  1321. $unlikely_prefix"
  1322. }
  1323. export -f expand_vars
  1324. yaml_get_interpret() {
  1325. local content tag
  1326. content=$(cat -)
  1327. tag=$(echo "$content" | shyaml -y get-value) || return 1
  1328. tag="${tag%% *}"
  1329. content=$(echo "$content" | shyaml get-value) || return 1
  1330. if ! [ "${tag:0:1}" == "!" ]; then
  1331. echo "$content" || return 1
  1332. return 0
  1333. fi
  1334. case "$tag" in
  1335. "!bash-stdout")
  1336. echo "$content" | bash || {
  1337. err "shell code didn't end with errorlevel 0"
  1338. return 1
  1339. }
  1340. ;;
  1341. "!var-expand")
  1342. echo "$content" | expand_vars || {
  1343. err "shell expansion failed"
  1344. return 1
  1345. }
  1346. ;;
  1347. *)
  1348. err "Invalid object tag ${WHITE}$tag${NORMAL}"
  1349. return 1
  1350. ;;
  1351. esac
  1352. }
  1353. export -f yaml_get_interpret
  1354. options-get () {
  1355. local key="$1" out
  1356. service_def=$(get_compose_service_def "$SERVICE_NAME") || return 1
  1357. if ! out=$(echo "$service_def" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1358. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1359. return 1
  1360. fi
  1361. echo "$out" | yaml_get_interpret
  1362. }
  1363. export -f options-get
  1364. relation-base-compose-get () {
  1365. local key="$1" out
  1366. if ! out=$(echo "$RELATION_BASE_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1367. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1368. return 1
  1369. fi
  1370. echo "$out" | yaml_get_interpret
  1371. }
  1372. export -f relation-base-compose-get
  1373. relation-target-compose-get () {
  1374. local key="$1" out
  1375. if ! out=$(echo "$RELATION_TARGET_COMPOSE_DEF" | shyaml -y get-value "options.$key" 2>/dev/null); then
  1376. err "The key $WHITE$key$NORMAL was not found in base service compose definition.."
  1377. return 1
  1378. fi
  1379. echo "$out" | yaml_get_interpret
  1380. }
  1381. export -f relation-target-compose-get
  1382. relation-set () {
  1383. local key="$1" value="$2"
  1384. if [ -z "$RELATION_DATA_FILE" ]; then
  1385. err "$FUNCNAME: relation does not seems to be correctly setup."
  1386. return 1
  1387. fi
  1388. if ! [ -r "$RELATION_DATA_FILE" ]; then
  1389. err "$FUNCNAME: can't read relation's data." >&2
  1390. return 1
  1391. fi
  1392. _config_merge "$RELATION_DATA_FILE" <(yaml_key_val_str "$key" "$value")
  1393. }
  1394. export -f relation-set
  1395. _config_merge() {
  1396. local config_filename="$1" merge_to_file="$2"
  1397. touch "$config_filename" &&
  1398. merge_yaml "$config_filename" "$merge_to_file" > "$config_filename.tmp" || return 1
  1399. mv "$config_filename.tmp" "$config_filename"
  1400. }
  1401. export -f _config_merge
  1402. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1403. config-add() {
  1404. local metadata="$1"
  1405. _config_merge "$RELATION_CONFIG" <(echo "$metadata")
  1406. }
  1407. export -f config-add
  1408. ## XXXvlab; this can be used only in relation, I'd like to use it in init.
  1409. init-config-add() {
  1410. local metadata="$1"
  1411. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" \
  1412. <(yaml_key_val_str "services" "$metadata")
  1413. }
  1414. export -f init-config-add
  1415. logstdout() {
  1416. local name="$1"
  1417. sed -r 's%^%'"${name}"'> %g'
  1418. }
  1419. export -f logstdout
  1420. logstderr() {
  1421. local name="$1"
  1422. sed -r 's%^(.*)$%'"${RED}${name}>${NORMAL} \1"'%g'
  1423. }
  1424. export -f logstderr
  1425. _run_service_relation () {
  1426. local relation_name="$1" service="$2" target_service="$3" relation_config="$4" relation_dir services
  1427. charm=$(get_service_charm "$service") || return 1
  1428. target_charm=$(get_service_charm "$target_service") || return 1
  1429. base_script_name=$(charm.has_relation_hook "$charm" "$relation_name" relation-joined) || true
  1430. target_script_name=$(charm.has_relation_hook "$target_charm" "$relation_name" relation-joined) || true
  1431. [ "$base_script_name" -o "$target_script_name" ] || return 0
  1432. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  1433. RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config") || return 1
  1434. export BASE_SERVICE_NAME=$service
  1435. export BASE_CHARM_NAME=$charm
  1436. export BASE_CHARM_PATH=$(charm.get_dir "$charm")
  1437. export TARGET_SERVICE_NAME=$target_service
  1438. export TARGET_CHARM_NAME=$target_charm
  1439. export TARGET_CHARM_PATH=$(charm.get_dir "$target_charm")
  1440. export RELATION_DATA_FILE
  1441. target_errlvl=0
  1442. if [ -z "$target_script_name" ]; then
  1443. verb "No relation script $DARKBLUE$relation_name$NORMAL in target $DARKPINK$target_charm$NORMAL."
  1444. else
  1445. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1446. "for target $DARKYELLOW$target_service$NORMAL (charm $DARKPINK$target_charm$NORMAL)"
  1447. RELATION_CONFIG="$relation_dir/config_provider"
  1448. DOCKER_BASE_IMAGE=$(service_base_docker_image "$target_service") || return 1
  1449. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1450. {
  1451. (
  1452. SERVICE_NAME=$target_service
  1453. SERVICE_DATASTORE="$DATASTORE/$target_service"
  1454. SERVICE_CONFIGSTORE="$CONFIGSTORE/$target_service"
  1455. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1456. charm.run_relation_hook "$target_charm" "$relation_name" relation-joined
  1457. echo "$?" > "$relation_dir/target_errlvl"
  1458. ) | logstdout "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1459. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$target_service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@${NORMAL}" 3>&1 1>&2 2>&3
  1460. target_errlvl="$(cat "$relation_dir/target_errlvl")" || {
  1461. err "Relation script '$script_name' in $DARKPINK$target_charm$NORMAL" \
  1462. "failed before outputing an errorlevel."
  1463. ((target_errlvl |= "1" ))
  1464. }
  1465. if [ -e "$RELATION_CONFIG" ]; then
  1466. debug "Merging some new config info in $DARKYELLOW$target_service$NORMAL"
  1467. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1468. rm "$RELATION_CONFIG"
  1469. ((target_errlvl |= "$?"))
  1470. fi
  1471. fi
  1472. if [ "$target_errlvl" == 0 ]; then
  1473. errlvl=0
  1474. if [ "$base_script_name" ]; then
  1475. verb "Running ${DARKBLUE}$relation_name${NORMAL} relation-joined script" \
  1476. "for $DARKYELLOW$service$NORMAL (charm $DARKPINK$charm$NORMAL)"
  1477. RELATION_CONFIG="$relation_dir/config_providee"
  1478. RELATION_DATA="$(cat "$RELATION_DATA_FILE")"
  1479. DOCKER_BASE_IMAGE=$(service_base_docker_image "$service") || return 1
  1480. export DOCKER_BASE_IMAGE RELATION_CONFIG RELATION_DATA
  1481. {
  1482. (
  1483. SERVICE_NAME=$service
  1484. SERVICE_DATASTORE="$DATASTORE/$service"
  1485. SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  1486. export SERVICE_NAME DOCKER_BASE_IMAGE SERVICE_DATASTORE SERVICE_CONFIGSTORE
  1487. charm.run_relation_hook "$charm" "$relation_name" relation-joined
  1488. echo "$?" > "$relation_dir/errlvl"
  1489. ) | logstdout "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${GREEN}@${NORMAL}"
  1490. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/$DARKBLUE$relation_name$NORMAL (joined) ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  1491. errlvl="$(cat "$relation_dir/errlvl")" || {
  1492. err "Relation script '$script_name' in $DARKPINK$charm$NORMAL" \
  1493. "failed before outputing an errorlevel."
  1494. ((errlvl |= "1" ))
  1495. }
  1496. if [ -e "$RELATION_CONFIG" ]; then
  1497. _config_merge "$state_tmpdir/to-merge-in-docker-compose.yml" "$RELATION_CONFIG" &&
  1498. rm "$RELATION_CONFIG"
  1499. ((errlvl |= "$?" ))
  1500. fi
  1501. if [ "$errlvl" != 0 ]; then
  1502. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$service$NORMAL failed to run properly."
  1503. fi
  1504. else
  1505. verb "No relation script '$script_name' in charm $DARKPINK$charm$NORMAL. Ignoring."
  1506. fi
  1507. else
  1508. err "Relation $DARKBLUE$relation_name$NORMAL on $DARKYELLOW$target_service$NORMAL failed to run properly."
  1509. fi
  1510. if [ "$target_errlvl" == 0 -a "$errlvl" == 0 ]; then
  1511. debug "Relation $DARKBLUE$relation_name$NORMAL is established" \
  1512. "between $DARKYELLOW$service$NORMAL and $DARKYELLOW$target_service$NORMAL."
  1513. return 0
  1514. else
  1515. return 1
  1516. fi
  1517. }
  1518. export -f _run_service_relation
  1519. _get_compose_relations_cached () {
  1520. local compose_service_def="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  1521. relation_name relation_def target_service
  1522. if [ -e "$cache_file" ]; then
  1523. #debug "$FUNCNAME: STATIC cache hit $1"
  1524. cat "$cache_file" &&
  1525. touch "$cache_file" || return 1
  1526. return 0
  1527. fi
  1528. (
  1529. set -o pipefail
  1530. if [ "$compose_service_def" ]; then
  1531. while read-0 relation_name relation_def; do
  1532. ## XXXvlab: could we use braces here instead of parenthesis ?
  1533. (
  1534. case "$(echo "$relation_def" | shyaml get-type 2>/dev/null)" in
  1535. "str")
  1536. target_service="$(echo "$relation_def" | shyaml get-value 2>/dev/null)" || return 1
  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. ;;
  1540. "sequence")
  1541. while read-0 target_service; do
  1542. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1543. printf "%s\0" "$relation_name" "$target_service" "" "$tech_dep"
  1544. done < <(echo "$relation_def" | shyaml get-values-0 2>/dev/null)
  1545. ;;
  1546. "struct")
  1547. while read-0 target_service relation_config; do
  1548. tech_dep="$(get_service_relation_tech_dep "$target_service" "$relation_name")" || return 1
  1549. printf "%s\0" "$relation_name" "$target_service" "$relation_config" "$tech_dep"
  1550. done < <(echo "$relation_def" | shyaml key-values-0 2>/dev/null)
  1551. ;;
  1552. esac
  1553. ) </dev/null >> "$cache_file" || return 1
  1554. done < <(echo "$compose_service_def" | shyaml key-values-0 relations 2>/dev/null)
  1555. fi
  1556. )
  1557. if [ "$?" != 0 ]; then
  1558. err "Error while looking for compose relations."
  1559. rm -f "$cache_file" ## no cache
  1560. return 1
  1561. fi
  1562. [ -e "$cache_file" ] && cat "$cache_file"
  1563. return 0
  1564. }
  1565. export -f _get_compose_relations_cached
  1566. get_compose_relations () {
  1567. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1568. compose_def
  1569. if [ -e "$cache_file" ]; then
  1570. #debug "$FUNCNAME: SESSION cache hit $1"
  1571. cat "$cache_file"
  1572. return 0
  1573. fi
  1574. compose_def="$(get_compose_service_def "$service")" || return 1
  1575. _get_compose_relations_cached "$compose_def" > "$cache_file"
  1576. if [ "$?" != 0 ]; then
  1577. rm -f "$cache_file" ## no cache
  1578. return 1
  1579. fi
  1580. cat "$cache_file"
  1581. }
  1582. export -f get_compose_relations
  1583. get_service_relations () {
  1584. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1585. s rn ts rc td
  1586. if [ -e "$cache_file" ]; then
  1587. #debug "$FUNCNAME: SESSION cache hit $1"
  1588. cat "$cache_file"
  1589. return 0
  1590. fi
  1591. if [ -z "$ALL_RELATIONS" ]; then
  1592. err "Can't access global \$ALL_RELATIONS"
  1593. return 1
  1594. fi
  1595. while read-0 s rn ts rc td; do
  1596. [[ "$s" == "$service" ]] || continue
  1597. printf "%s\0" "$rn" "$ts" "$rc" "$td"
  1598. done < <(cat "$ALL_RELATIONS") > "$cache_file"
  1599. if [ "$?" != 0 ]; then
  1600. rm -f "$cache_file" ## no cache
  1601. return 1
  1602. fi
  1603. cat "$cache_file"
  1604. }
  1605. export -f get_service_relations
  1606. get_service_relation() {
  1607. local service="$1" relation="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1608. rn ts rc td
  1609. if [ -e "$cache_file" ]; then
  1610. #debug "$FUNCNAME: SESSION cache hit $1"
  1611. cat "$cache_file"
  1612. return 0
  1613. fi
  1614. while read-0 rn ts rc td; do
  1615. [ "$relation" == "$rn" ] && {
  1616. printf "%s\0" "$ts" "$rc" "$td"
  1617. break
  1618. }
  1619. done < <(get_service_relations "$service") > "$cache_file"
  1620. if [ "$?" != 0 ]; then
  1621. rm -f "$cache_file" ## no cache
  1622. return 1
  1623. fi
  1624. cat "$cache_file"
  1625. }
  1626. export -f get_service_relation
  1627. _get_charm_metadata_uses() {
  1628. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  1629. if [ -e "$cache_file" ]; then
  1630. #debug "$FUNCNAME: SESSION cache hit $1"
  1631. cat "$cache_file" || return 1
  1632. return 0
  1633. fi
  1634. printf "%s" "$metadata" | { shyaml key-values-0 uses 2>/dev/null || true; } | tee "$cache_file"
  1635. }
  1636. export -f _get_charm_metadata_uses
  1637. _get_service_metadata() {
  1638. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1639. charm
  1640. if [ -e "$cache_file" ]; then
  1641. #debug "$FUNCNAME: SESSION cache hit $1"
  1642. cat "$cache_file"
  1643. return 0
  1644. fi
  1645. charm="$(get_service_charm "$service")" || return 1
  1646. charm.metadata "$charm" > "$cache_file"
  1647. if [ "$?" != 0 ]; then
  1648. rm -f "$cache_file" ## no cache
  1649. return 1
  1650. fi
  1651. cat "$cache_file"
  1652. }
  1653. export -f _get_service_metadata
  1654. _get_service_uses() {
  1655. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  1656. metadata
  1657. if [ -e "$cache_file" ]; then
  1658. #debug "$FUNCNAME: SESSION cache hit $1"
  1659. cat "$cache_file"
  1660. return 0
  1661. fi
  1662. metadata="$(_get_service_metadata "$service")" || return 1
  1663. _get_charm_metadata_uses "$metadata" > "$cache_file"
  1664. if [ "$?" != 0 ]; then
  1665. rm -f "$cache_file" ## no cache
  1666. return 1
  1667. fi
  1668. cat "$cache_file"
  1669. }
  1670. export -f _get_service_uses
  1671. _get_services_uses() {
  1672. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1673. service rn rd
  1674. if [ -e "$cache_file" ]; then
  1675. #debug "$FUNCNAME: SESSION cache hit $1"
  1676. cat "$cache_file"
  1677. return 0
  1678. fi
  1679. for service in "$@"; do
  1680. _get_service_uses "$service" | while read-0 rn rd; do
  1681. printf "%s\0" "$service" "$rn" "$rd"
  1682. done
  1683. [ "${PIPESTATUS[0]}" == 0 ] || {
  1684. return 1
  1685. }
  1686. done > "${cache_file}.wip"
  1687. mv "${cache_file}"{.wip,} &&
  1688. cat "$cache_file" || return 1
  1689. }
  1690. export -f _get_services_uses
  1691. _get_provides_provides() {
  1692. local provides="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1693. service rn rd
  1694. if [ -e "$cache_file" ]; then
  1695. # debug "$FUNCNAME: CACHEDIR cache hit $1"
  1696. cat "$cache_file"
  1697. return 0
  1698. fi
  1699. type=$(printf "%s" "$provides" | shyaml get-type)
  1700. case "$type" in
  1701. sequence)
  1702. while read-0 prov; do
  1703. printf "%s\0" "$prov" ""
  1704. done < <(echo "$provides" | shyaml get-values-0)
  1705. ;;
  1706. struct)
  1707. printf "%s" "$provides" | shyaml key-values-0
  1708. ;;
  1709. str)
  1710. printf "%s\0" "$(echo "$provides" | shyaml get-value)" ""
  1711. ;;
  1712. *)
  1713. err "Unexpected type '$type' for provider identifier in charm '$charm'."
  1714. return 1
  1715. esac | tee "$cache_file"
  1716. return "${PIPESTATUS[0]}"
  1717. }
  1718. _get_metadata_provides() {
  1719. local metadata="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1720. service rn rd
  1721. if [ -e "$cache_file" ]; then
  1722. #debug "$FUNCNAME: CACHEDIR cache hit"
  1723. cat "$cache_file"
  1724. return 0
  1725. fi
  1726. provides=$(printf "%s" "$metadata" | shyaml get-value -y -q provides "")
  1727. [ "$provides" -a "$provides" != "''" ] || { touch "$cache_file"; return 0; }
  1728. _get_provides_provides "$provides" | tee "$cache_file"
  1729. return "${PIPESTATUS[0]}"
  1730. }
  1731. _get_services_provides() {
  1732. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1733. service rn rd
  1734. if [ -e "$cache_file" ]; then
  1735. #debug "$FUNCNAME: SESSION cache hit $1"
  1736. cat "$cache_file"
  1737. return 0
  1738. fi
  1739. ## YYY: replace the inner loop by a cached function
  1740. for service in "$@"; do
  1741. metadata="$(_get_service_metadata "$service")" || return 1
  1742. while read-0 rn rd; do
  1743. printf "%s\0" "$service" "$rn" "$rd"
  1744. done < <(_get_metadata_provides "$metadata")
  1745. done > "$cache_file"
  1746. if [ "$?" != 0 ]; then
  1747. rm -f "$cache_file" ## no cache
  1748. return 1
  1749. fi
  1750. cat "$cache_file"
  1751. }
  1752. export -f _get_services_provides
  1753. _get_charm_provides() {
  1754. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(charm.store_metadata_hash)"
  1755. if [ -e "$cache_file" ]; then
  1756. #debug "$FUNCNAME: SESSION cache hit"
  1757. cat "$cache_file"
  1758. return 0
  1759. fi
  1760. start="$SECONDS"
  1761. debug "Getting charm provider list..."
  1762. while read-0 charm _ realpath metadata; do
  1763. metadata="$(charm.metadata "$charm")" || continue
  1764. # echo "reading $charm" >&2
  1765. while read-0 rn rd; do
  1766. printf "%s\0" "$charm" "$rn" "$rd"
  1767. done < <(_get_metadata_provides "$metadata")
  1768. done < <(charm.ls) | tee "$cache_file"
  1769. errlvl="${PIPESTATUS[0]}"
  1770. debug " ..charm provider list done $GRAY(in $((SECONDS - start))s)$NORMAL"
  1771. return "$errlvl"
  1772. }
  1773. _get_charm_providing() {
  1774. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1775. relation="$1"
  1776. if [ -e "$cache_file" ]; then
  1777. #debug "$FUNCNAME: SESSION cache hit $1"
  1778. cat "$cache_file"
  1779. return 0
  1780. fi
  1781. while read-0 charm relation_name relation_def; do
  1782. [ "$relation_name" == "$relation" ] || continue
  1783. printf "%s\0" "$charm" "$relation_def"
  1784. done < <(_get_charm_provides) > "$cache_file"
  1785. if [ "$?" != 0 ]; then
  1786. rm -f "$cache_file" ## no cache
  1787. return 1
  1788. fi
  1789. cat "$cache_file"
  1790. }
  1791. _get_services_providing() {
  1792. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1793. relation="$1"
  1794. shift ## services is "$@"
  1795. if [ -e "$cache_file" ]; then
  1796. #debug "$FUNCNAME: SESSION cache hit $1"
  1797. cat "$cache_file"
  1798. return 0
  1799. fi
  1800. while read-0 service relation_name relation_def; do
  1801. [ "$relation_name" == "$relation" ] || continue
  1802. printf "%s\0" "$service" "$relation_def"
  1803. done < <(_get_services_provides "$@") > "$cache_file"
  1804. if [ "$?" != 0 ]; then
  1805. rm -f "$cache_file" ## no cache
  1806. return 1
  1807. fi
  1808. cat "$cache_file"
  1809. }
  1810. export -f _get_services_provides
  1811. _out_new_relation_from_defs() {
  1812. local service="$1" rn="$2" ts="$3" prov_def="$4" rel_def="$5" rc td rc_prov
  1813. rc_prov=$(printf "%s" "$prov_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1814. ## YYYvlab: should be seen even in no debug mode no ?
  1815. rc=$(printf "%s" "$rel_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1816. td=$(echo "$prov_def" | shyaml get-value 'tech-dep' 2>/dev/null)
  1817. td=${td:-True}
  1818. rc=$(merge_yaml_str "$rc_prov" "$rc") || return 1
  1819. printf "%s\0" "$service" "$relation_name" "$ts" "$rc" "$td"
  1820. }
  1821. get_all_relations () {
  1822. local cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)" \
  1823. services
  1824. if [ -e "${cache_file}" ]; then
  1825. #debug "$FUNCNAME: SESSION cache hit $1"
  1826. cat "${cache_file}"
  1827. return 0
  1828. fi
  1829. declare -A services
  1830. services_uses=()
  1831. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1832. _get_services_uses "$@" || return 1
  1833. array_read-0 services_uses < <(_get_services_uses "$@")
  1834. services_provides=()
  1835. ## XXXvlab: bwerk, leveraging cache to be able to get the errorlevel here.
  1836. _get_services_provides "$@" || return 1
  1837. array_read-0 services_provides < <(_get_services_provides "$@")
  1838. for service in "$@"; do
  1839. services[$service]=1
  1840. done
  1841. all_services=("$@")
  1842. while [ "${#all_services[@]}" != 0 ]; do
  1843. array_pop all_services service
  1844. while read-0 relation_name ts relation_config tech_dep; do
  1845. printf "%s\0" "$service" "$relation_name" "$ts" "$relation_config" "$tech_dep"
  1846. ## adding target services ?
  1847. [ "${services[$ts]}" ] && continue
  1848. array_read-0 services_uses < <(_get_services_uses "$ts")
  1849. all_services+=("$ts")
  1850. services[$ts]=1
  1851. done < <(get_compose_relations "$service")
  1852. done > "${cache_file}.wip"
  1853. while true; do
  1854. changed=
  1855. new_services_uses=()
  1856. summon=()
  1857. required=()
  1858. recommended=()
  1859. optional=()
  1860. while [ "${#services_uses[@]}" != 0 ]; do
  1861. service="${services_uses[0]}"
  1862. relation_name="${services_uses[1]}"
  1863. relation_def="${services_uses[2]}"
  1864. services_uses=("${services_uses[@]:3}")
  1865. default_options=$(printf "%s" "$relation_def" | shyaml -y get-value "default-options" 2>/dev/null)
  1866. ## is this "use" declaration satisfied ?
  1867. found=
  1868. while read-0 s rn ts rc td; do
  1869. if [ -z "$found" -a "$service" == "$s" -a "$relation_name" == "$rn" ]; then
  1870. if [ "$default_options" ]; then
  1871. rc=$(merge_yaml_str "$default_options" "$rc") || return 1
  1872. fi
  1873. found="$ts"
  1874. fi
  1875. printf "%s\0" "$s" "$rn" "$ts" "$rc" "$td"
  1876. done < "${cache_file}.wip" > "${cache_file}.wip.new"
  1877. mv "${cache_file}.wip.new" "${cache_file}.wip"
  1878. if [ "$found" ]; then ## this "use" declaration was satisfied
  1879. debug "${DARKYELLOW}$service${NORMAL} use declaration for relation " \
  1880. "${DARKBLUE}$relation_name${NORMAL} is satisfied with ${DARKYELLOW}$found${NORMAL}"
  1881. continue
  1882. fi
  1883. auto=$(echo "$relation_def" | shyaml get-value auto pair 2>/dev/null)
  1884. case "$auto" in
  1885. "pair")
  1886. service_list=()
  1887. array_read-0 service_list < <(array_keys_to_stdin services)
  1888. providers=()
  1889. array_read-0 providers providers_def < <(_get_services_providing "$relation_name" "${service_list[@]}")
  1890. if [ "${#providers[@]}" == 1 ]; then
  1891. ts="${providers[0]}"
  1892. debug "Auto-pairs ${DARKYELLOW}$service${NORMAL}" \
  1893. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  1894. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  1895. "${providers_def[0]}" "$relation_def" \
  1896. >> "${cache_file}.wip"
  1897. ## Adding service
  1898. [ "${services[$ts]}" ] && continue
  1899. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  1900. services[$ts]=1
  1901. changed=1
  1902. continue
  1903. elif [ "${#providers[@]}" -gt 1 ]; then
  1904. msg=""
  1905. warn "No auto-pairing ${DARKYELLOW}$service${NORMAL}" \
  1906. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  1907. "(> 1 provider)."
  1908. continue
  1909. else
  1910. : ## Do nothing
  1911. fi
  1912. ;;
  1913. "summon")
  1914. summon+=("$service" "$relation_name" "$relation_def")
  1915. ;;
  1916. ""|null|disable|disabled)
  1917. :
  1918. ;;
  1919. *)
  1920. err "Invalid ${WHITE}auto${NORMAL} value '$auto'."
  1921. return 1
  1922. ;;
  1923. esac
  1924. constraint=$(echo "$relation_def" | shyaml get-value constraint auto-pair 2>/dev/null)
  1925. case "$constraint" in
  1926. "required")
  1927. required+=("$service" "$relation_name" "$relation_def")
  1928. ;;
  1929. "recommended")
  1930. recommended+=("$service" "$relation_name" "$relation_def")
  1931. ;;
  1932. "optional")
  1933. optional+=("$service" "$relation_name" "$relation_def")
  1934. ;;
  1935. *)
  1936. err "Invalid ${WHITE}constraint${NORMAL} value '$contraint'."
  1937. return 1
  1938. ;;
  1939. esac
  1940. new_services_uses+=("$service" "$relation_name" "$relation_def") ## re-queue it
  1941. done
  1942. services_uses=("${new_services_uses[@]}")
  1943. if [ "$changed" ]; then
  1944. continue
  1945. fi
  1946. ## situation is stable
  1947. if [ "${#summon[@]}" != 0 ]; then
  1948. while [ "${#summon[@]}" != 0 ]; do
  1949. service="${summon[0]}"
  1950. relation_name="${summon[1]}"
  1951. relation_def="${summon[2]}"
  1952. summon=("${summon[@]:3}")
  1953. providers=()
  1954. providers_def=()
  1955. array_read-0 providers providers_def < <(_get_charm_providing "$relation_name" "${service_list[@]}")
  1956. if [ "${#providers[@]}" == 0 ]; then
  1957. die "Summoning a ${DARKBLUE}$relation_name${NORMAL} provider failed: none were found in charm store."
  1958. fi
  1959. if [ "${#providers[@]}" -gt 1 ]; then
  1960. warn "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  1961. "--${DARKBLUE}$relation_name${NORMAL}--> ($DARKYELLOW""${providers[@]}""$NORMAL)"\
  1962. "(> 1 provider). Choosing first."
  1963. fi
  1964. ts="${providers[0]}"
  1965. ## YYYvlab: should be seen even in no debug mode no ?
  1966. debug "Auto-summon ${DARKYELLOW}$service${NORMAL}" \
  1967. "--${DARKBLUE}$relation_name${NORMAL}--> ${DARKYELLOW}$ts${NORMAL}"
  1968. _out_new_relation_from_defs "$service" "$relation_name" "$ts" \
  1969. "${providers_def[0]}" "$relation_def" \
  1970. >> "${cache_file}.wip"
  1971. ## Adding service
  1972. [ "${services[$ts]}" ] && continue
  1973. array_read-0 new_services_uses < <(_get_services_uses "$ts")
  1974. services[$ts]=1
  1975. changed=1
  1976. done
  1977. continue
  1978. fi
  1979. [ "$NO_CONSTRAINT_CHECK" ] && break
  1980. if [ "${#required[@]}" != 0 ]; then
  1981. echo "$(_display_solves required)" | sed -r "s/^/${RED}||${NORMAL} /g" >&2
  1982. err "Required relations not satisfied"
  1983. return 1
  1984. fi
  1985. if [ "${#recommended[@]}" != 0 ]; then
  1986. ## make recommendation
  1987. echo "$(_display_solves recommended)" | sed -r "s/^/${YELLOW}||${NORMAL} /g" >&2
  1988. fi
  1989. if [ "${#optional[@]}" != 0 ]; then
  1990. ## inform about options
  1991. echo "$(_display_solves optional)" | sed -r "s/^/${BLUE}||${NORMAL} /g" >&2
  1992. fi
  1993. # if [ "${#required[@]}" != 0 ]; then
  1994. # err "Required relations not satisfied"
  1995. # return 1
  1996. # fi
  1997. if [ "${#recommended[@]}" != 0 ]; then
  1998. warn "Recommended relations not satisfied"
  1999. fi
  2000. break
  2001. done
  2002. if [ "$?" != 0 ]; then
  2003. rm -f "${cache_file}"{,.wip,.wip.new} ## no cache
  2004. return 1
  2005. fi
  2006. export ALL_RELATIONS="$cache_file"
  2007. mv "${cache_file}"{.wip,}
  2008. cat "$cache_file"
  2009. }
  2010. export -f get_all_relations
  2011. _display_solves() {
  2012. local array_name="$1" by_relation msg
  2013. ## inform about options
  2014. msg=""
  2015. declare -A by_relation
  2016. while read-0 service relation_name relation_def; do
  2017. solves=$(printf "%s" "$relation_def" | shyaml -y get-value solves 2>/dev/null);
  2018. auto=$(printf "%s" "$relation_def" | shyaml get-value auto 2>/dev/null);
  2019. if [ -z "$solves" ]; then
  2020. continue
  2021. fi
  2022. by_relation[$relation_name]+=$(printf "\n %s" "${DARKYELLOW}$service$NORMAL for:")
  2023. if [ "$auto" == "pair" ]; then
  2024. requirement="add provider in cluster to auto-pair"
  2025. else
  2026. requirement="add explicit relation"
  2027. fi
  2028. while read-0 name def; do
  2029. by_relation[$relation_name]+=$(printf "\n - ${DARKCYAN}%-15s${NORMAL} %s (%s)" "$name" "$def" "$requirement")
  2030. done < <(printf "%s" "$solves" | shyaml key-values-0)
  2031. done < <(array_values_to_stdin "$array_name")
  2032. while read-0 relation_name message; do
  2033. msg+="$(printf "\n${DARKBLUE}%s$NORMAL provider is $array_name by%s" \
  2034. "$relation_name" "$message" )"
  2035. done < <(array_kv_to_stdin by_relation)
  2036. if [ "$msg" ]; then
  2037. printf "%s\n" "${msg:1}"
  2038. fi
  2039. }
  2040. get_compose_relation_def() {
  2041. local service="$1" relation="$2" relation_name target_service relation_config tech_dep
  2042. while read-0 relation_name target_service relation_config tech_dep; do
  2043. [ "$relation_name" == "$relation" ] || continue
  2044. printf "%s\0%s\0%s\0" "$target_service" "$relation_config" "$tech_dep"
  2045. done < <(get_compose_relations "$service") || return 1
  2046. }
  2047. export -f get_compose_relation_def
  2048. run_service_relations () {
  2049. local service services loaded subservices subservice
  2050. PROJECT_NAME=$(get_default_project_name) || return 1
  2051. export PROJECT_NAME
  2052. declare -A loaded
  2053. subservices=$(get_ordered_service_dependencies "$@") || return 1
  2054. for service in $subservices; do
  2055. # debug "Upping dep's relations of ${DARKYELLOW}$service${NORMAL}:"
  2056. for subservice in $(get_service_deps "$service") "$service"; do
  2057. [ "${loaded[$subservice]}" ] && continue
  2058. export BASE_SERVICE_NAME=$service
  2059. MASTER_BASE_SERVICE_NAME=$(get_top_master_service_for_service "$subservice") || return 1
  2060. MASTER_BASE_CHARM_NAME=$(get_service_charm "$MASTER_BASE_SERVICE_NAME") || return 1
  2061. RELATION_BASE_COMPOSE_DEF=$(get_compose_service_def "$subservice") || return 1
  2062. export RELATION_BASE_COMPOSE_DEF MASTER_BASE_{CHARM,SERVICE}_NAME
  2063. # debug " Relations of ${DARKYELLOW}$subservice${NORMAL}:"
  2064. while read-0 relation_name target_service relation_config tech_dep; do
  2065. export relation_config
  2066. export TARGET_SERVICE_NAME=$target_service
  2067. MASTER_TARGET_SERVICE_NAME=$(get_top_master_service_for_service "$target_service") || return 1
  2068. MASTER_TARGET_CHARM_NAME=$(get_service_charm "$MASTER_TARGET_SERVICE_NAME") || return 1
  2069. RELATION_TARGET_COMPOSE_DEF=$(get_compose_service_def "$target_service") || return 1
  2070. export RELATION_TARGET_COMPOSE_DEF MASTER_TARGET_{CHARM,SERVICE}_NAME
  2071. Wrap -d "Building $DARKYELLOW$subservice$NORMAL --$DARKBLUE$relation_name$NORMAL--> $DARKYELLOW$target_service$NORMAL" <<EOF || return 1
  2072. _run_service_relation "$relation_name" "$subservice" "$target_service" "\$relation_config"
  2073. EOF
  2074. done < <(get_service_relations "$subservice") || return 1
  2075. loaded[$subservice]=1
  2076. done
  2077. done
  2078. }
  2079. export -f run_service_relations
  2080. _run_service_action_direct() {
  2081. local service="$1" action="$2" charm _dummy
  2082. shift; shift
  2083. read-0 charm || true ## against 'set -e' that could be setup in parent scripts
  2084. if read-0 _dummy || [ "$_dummy" ]; then
  2085. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2086. return 1
  2087. fi
  2088. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2089. export state_tmpdir
  2090. {
  2091. (
  2092. set +e ## Prevents unwanted leaks from parent shell
  2093. export COMPOSE_CONFIG=$(get_compose_yml_content)
  2094. export METADATA_CONFIG=$(charm.metadata "$charm")
  2095. export SERVICE_NAME=$service
  2096. export ACTION_NAME=$action
  2097. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2098. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2099. export SERVICE_DATASTORE="$DATASTORE/$service"
  2100. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2101. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2102. stdbuf -oL -eL bash -c 'charm.run_direct_action "$@"' -- "$charm" "$action" "$@"
  2103. echo "$?" > "$action_errlvl_file"
  2104. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2105. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2106. if ! [ -e "$action_errlvl_file" ]; then
  2107. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2108. "to output an errlvl"
  2109. return 1
  2110. fi
  2111. return "$(cat "$action_errlvl_file")"
  2112. }
  2113. export -f _run_service_action_direct
  2114. _run_service_action_relation() {
  2115. local service="$1" action="$2" charm target_charm relation_name relation_config _dummy
  2116. shift; shift
  2117. read-0 charm target_service target_charm relation_name relation_config || true
  2118. if read-0 _dummy || [ "$_dummy" ]; then
  2119. print_syntax_error "$FUNCNAME: too many arguments in action descriptor"
  2120. return 1
  2121. fi
  2122. export RELATION_DATA_FILE=$(get_relation_data_file "$service" "$target_service" "$relation_name" "$relation_config")
  2123. export action_errlvl_file="$state_tmpdir/action-$service-$charm-$action-errlvl"
  2124. export state_tmpdir
  2125. {
  2126. (
  2127. set +e ## Prevents unwanted leaks from parent shell
  2128. export METADATA_CONFIG=$(charm.metadata "$charm")
  2129. export SERVICE_NAME=$service
  2130. export RELATION_TARGET_SERVICE="$target_service"
  2131. export RELATION_TARGET_CHARM="$target_charm"
  2132. export RELATION_BASE_SERVICE="$service"
  2133. export RELATION_BASE_CHARM="$charm"
  2134. export ACTION_NAME=$action
  2135. export CONTAINER_NAME=$(get_top_master_service_for_service "$service")
  2136. export DOCKER_BASE_IMAGE=$(service_base_docker_image "$CONTAINER_NAME")
  2137. export SERVICE_DATASTORE="$DATASTORE/$service"
  2138. export SERVICE_CONFIGSTORE="$CONFIGSTORE/$service"
  2139. exname="$exname $ACTION_NAME $SERVICE_NAME" \
  2140. stdbuf -oL -eL bash -c 'charm.run_relation_action "$@"' -- "$target_charm" "$relation_name" "$action" "$@"
  2141. echo "$?" > "$action_errlvl_file"
  2142. ) | logstdout "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${GREEN}@${NORMAL}"
  2143. } 3>&1 1>&2 2>&3 | logstderr "$DARKYELLOW$service$NORMAL/${DARKCYAN}$action${NORMAL} ${RED}@$NORMAL" 3>&1 1>&2 2>&3
  2144. if ! [ -e "$action_errlvl_file" ]; then
  2145. err "Action $DARKYELLOW$service$NORMAL:$DARKCYAN$action$NORMAL has failed without having time" \
  2146. "to output an errlvl"
  2147. return 1
  2148. fi
  2149. return "$(cat "$action_errlvl_file")"
  2150. }
  2151. export -f _run_service_action_relation
  2152. get_relation_data_dir() {
  2153. local service="$1" target_service="$2" relation_name="$3" \
  2154. cache_file="$state_tmpdir/$FUNCNAME.cache.$(printf "%s\0" "$@" | md5_compat)"
  2155. if [ -e "$cache_file" ]; then
  2156. # debug "$FUNCNAME: cache hit ($*)"
  2157. cat "$cache_file"
  2158. return 0
  2159. fi
  2160. project=$(get_default_project_name) || return 1
  2161. relation_dir="$VARDIR/relations/$project/${service}-${target_service}/$relation_name"
  2162. if ! [ -d "$relation_dir" ]; then
  2163. mkdir -p "$relation_dir" || return 1
  2164. chmod go-rwx "$relation_dir" || return 1 ## protecting this directory
  2165. fi
  2166. echo "$relation_dir" | tee "$cache_file"
  2167. }
  2168. export -f get_relation_data_dir
  2169. get_relation_data_file() {
  2170. local service="$1" target_service="$2" relation_name="$3" relation_config="$4"
  2171. relation_dir=$(get_relation_data_dir "$service" "$target_service" "$relation_name") || return 1
  2172. relation_data_file="$relation_dir/data"
  2173. new=
  2174. if [ -e "$relation_data_file" ]; then
  2175. ## Has reference changed ?
  2176. new_md5=$(echo "$relation_config" | md5_compat)
  2177. if [ "$new_md5" != "$(cat "$relation_data_file.md5_ref" 2>/dev/null)" ]; then
  2178. new=true
  2179. fi
  2180. else
  2181. new=true
  2182. fi
  2183. if [ "$new" ]; then
  2184. echo "$relation_config" > "$relation_data_file"
  2185. chmod go-rwx "$relation_data_file" ## protecting this file
  2186. echo "$relation_config" | md5_compat > "$relation_data_file.md5_ref"
  2187. fi
  2188. echo "$relation_data_file"
  2189. }
  2190. export -f get_relation_data_file
  2191. has_service_action () {
  2192. local service="$1" action="$2" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2193. charm target_charm relation_name target_service relation_config _tech_dep
  2194. if [ -e "$cache_file" ]; then
  2195. # debug "$FUNCNAME: cache hit ($*)"
  2196. cat "$cache_file"
  2197. return 0
  2198. fi
  2199. charm=$(get_service_charm "$service") || return 1
  2200. ## Action directly provided ?
  2201. if charm.has_direct_action "$charm" "$action" >/dev/null; then
  2202. echo -en "direct\0$charm" | tee "$cache_file"
  2203. return 0
  2204. fi
  2205. ## Action provided by relation ?
  2206. while read-0 relation_name target_service relation_config _tech_dep; do
  2207. target_charm=$(get_service_charm "$target_service") || return 1
  2208. if charm.has_relation_action "$target_charm" "$relation_name" "$action" >/dev/null; then
  2209. echo -en "relation\0$charm\0$target_service\0$target_charm\0$relation_name\0$relation_config" | tee "$cache_file"
  2210. return 0
  2211. fi
  2212. done < <(get_service_relations "$service")
  2213. return 1
  2214. # master=$(get_top_master_service_for_service "$service")
  2215. # [ "$master" == "$charm" ] && return 1
  2216. # has_service_action "$master" "$action"
  2217. }
  2218. export -f has_service_action
  2219. run_service_action () {
  2220. local service="$1" action="$2"
  2221. shift ; shift
  2222. {
  2223. if ! read-0 action_type; then
  2224. info "Service $DARKYELLOW$service$NORMAL does not have any action $DARKCYAN$action$NORMAL defined."
  2225. info " Add an executable script to 'actions/$action' to implement action."
  2226. return 1
  2227. fi
  2228. Section "running $DARKYELLOW$service$NORMAL/$DARKCYAN$action$NORMAL ($action_type)"; Feed
  2229. "_run_service_action_${action_type}" "$service" "$action" "$@"
  2230. } < <(has_service_action "$service" "$action")
  2231. }
  2232. export -f run_service_action
  2233. get_compose_relation_config() {
  2234. local service=$1 relation_config cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2235. if [ -e "$cache_file" ]; then
  2236. # debug "$FUNCNAME: cache hit ($*)"
  2237. cat "$cache_file"
  2238. return 0
  2239. fi
  2240. compose_service_def=$(get_compose_service_def "$service") || return 1
  2241. echo "$compose_service_def" | shyaml get-value "relations" 2>/dev/null | tee "$cache_file"
  2242. }
  2243. export -f get_compose_relation_config
  2244. # ## Return key-values-0
  2245. # get_compose_relation_config_for_service() {
  2246. # local service=$1 relation_name=$2 relation_config
  2247. # compose_service_relations=$(get_compose_relation_config "$service") || return 1
  2248. # if ! relation_config=$(
  2249. # echo "$compose_service_relations" |
  2250. # shyaml get-value "${relation_name}" 2>/dev/null); then
  2251. # err "Couldn't find $DARKYELLOW${service}$NORMAL/${WHITE}${relation_name}$NORMAL" \
  2252. # "relation config in compose configuration."
  2253. # return 1
  2254. # fi
  2255. # if [ -z "$relation_config" ]; then
  2256. # err "Relation ${WHITE}mysql-database$NORMAL is empty in compose configuration."
  2257. # return 1
  2258. # fi
  2259. # if ! echo "$relation_config" | shyaml key-values-0 2>/dev/null; then
  2260. # err "No key/values in ${DARKBLUE}mysql-database$NORMAL of compose config."
  2261. # return 1
  2262. # fi
  2263. # }
  2264. # export -f get_compose_relation_config_for_service
  2265. _get_container_relation() {
  2266. local metadata=$1 found relation_name relation_def
  2267. found=
  2268. while read-0 relation_name relation_def; do
  2269. [ "$(echo "$relation_def" | shyaml get-value "scope" 2>/dev/null)" == "container" ] && {
  2270. found="$relation_name"
  2271. break
  2272. }
  2273. done < <(_get_charm_metadata_uses "$metadata")
  2274. if [ -z "$found" ]; then
  2275. die "Charm $DARKPINK$charm$NORMAL is a subordinate but does not have any required relation declaration with" \
  2276. "${WHITE}scope${NORMAL} set to 'container'."
  2277. fi
  2278. printf "%s" "$found"
  2279. }
  2280. _get_master_service_for_service_cached () {
  2281. local service="$1" charm="$2" metadata="$3" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2282. charm requires master_charm target_charm target_service service_def found
  2283. if [ -e "$cache_file" ]; then
  2284. # debug "$FUNCNAME: STATIC cache hit ($1)"
  2285. cat "$cache_file" &&
  2286. touch "$cache_file" || return 1
  2287. return 0
  2288. fi
  2289. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" != "True" ]; then
  2290. ## just return service name
  2291. echo "$service" | tee "$cache_file"
  2292. return 0
  2293. fi
  2294. ## Action provided by relation ?
  2295. container_relation=$(_get_container_relation "$metadata")
  2296. read-0 target_service _ _ < <(get_service_relation "$service" "$container_relation")
  2297. if [ -z "$target_service" ]; then
  2298. err "Couldn't find ${WHITE}relations.${container_relation}${NORMAL} in" \
  2299. "${DARKYELLOW}$service$NORMAL compose definition."
  2300. err ${FUNCNAME[@]}
  2301. return 1
  2302. fi
  2303. echo "$target_service" | tee "$cache_file"
  2304. }
  2305. export -f _get_master_service_for_service_cached
  2306. get_master_service_for_service() {
  2307. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2308. charm metadata result
  2309. if [ -e "$cache_file" ]; then
  2310. # debug "$FUNCNAME: SESSION cache hit ($*)"
  2311. cat "$cache_file" || return 1
  2312. return 0
  2313. fi
  2314. charm=$(get_service_charm "$service") || return 1
  2315. metadata=$(charm.metadata "$charm" 2>/dev/null) || {
  2316. metadata=""
  2317. warn "No charm $DARKPINK$charm$NORMAL found."
  2318. }
  2319. result=$(_get_master_service_for_service_cached "$service" "$charm" "$metadata") || return 1
  2320. echo "$result" | tee "$cache_file" || return 1
  2321. }
  2322. export -f get_master_service_for_service
  2323. get_top_master_service_for_service() {
  2324. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1" \
  2325. current_service
  2326. if [ -e "$cache_file" ]; then
  2327. # debug "$FUNCNAME: cache hit ($*)"
  2328. cat "$cache_file"
  2329. return 0
  2330. fi
  2331. current_service="$service"
  2332. while true; do
  2333. master_service=$(get_master_service_for_service "$current_service") || return 1
  2334. [ "$master_service" == "$current_service" ] && break
  2335. current_service="$master_service"
  2336. done
  2337. echo "$current_service" | tee "$cache_file"
  2338. return 0
  2339. }
  2340. export -f get_top_master_service_for_service
  2341. ##
  2342. ## The result is a mixin that is not always a complete valid
  2343. ## docker-compose entry (thinking of subordinates). The result
  2344. ## will be merge with master charms.
  2345. _get_docker_compose_mixin_from_metadata_cached() {
  2346. local service="$1" charm="$2" metadata="$3" has_build_dir="$4" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  2347. metadata_file metadata volumes docker_compose subordinate image
  2348. if [ -e "$cache_file" ]; then
  2349. #debug "$FUNCNAME: STATIC cache hit $1"
  2350. cat "$cache_file" &&
  2351. touch "$cache_file" || return 1
  2352. return 0
  2353. fi
  2354. mixin=$(echo -en "labels:\n- compose.charm=$charm")
  2355. if [ "$metadata" ]; then
  2356. ## resources to volumes
  2357. volumes=$(
  2358. for resource_type in data config; do
  2359. while read-0 resource; do
  2360. eval "echo \" - \$${resource_type^^}STORE/\$service\$resource:\$resource:rw\""
  2361. done < <(echo "$metadata" | shyaml get-values-0 "${resource_type}-resources" 2>/dev/null)
  2362. done
  2363. while read-0 resource; do
  2364. if [[ "$resource" == /*:/*:* ]]; then
  2365. echo " - $resource"
  2366. elif [[ "$resource" == /*:/* ]]; then
  2367. echo " - $resource:rw"
  2368. elif [[ "$resource" == /*:* ]]; then
  2369. echo " - ${resource%%:*}:$resource"
  2370. elif [[ "$resource" =~ ^/[^:]+$ ]]; then
  2371. echo " - $resource:$resource:rw"
  2372. else
  2373. die "Invalid host-resource specified in 'metadata.yml'."
  2374. fi
  2375. done < <(echo "$metadata" | shyaml get-values-0 "host-resources" 2>/dev/null)
  2376. while read-0 resource; do
  2377. dest="$(charm.get_dir "$charm")/resources$resource"
  2378. if ! [ -e "$dest" ]; then
  2379. die "charm-resource: '$resource' does not exist (file: '$dest')."
  2380. fi
  2381. echo " - $dest:$resource:ro"
  2382. done < <(echo "$metadata" | shyaml get-values-0 "charm-resources" 2>/dev/null)
  2383. ) || return 1
  2384. if [ "$volumes" ]; then
  2385. mixin=$(merge_yaml_str "$mixin" "$(echo -en "volumes:\n$volumes")") || {
  2386. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  2387. "from charm ${DARKPINK}$charm$NORMAL."
  2388. return 1
  2389. }
  2390. fi
  2391. docker_compose=$(echo "$metadata" | shyaml get-value -y "docker-compose" 2>/dev/null)
  2392. if [ "$docker_compose" ]; then
  2393. mixin=$(merge_yaml_str "$mixin" "$docker_compose") || {
  2394. err "Failed to merge mixin with ${WHITE}docker-compose${NORMAL} option" \
  2395. "from charm ${DARKPINK}$charm$NORMAL."
  2396. return 1
  2397. }
  2398. fi
  2399. if [ "$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)" == "True" ]; then
  2400. subordinate=true
  2401. fi
  2402. fi
  2403. image=$(echo "$metadata" | shyaml get-value "docker-image" 2>/dev/null)
  2404. [ "$image" == "None" ] && image=""
  2405. image_or_build_statement=
  2406. if [ "$image" ]; then
  2407. if [ "$subordinate" ]; then
  2408. err "Subordinate charm can not have a ${WHITE}docker-image${NORMAL} value."
  2409. return 1
  2410. fi
  2411. image_or_build_statement="image: $image"
  2412. elif [ "$has_build_dir" ]; then
  2413. if [ "$subordinate" ]; then
  2414. err "Subordinate charm can not have a 'build' sub directory."
  2415. return 1
  2416. fi
  2417. image_or_build_statement="build: $(charm.get_dir "$charm")/build"
  2418. fi
  2419. if [ "$image_or_build_statement" ]; then
  2420. mixin=$(merge_yaml_str "$mixin" "$image_or_build_statement") || {
  2421. err "Failed to merge yaml with image or build YAML statement."
  2422. return 1
  2423. }
  2424. fi
  2425. echo "$mixin" | tee "$cache_file"
  2426. }
  2427. export -f _get_docker_compose_mixin_from_metadata_cached
  2428. get_docker_compose_mixin_from_metadata() {
  2429. local service="$1" cache_file="$state_tmpdir/$FUNCNAME.cache.$1"
  2430. if [ -e "$cache_file" ]; then
  2431. #debug "$FUNCNAME: SESSION cache hit ($*)"
  2432. cat "$cache_file"
  2433. return 0
  2434. fi
  2435. charm=$(get_service_charm "$service") || return 1
  2436. metadata="$(charm.metadata "$charm" 2>/dev/null)" || return 1
  2437. has_build_dir=
  2438. [ -d "$(charm.get_dir "$charm")/build" ] && has_build_dir=true
  2439. mixin=$(_get_docker_compose_mixin_from_metadata_cached "$service" "$charm" "$metadata" "$has_build_dir") || return 1
  2440. echo "$mixin" | tee "$cache_file"
  2441. }
  2442. export -f get_docker_compose_mixin_from_metadata
  2443. _save() {
  2444. local name="$1"
  2445. cat - | tee -a "$docker_compose_dir/.data/$name"
  2446. }
  2447. export -f _save
  2448. get_default_project_name() {
  2449. if [ "$DEFAULT_PROJECT_NAME" ]; then
  2450. echo "$DEFAULT_PROJECT_NAME"
  2451. return 0
  2452. fi
  2453. compose_yml_location="$(get_compose_yml_location)" || return 1
  2454. if [ "$compose_yml_location" ]; then
  2455. if normalized_path=$(readlink -f "$compose_yml_location"); then
  2456. name="$(basename "$(dirname "$normalized_path")")"
  2457. echo "${name%%-deploy}"
  2458. return 0
  2459. fi
  2460. fi
  2461. echo "orphan"
  2462. return 0
  2463. }
  2464. export -f get_default_project_name
  2465. get_running_compose_containers() {
  2466. ## XXXvlab: docker bug: there will be a final newline anyway
  2467. docker ps --filter label="compose.service" --format='{{.ID}}'
  2468. }
  2469. export -f get_running_compose_containers
  2470. get_volumes_for_container() {
  2471. local container="$1"
  2472. docker inspect \
  2473. --format '{{range $mount := .Mounts}}{{$mount.Source}}{{"\x00"}}{{$mount.Destination}}{{"\x00"}}{{end}}' \
  2474. "$container"
  2475. }
  2476. export -f get_volumes_for_container
  2477. is_volume_used() {
  2478. local volume="$1" container_id src dst
  2479. while read container_id; do
  2480. while read-0 src dst; do
  2481. [[ "$src" == "$volume"/* ]] && return 0
  2482. done < <(get_volumes_for_container "$container_id")
  2483. done < <(get_running_compose_containers)
  2484. return 1
  2485. }
  2486. export -f is_volume_used
  2487. clean_unused_docker_compose() {
  2488. for f in /var/lib/compose/docker-compose/*; do
  2489. [ -e "$f" ] || continue
  2490. is_volume_used "$f" && continue
  2491. debug "Cleaning unused docker-compose ${f##*/}"
  2492. rm -rf "$f" || return 1
  2493. done
  2494. }
  2495. export -f clean_unused_docker_compose
  2496. stdin_get_hash() {
  2497. local sha
  2498. sha=$(sha256sum) || return 1
  2499. sha=${sha:0:64}
  2500. echo "$sha"
  2501. }
  2502. export -f stdin_get_hash
  2503. file_get_hash() {
  2504. stdin_get_hash < "$1" || return 1
  2505. }
  2506. export -f file_get_hash
  2507. docker_compose_store() {
  2508. local file="$1" sha
  2509. sha=$(file_get_hash "$file") || return 1
  2510. project=$(get_default_project_name) || return 1
  2511. dst="/var/lib/compose/docker-compose/$sha/$project"
  2512. mkdir -p "$dst" || return 1
  2513. cat <<EOF > "$dst/.env" || return 1
  2514. DOCKER_COMPOSE_PATH=$dst
  2515. EOF
  2516. cp "$file" "$dst/docker-compose.yml" || return 1
  2517. mkdir -p "$dst/bin" || return 1
  2518. cat <<EOF > "$dst/bin/dc" || return 1
  2519. #!/bin/bash
  2520. $(declare -f read-0)
  2521. docker_run_opts=()
  2522. while read-0 opt; do
  2523. docker_run_opts+=("\$opt")
  2524. done < <(cat "$COMPOSE_LAUNCHER_OPTS")
  2525. docker_run_opts+=(
  2526. "-w" "$dst"
  2527. "--entrypoint" "/usr/local/bin/docker-compose"
  2528. )
  2529. [ -t 1 ] && {
  2530. docker_run_opts+=("-ti")
  2531. }
  2532. exec docker run --rm "\${docker_run_opts[@]}" "${COMPOSE_DOCKER_IMAGE:-docker.0k.io/compose}" "\$@"
  2533. EOF
  2534. chmod +x "$dst/bin/dc" || return 1
  2535. printf "%s" "$sha"
  2536. }
  2537. launch_docker_compose() {
  2538. local charm docker_compose_tmpdir docker_compose_dir
  2539. docker_compose_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2540. #debug "Creating temporary docker-compose directory in '$docker_compose_tmpdir'."
  2541. trap_add EXIT "rm -rf \"$docker_compose_tmpdir\""
  2542. ## docker-compose will name network from the parent dir name
  2543. project=$(get_default_project_name)
  2544. mkdir -p "$docker_compose_tmpdir/$project"
  2545. docker_compose_dir="$docker_compose_tmpdir/$project"
  2546. get_docker_compose $SERVICE_PACK > "$docker_compose_dir/docker-compose.yml" || return 1
  2547. if [ -e "$state_tmpdir/to-merge-in-docker-compose.yml" ]; then
  2548. # debug "Merging some config data in docker-compose.yml:"
  2549. # debug "$(cat $state_tmpdir/to-merge-in-docker-compose.yml)"
  2550. _config_merge "$docker_compose_dir/docker-compose.yml" "$state_tmpdir/to-merge-in-docker-compose.yml" || return 1
  2551. fi
  2552. if [ -z "$(echo $(cat "$docker_compose_dir/docker-compose.yml"))" ]; then
  2553. die "Generated 'docker-compose.yml' is unexpectedly empty."
  2554. fi
  2555. ## XXXvlab: could be more specific and only link the needed charms
  2556. ## XXXvlab: why do we need these links ? If this is for the build command, then it is not useful anymore.
  2557. # for charm in $(shyaml keys services < "$docker_compose_dir/docker-compose.yml"); do
  2558. # if charm.exists "$charm"; then
  2559. # ln -sf "$(charm.get_dir "$charm")" "$docker_compose_dir/$charm" || exit 1
  2560. # fi
  2561. # done
  2562. mkdir "$docker_compose_dir/.data"
  2563. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2564. sha=$(docker_compose_store "$docker_compose_dir/docker-compose.yml") || return 1
  2565. fi
  2566. {
  2567. {
  2568. if [ -z "$COMPOSE_DISABLE_DOCKER_COMPOSE_STORE" ]; then
  2569. cd "/var/lib/compose/docker-compose/$sha/$project"
  2570. else
  2571. cd "$docker_compose_dir"
  2572. fi
  2573. if [ -f ".env" ]; then
  2574. debug "${WHITE}.env$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2575. debug "$(cat ".env" | prefix " $GRAY|$NORMAL ")"
  2576. fi
  2577. debug "${WHITE}docker-compose.yml$NORMAL for $DARKYELLOW$SERVICE_PACK$NORMAL:"
  2578. debug "$(cat "docker-compose.yml" | prefix " $GRAY|$NORMAL ")"
  2579. debug "${WHITE}Launching$NORMAL: docker-compose $@"
  2580. if [ "$DRY_COMPOSE_RUN" ]; then
  2581. echo docker-compose "$@"
  2582. else
  2583. docker-compose "$@"
  2584. fi
  2585. echo "$?" > "$docker_compose_dir/.data/errlvl"
  2586. } | _save stdout
  2587. } 3>&1 1>&2 2>&3 | _save stderr 3>&1 1>&2 2>&3
  2588. 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
  2589. err "Detected bug https://github.com/docker/docker/issues/4036 ... "
  2590. err "Please re-launch your command, or switch from 'devicemapper' driver to 'overlayfs' or 'aufs'."
  2591. fi
  2592. docker_compose_errlvl="$(cat "$docker_compose_dir/.data/errlvl" 2>/dev/null)"
  2593. if [ -z "$docker_compose_errlvl" ]; then
  2594. err "Something went wrong before you could gather docker-compose errorlevel."
  2595. return 1
  2596. fi
  2597. return "$docker_compose_errlvl"
  2598. }
  2599. export -f launch_docker_compose
  2600. get_compose_yml_location() {
  2601. if ! [ -z ${COMPOSE_YML_FILE+x} ]; then ## if set, even if empty
  2602. echo "$COMPOSE_YML_FILE"
  2603. return 0
  2604. fi
  2605. parent=$(while ! [ -f "./compose.yml" ]; do
  2606. [ "$PWD" == "/" ] && exit 0
  2607. cd ..
  2608. done; echo "$PWD"
  2609. )
  2610. if [ "$parent" ]; then
  2611. echo "$parent/compose.yml"
  2612. return 0
  2613. fi
  2614. ## XXXvlab: do we need this additional environment variable,
  2615. ## COMPOSE_YML_FILE is not sufficient ?
  2616. if [ "$DEFAULT_COMPOSE_FILE" ]; then
  2617. if ! [ -e "$DEFAULT_COMPOSE_FILE" ]; then
  2618. warn "No 'compose.yml' was found in current or parent dirs," \
  2619. "and \$DEFAULT_COMPOSE_FILE points to an unexistent file." \
  2620. "(${DEFAULT_COMPOSE_FILE})"
  2621. return 0
  2622. fi
  2623. echo "$DEFAULT_COMPOSE_FILE"
  2624. return 0
  2625. fi
  2626. warn "No 'compose.yml' was found in current or parent dirs, and no \$DEFAULT_COMPOSE_FILE was set."
  2627. return 0
  2628. }
  2629. export -f get_compose_yml_location
  2630. get_compose_yml_content() {
  2631. local cache_file="$state_tmpdir/$FUNCNAME.cache"
  2632. if [ -e "$cache_file" ]; then
  2633. cat "$cache_file" &&
  2634. touch "$cache_file" || return 1
  2635. return 0
  2636. fi
  2637. if [ -z "$COMPOSE_YML_FILE" ]; then
  2638. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  2639. fi
  2640. if [ -e "$COMPOSE_YML_FILE" ]; then
  2641. debug "Found $WHITE$exname$NORMAL YAML file in '$COMPOSE_YML_FILE'."
  2642. COMPOSE_YML_CONTENT=$(cat "$COMPOSE_YML_FILE") || {
  2643. err "Could not read '$COMPOSE_YML_FILE'."
  2644. return 1
  2645. }
  2646. else
  2647. debug "No compose file found. Using an empty one."
  2648. COMPOSE_YML_CONTENT=""
  2649. fi
  2650. COMPOSE_YML_CONTENT=$(merge_yaml_str "$COMPOSE_YML_CONTENT" "${compose_contents[@]}") || return 1
  2651. output=$(echo "$COMPOSE_YML_CONTENT"| shyaml get-value 2>&1)
  2652. if [ "$?" != 0 ]; then
  2653. outputed_something=
  2654. while IFS='' read -r line1 && IFS='' read -r line2; do
  2655. [ "$outputed_something" ] || err "Invalid YAML in '$COMPOSE_YML_FILE':"
  2656. outputed_something=true
  2657. echo "$line1 $GRAY($line2)$NORMAL"
  2658. done < <(echo "$output" | grep ^yaml.scanner -A 100 |
  2659. sed -r 's/^ in "<stdin>", //g' | sed -r 's/^yaml.scanner.[a-zA-Z]+: //g') |
  2660. prefix " $GRAY|$NORMAL "
  2661. [ "$outputed_something" ] || {
  2662. err "Unexpected error while running 'shyaml get-value' on '$COMPOSE_YML_FILE':"
  2663. echo "$output" | prefix " $GRAY|$NORMAL "
  2664. }
  2665. return 1
  2666. fi
  2667. echo "$COMPOSE_YML_CONTENT" | tee "$cache_file" || return 1
  2668. }
  2669. export -f get_compose_yml_content
  2670. get_default_target_services() {
  2671. local services=("$@")
  2672. if [ -z "${services[*]}" ]; then
  2673. if [ "$DEFAULT_SERVICES" ]; then
  2674. debug "No service provided, using $WHITE\$DEFAULT_SERVICES$NORMAL variable." \
  2675. "Target services: $DARKYELLOW$DEFAULT_SERVICES$NORMAL"
  2676. services="$DEFAULT_SERVICES"
  2677. else
  2678. err "No service provided."
  2679. return 1
  2680. fi
  2681. fi
  2682. echo "${services[*]}"
  2683. }
  2684. export -f get_default_target_services
  2685. get_master_services() {
  2686. local loaded master_service service
  2687. declare -A loaded
  2688. for service in "$@"; do
  2689. master_service=$(get_top_master_service_for_service "$service") || return 1
  2690. if [ "${loaded[$master_service]}" ]; then
  2691. continue
  2692. fi
  2693. echo "$master_service"
  2694. loaded["$master_service"]=1
  2695. done | xargs printf "%s "
  2696. return "${PIPESTATUS[0]}"
  2697. }
  2698. export -f get_master_services
  2699. get_current_docker_container_id() {
  2700. local line
  2701. line=$(cat "/proc/self/cpuset") || return 1
  2702. [[ "$line" == *docker* ]] || return 1
  2703. echo "${line##*/}"
  2704. }
  2705. export -f get_current_docker_container_id
  2706. ## if we are in a docker compose, we might want to know what is the
  2707. ## real host path of some local paths.
  2708. get_host_path() {
  2709. local path="$1"
  2710. path=$(realpath "$path") || return 1
  2711. container_id=$(get_current_docker_container_id) || {
  2712. print "%s" "$path"
  2713. return 0
  2714. }
  2715. biggest_dst=
  2716. current_src=
  2717. while read-0 src dst; do
  2718. [[ "$path" == "$dst"* ]] || continue
  2719. if [[ "${#biggest_dst}" < "${#dst}" ]]; then
  2720. biggest_dst="$dst"
  2721. current_src="$src"
  2722. fi
  2723. done < <(get_volumes_for_container "$container_id")
  2724. if [ "$current_src" ]; then
  2725. printf "%s" "$current_src"
  2726. else
  2727. return 1
  2728. fi
  2729. }
  2730. export -f get_host_path
  2731. _setup_state_dir() {
  2732. export state_tmpdir=$(mktemp -d -t tmp.XXXXXXXXXX)
  2733. #debug "Creating temporary state directory in '$state_tmpdir'."
  2734. # trap_add EXIT "debug \"Removing temporary state directory in $state_tmpdir.\";\
  2735. # rm -rf \"$state_tmpdir\""
  2736. trap_add EXIT "rm -rf \"$state_tmpdir\""
  2737. }
  2738. get_docker_compose_help_msg() {
  2739. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2740. docker_compose_help_msg
  2741. if [ -e "$cache_file" ]; then
  2742. cat "$cache_file" &&
  2743. touch "$cache_file" || return 1
  2744. return 0
  2745. fi
  2746. docker_compose_help_msg=$(docker-compose $action --help 2>/dev/null) || return 1
  2747. echo "$docker_compose_help_msg" |
  2748. tee "$cache_file" || return 1
  2749. }
  2750. get_docker_compose_usage() {
  2751. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2752. docker_compose_help_msg
  2753. if [ -e "$cache_file" ]; then
  2754. cat "$cache_file" &&
  2755. touch "$cache_file" || return 1
  2756. return 0
  2757. fi
  2758. docker_compose_help_msg=$(get_docker_compose_help_msg $action) || return 1
  2759. echo "$docker_compose_help_msg" |
  2760. grep -m 1 "^Usage:" -A 10000 |
  2761. egrep -m 1 "^\$" -B 10000 |
  2762. xargs printf "%s " |
  2763. sed -r 's/^Usage: //g' |
  2764. tee "$cache_file" || return 1
  2765. }
  2766. get_docker_compose_opts_help() {
  2767. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2768. docker_compose_help_msg
  2769. if [ -e "$cache_file" ]; then
  2770. cat "$cache_file" &&
  2771. touch "$cache_file" || return 1
  2772. return 0
  2773. fi
  2774. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2775. echo "$docker_compose_opts_help" |
  2776. grep '^Options:' -A 20000 |
  2777. tail -n +2 |
  2778. { cat ; echo; } |
  2779. egrep -m 1 "^\S*\$" -B 10000 |
  2780. head -n -1 |
  2781. tee "$cache_file" || return 1
  2782. }
  2783. get_docker_compose_commands_help() {
  2784. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2785. docker_compose_help_msg
  2786. if [ -e "$cache_file" ]; then
  2787. cat "$cache_file" &&
  2788. touch "$cache_file" || return 1
  2789. return 0
  2790. fi
  2791. docker_compose_opts_help=$(get_docker_compose_help_msg $action) || return 1
  2792. echo "$docker_compose_opts_help" |
  2793. grep '^Commands:' -A 20000 |
  2794. tail -n +2 |
  2795. { cat ; echo; } |
  2796. egrep -m 1 "^\S*\$" -B 10000 |
  2797. head -n -1 |
  2798. tee "$cache_file" || return 1
  2799. }
  2800. get_docker_compose_opts_list() {
  2801. local action="$1" cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$1"; cat "$(which docker-compose)" | md5_compat)" \
  2802. docker_compose_help_msg
  2803. if [ -e "$cache_file" ]; then
  2804. cat "$cache_file" &&
  2805. touch "$cache_file" || return 1
  2806. return 0
  2807. fi
  2808. docker_compose_opts_help=$(get_docker_compose_opts_help $action) || return 1
  2809. echo "$docker_compose_opts_help" |
  2810. egrep "^\s+-" |
  2811. sed -r 's/\s+((((-[a-zA-Z]|--[a-zA-Z0-9-]+)( [A-Z=]+|=[^ ]+)?)(, )?)+)\s+.*$/\1/g' |
  2812. tee "$cache_file" || return 1
  2813. }
  2814. options_parser() {
  2815. sed -r 's/^(\s+(((-[a-zA-Z]|--[a-zA-Z0-9-]+)([ =]([a-zA-Z_=\"\[]|\])+)?(, | )?)+)\s+)[^ ].*$/\x0\2\x0\0/g'
  2816. printf "\0"
  2817. }
  2818. remove_options_in_option_help_msg() {
  2819. {
  2820. read-0 null
  2821. if [ "$null" ]; then
  2822. err "options parsing error, should start with an option line."
  2823. return 1
  2824. fi
  2825. while read-0 opt full_txt;do
  2826. multi_opts="$(printf "%s " $opt | multi_opts_filter)"
  2827. single_opts="$(printf "%s " $opt | single_opts_filter)"
  2828. for to_remove in "$@"; do
  2829. str_matches "$to_remove" $multi_opts $single_opts && {
  2830. continue 2
  2831. }
  2832. done
  2833. echo -n "$full_txt"
  2834. done
  2835. } < <(options_parser)
  2836. }
  2837. _MULTIOPTION_REGEX='^((-[a-zA-Z]|--[a-zA-Z0-9-]+)(, )?)+'
  2838. _MULTIOPTION_REGEX_LINE_FILTER=$_MULTIOPTION_REGEX'(\s|=)'
  2839. multi_opts_filter() {
  2840. egrep "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2841. sed -r "s/^($_MULTIOPTION_REGEX)(\s|=).*$/\1/g" |
  2842. tr ',' "\n" | xargs printf "%s "
  2843. }
  2844. single_opts_filter() {
  2845. egrep -v "$_MULTIOPTION_REGEX_LINE_FILTER" |
  2846. tr ',' "\n" | xargs printf "%s "
  2847. }
  2848. get_docker_compose_multi_opts_list() {
  2849. local action="$1" opts_list
  2850. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2851. echo "$opts_list" | multi_opts_filter
  2852. }
  2853. get_docker_compose_single_opts_list() {
  2854. local action="$1" opts_list
  2855. opts_list=$(get_docker_compose_opts_list "$action") || return 1
  2856. echo "$opts_list" | single_opts_filter
  2857. }
  2858. display_commands_help() {
  2859. local charm_actions
  2860. echo
  2861. echo "${WHITE}Commands${NORMAL} (thanks to docker-compose):"
  2862. get_docker_compose_commands_help | sed -r "s/ ([a-z]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2/g"
  2863. charm_actions_help=$(get_docker_charm_action_help) || return 1
  2864. if [ "$charm_actions_help" ]; then
  2865. echo
  2866. echo "${WHITE}Charm actions${NORMAL}:"
  2867. printf "%s\n" "$charm_actions_help" | \
  2868. sed -r "s/^ ([a-z0-9-]+)(\s+)([a-z0-9-]+)(\s+)/ ${DARKCYAN}\1${NORMAL}\2${DARKYELLOW}\3${NORMAL}\4/g"
  2869. fi
  2870. }
  2871. get_docker_charm_action_help() {
  2872. local services service charm relation_name target_service relation_config \
  2873. target_charm
  2874. services=($(get_compose_yml_content | shyaml keys 2>/dev/null))
  2875. for service in "${services[@]}"; do
  2876. out=$(
  2877. charm=$(get_service_charm "$service") || return 1
  2878. for action in $(charm.ls_direct_actions "$charm"); do
  2879. printf " %-28s %s\n" "$action $service" "Direct action from ${DARKPINK}$charm${NORMAL}"
  2880. done
  2881. while read-0 relation_name target_service _relation_config _tech_dep; do
  2882. target_charm=$(get_service_charm "$target_service") || return 1
  2883. for action in $(charm.ls_relation_actions "$target_charm" "$relation_name"); do
  2884. printf " %-28s %s\n" "$action $service" "Indirect action from ${DARKPINK}$target_charm${NORMAL}"
  2885. done
  2886. done < <(get_compose_relations "$service")
  2887. )
  2888. if [ "$out" ]; then
  2889. echo " for ${DARKYELLOW}$service${NORMAL}:"
  2890. printf "%s\n" "$out"
  2891. fi
  2892. done
  2893. }
  2894. display_help() {
  2895. print_help
  2896. echo "${WHITE}Options${NORMAL}:"
  2897. echo " -h, --help Print this message and quit"
  2898. echo " (ignoring any other options)"
  2899. echo " -V, --version Print current version and quit"
  2900. echo " (ignoring any other options)"
  2901. echo " --dirs Display data dirs and quit"
  2902. echo " (ignoring any other options)"
  2903. echo " -v, --verbose Be more verbose"
  2904. echo " -d, --debug Print full debugging information (sets also verbose)"
  2905. echo " --dry-compose-run If docker-compose will be run, only print out what"
  2906. echo " command line will be used."
  2907. echo " --rebuild-relations-to-service, -R SERVICE"
  2908. echo " Will rebuild all relations to given service"
  2909. echo " --add-compose-content, -Y YAML"
  2910. echo " Will merge some direct YAML with the current compose"
  2911. get_docker_compose_opts_help | remove_options_in_option_help_msg --version --help --verbose |
  2912. filter_docker_compose_help_message
  2913. display_commands_help
  2914. }
  2915. _graph_service() {
  2916. local service="$1" base="$1"
  2917. charm=$(get_service_charm "$service") || return 1
  2918. metadata=$(charm.metadata "$charm") || return 1
  2919. subordinate=$(echo "$metadata" | shyaml get-value "subordinate" 2>/dev/null)
  2920. if [ "$subordinate" == "True" ]; then
  2921. requires="$(echo "$metadata" | shyaml get-value "requires" 2>/dev/null)"
  2922. master_charm=
  2923. while read-0 relation_name relation; do
  2924. [ "$(echo "$relation" | shyaml get-value "scope" 2>/dev/null)" == "container" ] || continue
  2925. interface="$(echo "$relation" | shyaml get-value "interface" 2>/dev/null)"
  2926. if [ -z "$interface" ]; then
  2927. err "No ${WHITE}$interface${NORMAL} set for relation $relation_name."
  2928. return 1
  2929. fi
  2930. ## Action provided by relation ?
  2931. target_service=
  2932. while read-0 relation_name candidate_target_service _relation_config _tech_dep; do
  2933. [ "$interface" == "$relation_name" ] && {
  2934. target_service="$candidate_target_service"
  2935. break
  2936. }
  2937. done < <(get_service_relations "$service")
  2938. if [ -z "$target_service" ]; then
  2939. err "Couldn't find ${WHITE}relations.$interface${NORMAL} in" \
  2940. "${DARKYELLOW}$service$NORMAL compose definition."
  2941. return 1
  2942. fi
  2943. master_service="$target_service"
  2944. master_charm=$(get_service_charm "$target_service") || return 1
  2945. break
  2946. done < <(echo "$requires" | shyaml key-values-0 2>/dev/null)
  2947. fi
  2948. _graph_node_service "$service" "$base" "$charm"
  2949. _graph_edge_service "$service" "$subordinate" "$master_service"
  2950. }
  2951. _graph_node_service() {
  2952. local service="$1" base="$2" charm="$3"
  2953. cat <<EOF
  2954. "$(_graph_node_service_label ${service})" [
  2955. style = "filled, $([ "$subordinate" == "True" ] && echo "dashed" || echo "bold")"
  2956. penwidth = $([ "$subordinate" == "True" ] && echo "3" || echo "5")
  2957. color = $([ "$base" ] && echo "blue" || echo "black")
  2958. fillcolor = "white"
  2959. fontname = "Courier New"
  2960. shape = "Mrecord"
  2961. label =<$(_graph_node_service_content "$service")>
  2962. ];
  2963. EOF
  2964. }
  2965. _graph_edge_service() {
  2966. local service="$1" subordinate="$2" master_service="$3"
  2967. while read-0 relation_name target_service relation_config tech_dep; do
  2968. cat <<EOF
  2969. "$(_graph_node_service_label ${service})" -> "$(_graph_node_service_label ${target_service})" [
  2970. penwidth = $([ "$master_service" == "$target_service" ] && echo 3 || echo 2)
  2971. fontsize = 16
  2972. fontcolor = "black"
  2973. style = $([ "$master_service" == "$target_service" ] && echo dashed || echo "\"\"")
  2974. weight = $([ "$master_service" == "$target_service" ] && echo 2.0 || echo 1.0)
  2975. dir = $([ "$master_service" == "$target_service" ] && echo none || echo both)
  2976. arrowtail = odot
  2977. # arrowhead = dotlicurve
  2978. taillabel = "$relation_name" ];
  2979. EOF
  2980. done < <(get_service_relations "$service") || return 1
  2981. }
  2982. _graph_node_service_label() {
  2983. local service="$1"
  2984. echo "service_$service"
  2985. }
  2986. _graph_node_service_content() {
  2987. local service="$1"
  2988. charm=$(get_service_charm "$service") || return 1
  2989. cat <<EOF
  2990. <table border="0" cellborder="0" cellpadding="3" bgcolor="white">
  2991. <tr>
  2992. <td bgcolor="black" align="center" colspan="2">
  2993. <font color="white">$service</font>
  2994. </td>
  2995. </tr>
  2996. $(if [ "$charm" != "$service" ]; then
  2997. cat <<EOF2
  2998. <tr>
  2999. <td align="left" port="r0">charm: $charm</td>
  3000. </tr>
  3001. EOF2
  3002. fi)
  3003. </table>
  3004. EOF
  3005. }
  3006. cla_contains () {
  3007. local e
  3008. for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  3009. return 1
  3010. }
  3011. filter_docker_compose_help_message() {
  3012. cat - |
  3013. sed -r "s/docker-compose run/${DARKWHITE}compose${NORMAL} ${DARKCYAN}$action${NORMAL}/g;
  3014. s/docker-compose.yml/compose.yml/g;
  3015. s/SERVICES?/${DARKYELLOW}\0${NORMAL}/g;
  3016. s/^(\s+)\\$/\1${WHITE}\$${NORMAL}/g;
  3017. s/^(\s+)run/\1${DARKCYAN}$action${NORMAL}/g;
  3018. s/docker-compose/${DARKWHITE}compose${NORMAL}/g"
  3019. }
  3020. graph() {
  3021. local services=("$@")
  3022. declare -A entries
  3023. cat <<EOF
  3024. digraph g {
  3025. graph [
  3026. fontsize=30
  3027. labelloc="t"
  3028. label=""
  3029. splines=true
  3030. overlap=false
  3031. #rankdir = "LR"
  3032. ];
  3033. ratio = auto;
  3034. EOF
  3035. for target_service in "$@"; do
  3036. services=$(get_ordered_service_dependencies "$target_service") || return 1
  3037. for service in $services; do
  3038. [ "${entries[$service]}" ] && continue || entries[$service]=1
  3039. if cla_contains "$service" "${services[@]}"; then
  3040. base=true
  3041. else
  3042. base=
  3043. fi
  3044. _graph_service "$service" "$base"
  3045. done
  3046. done
  3047. echo "}"
  3048. }
  3049. cached_wget() {
  3050. local cache_file="$CACHEDIR/$FUNCNAME.cache.$(echo "$*" | md5_compat)" \
  3051. url="$1"
  3052. if [ -e "$cache_file" ]; then
  3053. cat "$cache_file"
  3054. touch "$cache_file"
  3055. return 0
  3056. fi
  3057. wget -O- "${url}" |
  3058. tee "$cache_file"
  3059. if [ "${PIPESTATUS[0]}" != 0 ]; then
  3060. rm "$cache_file"
  3061. die "Unable to fetch '$url'."
  3062. return 1
  3063. fi
  3064. }
  3065. export -f cached_wget
  3066. [ "$SOURCED" ] && return 0
  3067. trap_add "EXIT" clean_cache
  3068. if [ -z "$DISABLE_SYSTEM_CONFIG_FILE" ]; then
  3069. if [ -r /etc/default/charm ]; then
  3070. . /etc/default/charm
  3071. fi
  3072. if [ -r "/etc/default/$exname" ]; then
  3073. . "/etc/default/$exname"
  3074. fi
  3075. ## XXXvlab: should provide YML config opportunities in possible parent dirs ?
  3076. ## userdir ? and global /etc/compose.yml ?
  3077. for cfgfile in /etc/compose.conf /etc/compose.local.conf \
  3078. /etc/default/compose /etc/compose/local.conf; do
  3079. [ -e "$cfgfile" ] || continue
  3080. . "$cfgfile" || die "Loading config file '$cfgfile' failed."
  3081. done
  3082. fi
  3083. _setup_state_dir
  3084. mkdir -p "$CACHEDIR" || exit 1
  3085. ##
  3086. ## Argument parsing
  3087. ##
  3088. services=()
  3089. remainder_args=()
  3090. compose_opts=()
  3091. compose_contents=()
  3092. action_opts=()
  3093. services_args=()
  3094. pos_arg_ct=0
  3095. no_hooks=
  3096. no_init=
  3097. action=
  3098. stage="main" ## switches from 'main', to 'action', 'remainder'
  3099. is_docker_compose_action=
  3100. rebuild_relations_to_service=()
  3101. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list) &&
  3102. DC_MATCH_SINGLE=$(get_docker_compose_single_opts_list) || return 1
  3103. while read-0 arg; do
  3104. case "$stage" in
  3105. "main")
  3106. case "$arg" in
  3107. --help|-h)
  3108. no_init=true ; no_hooks=true ; no_relations=true
  3109. display_help
  3110. exit 0
  3111. ;;
  3112. --verbose|-v)
  3113. export VERBOSE=true
  3114. compose_opts+=("--verbose")
  3115. ;;
  3116. --version|-V)
  3117. print_version
  3118. docker-compose --version
  3119. docker --version
  3120. exit 0
  3121. ;;
  3122. -f|--file)
  3123. read-0 value
  3124. [ -e "$value" ] || die "File $value doesn't exists"
  3125. export DEFAULT_COMPOSE_FILE="$value"
  3126. compose_opts+=("--file $value")
  3127. shift
  3128. ;;
  3129. -p|--project-name)
  3130. read-0 value
  3131. export DEFAULT_PROJECT_NAME="$value"
  3132. compose_opts+=("--project-name $value")
  3133. shift
  3134. ;;
  3135. --no-relations)
  3136. export no_relations=true
  3137. ;;
  3138. --no-hooks)
  3139. export no_hooks=true
  3140. ;;
  3141. --no-init)
  3142. export no_init=true
  3143. ;;
  3144. --rebuild-relations-to-service|-R)
  3145. read-0 value
  3146. rebuild_relations_to_service+=("$value")
  3147. shift
  3148. ;;
  3149. --debug)
  3150. export DEBUG=true
  3151. export VERBOSE=true
  3152. #compose_opts+=("--verbose" "--log-level" "DEBUG")
  3153. ;;
  3154. --add-compose-content|-Y)
  3155. read-0 value
  3156. compose_contents+=("$value")
  3157. shift
  3158. ;;
  3159. --dirs)
  3160. echo "CACHEDIR: $CACHEDIR"
  3161. echo "VARDIR: $VARDIR"
  3162. exit 0
  3163. ;;
  3164. --dry-compose-run)
  3165. export DRY_COMPOSE_RUN=true
  3166. ;;
  3167. --*|-*)
  3168. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3169. read-0 value
  3170. compose_opts+=("$arg" "$value")
  3171. shift;
  3172. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3173. compose_opts+=("$arg")
  3174. else
  3175. err "Unknown option '$arg'. Please check help:"
  3176. display_help
  3177. exit 1
  3178. fi
  3179. ;;
  3180. *)
  3181. action="$arg"
  3182. stage="action"
  3183. if DC_USAGE=$(get_docker_compose_usage "$action"); then
  3184. is_docker_compose_action=true
  3185. DC_MATCH_MULTI=$(get_docker_compose_multi_opts_list "$action") &&
  3186. DC_MATCH_SINGLE="$(get_docker_compose_single_opts_list "$action")"
  3187. if [ "$DC_MATCH_MULTI" ]; then
  3188. DC_MATCH_SINGLE="$DC_MATCH_SINGLE $(echo "$DC_MATCH_MULTI" | sed -r 's/( |$)/=\* /g')"
  3189. fi
  3190. pos_args=($(echo "$DC_USAGE" | sed -r 's/\[-[^]]+\] ?//g;s/\[options\] ?//g'))
  3191. pos_args=("${pos_args[@]:1}")
  3192. # echo "USAGE: $DC_USAGE"
  3193. # echo "pos_args: ${pos_args[@]}"
  3194. # echo "MULTI: $DC_MATCH_MULTI"
  3195. # echo "SINGLE: $DC_MATCH_SINGLE"
  3196. # exit 1
  3197. else
  3198. stage="remainder"
  3199. fi
  3200. ;;
  3201. esac
  3202. ;;
  3203. "action") ## Only for docker-compose actions
  3204. case "$arg" in
  3205. --help|-h)
  3206. no_init=true ; no_hooks=true ; no_relations=true
  3207. action_opts+=("$arg")
  3208. ;;
  3209. --*|-*)
  3210. if [ "$is_docker_compose_action" ]; then
  3211. if str_pattern_matches "$arg" $DC_MATCH_MULTI; then
  3212. read-0 value
  3213. action_opts+=("$arg" "$value")
  3214. shift
  3215. elif str_pattern_matches "$arg" $DC_MATCH_SINGLE; then
  3216. action_opts+=("$arg")
  3217. else
  3218. err "Unknown option '$arg'. Please check '${DARKCYAN}$action${NORMAL}' help:"
  3219. docker-compose "$action" --help |
  3220. filter_docker_compose_help_message >&2
  3221. exit 1
  3222. fi
  3223. fi
  3224. ;;
  3225. *)
  3226. # echo "LOOP $1 : pos_arg: $pos_arg_ct // ${pos_args[$pos_arg_ct]}"
  3227. if [[ "${pos_args[$pos_arg_ct]}" == "[SERVICE...]" ]]; then
  3228. services_args+=("$arg")
  3229. elif [[ "${pos_args[$pos_arg_ct]}" == "SERVICE" ]]; then
  3230. services_args=("$arg") || exit 1
  3231. stage="remainder"
  3232. else
  3233. action_posargs+=("$arg")
  3234. ((pos_arg_ct++))
  3235. fi
  3236. ;;
  3237. esac
  3238. ;;
  3239. "remainder")
  3240. remainder_args+=("$arg")
  3241. while read-0 arg; do
  3242. remainder_args+=("$arg")
  3243. done
  3244. break 3
  3245. ;;
  3246. esac
  3247. shift
  3248. done < <(cla.normalize "$@")
  3249. export compose_contents
  3250. [ "${services_args[*]}" ] && debug " ${DARKWHITE}Services:$NORMAL ${DARKYELLOW}${services_args[*]}$NORMAL"
  3251. [ "${compose_opts[*]}" ] && debug " ${DARKWHITE}Main docker-compose opts:$NORMAL ${compose_opts[*]}"
  3252. [ "${action_posargs[*]}" ] && debug " ${DARKWHITE}Main docker-compose pos args:$NORMAL ${action_posargs[*]}"
  3253. [ "${action_opts[*]}" ] && debug " ${DARKWHITE}Action $DARKCYAN$action$NORMAL with opts:$NORMAL ${action_opts[*]}"
  3254. [ "${remainder_args[*]}" ] && debug " ${DARKWHITE}Remainder args:$NORMAL ${remainder_args[*]}"
  3255. aexport remainder_args
  3256. ##
  3257. ## Actual code
  3258. ##
  3259. COMPOSE_YML_FILE=$(get_compose_yml_location) || exit 1
  3260. COMPOSE_YML_CONTENT=$(get_compose_yml_content) || exit 1
  3261. export COMPOSE_YML_FILE COMPOSE_YML_CONTENT
  3262. charm.sanity_checks || die "Sanity checks about charm-store failed. Please correct."
  3263. ##
  3264. ## Get services in command line.
  3265. ##
  3266. if [ -z "$is_docker_compose_action" -a "$action" ]; then
  3267. action_service=${remainder_args[0]}
  3268. if [ -z "$action_service" ]; then
  3269. err "No such command or action: ${DARKCYAN}$action${NORMAL}"
  3270. display_commands_help
  3271. exit 1
  3272. fi
  3273. remainder_args=("${remainder_args[@]:1}")
  3274. if has_service_action "$action_service" "$action" >/dev/null; then
  3275. is_service_action=true
  3276. {
  3277. read-0 action_type
  3278. case "$action_type" in
  3279. "relation")
  3280. read-0 _ target_service _target_charm relation_name
  3281. debug "Found action $DARKYELLOW${action_service}$NORMAL/$DARKBLUE$relation_name$NORMAL/$DARKCYAN$action$NORMAL (in $DARKYELLOW$target_service$NORMAL)"
  3282. ;;
  3283. "direct")
  3284. debug "Found action $DARKYELLOW${action_service}$NORMAL.$DARKCYAN$action$NORMAL"
  3285. ;;
  3286. esac
  3287. } < <(has_service_action "$action_service" "$action")
  3288. services_args=("$action_service")
  3289. else
  3290. die "Unknown action '${DARKCYAN}$action$NORMAL': It doesn't match any docker-compose commands nor inner charm actions."
  3291. fi
  3292. else
  3293. case "$action" in
  3294. ps|up)
  3295. if [ "${#services_args[@]}" == 0 ]; then
  3296. array_read-0 services_args < <(printf "%s" "$COMPOSE_YML_CONTENT" | shyaml keys-0 2>/dev/null)
  3297. fi
  3298. ;;
  3299. config)
  3300. services_args=("${action_posargs[@]}")
  3301. ;;
  3302. esac
  3303. fi
  3304. NO_CONSTRAINT_CHECK=True
  3305. case "$action" in
  3306. up)
  3307. NO_CONSTRAINT_CHECK=
  3308. ;;
  3309. esac
  3310. get_all_relations "${services_args[@]}" >/dev/null || exit 1
  3311. if [ "$is_docker_compose_action" -a "${#services_args[@]}" -gt 0 ]; then
  3312. services=($(get_master_services "${services_args[@]}")) || exit 1
  3313. if [ "$action" == "up" ]; then
  3314. ## remove run-once
  3315. for service in "${services_args[@]}"; do
  3316. type="$(get_service_type "$service")" || exit 1
  3317. if [ "$type" != "run-once" ]; then
  3318. action_posargs+=("$service")
  3319. fi
  3320. done
  3321. else
  3322. action_posargs+=("${services[@]}")
  3323. fi
  3324. fi
  3325. get_docker_compose "${services_args[@]}" >/dev/null || { ## precalculate variable \$_current_docker_compose
  3326. err "Fails to compile base 'docker-compose.yml'"
  3327. exit 1
  3328. }
  3329. ##
  3330. ## Pre-action
  3331. ##
  3332. full_init=
  3333. case "$action" in
  3334. up|run)
  3335. full_init=true
  3336. post_hook=true
  3337. ;;
  3338. ""|down|restart|logs|config|ps)
  3339. full_init=
  3340. ;;
  3341. *)
  3342. if [ "$is_service_action" ]; then
  3343. full_init=true
  3344. fi
  3345. ;;
  3346. esac
  3347. if [ "$full_init" ]; then
  3348. ## init in order
  3349. if [ -z "$no_init" ]; then
  3350. Section setup host resources
  3351. setup_host_resources "${services_args[@]}" || exit 1
  3352. Section initialisation
  3353. run_service_hook init "${services_args[@]}" || exit 1
  3354. fi
  3355. ## Get relations
  3356. if [ -z "$no_relations" ]; then
  3357. if [ "${#rebuild_relations_to_service[@]}" != 0 ]; then
  3358. rebuild_relations_to_service=$(get_master_services "${rebuild_relations_to_service[@]}") || return 1
  3359. rebuild_relations_to_service=($rebuild_relations_to_service)
  3360. project=$(get_default_project_name) || return 1
  3361. for service in "${rebuild_relations_to_service[@]}"; do
  3362. for dir in "$VARDIR/relations/$project/"*"-${service}/"*; do
  3363. [ -d "$dir" ] && {
  3364. debug rm -rf "$dir"
  3365. rm -rf "$dir"
  3366. }
  3367. done
  3368. done
  3369. fi
  3370. run_service_relations "${services_args[@]}" || exit 1
  3371. fi
  3372. run_service_hook pre_deploy "${services_args[@]}" || exit 1
  3373. fi
  3374. if [ "$action" == "run" -a "${#services_args}" != 0 ]; then
  3375. charm=$(get_service_charm "${services_args[0]}") || exit 1
  3376. metadata=$(charm.metadata "$charm") || exit 1
  3377. type="$(printf "%s" "$metadata" | shyaml get-value type 2>/dev/null)" || true
  3378. if [ "$type" == "run-once" ]; then
  3379. run_service_hook dc-pre-run "${services_args[@]}" || exit 1
  3380. fi
  3381. fi
  3382. export SERVICE_PACK="${services_args[*]}"
  3383. ##
  3384. ## Docker-compose
  3385. ##
  3386. case "$action" in
  3387. up|start|stop|build|run)
  3388. ## force daemon mode for up
  3389. if [[ "$action" == "up" ]]; then
  3390. if ! array_member action_opts -d; then
  3391. action_opts+=("-d")
  3392. fi
  3393. if ! array_member action_opts --remove-orphans; then
  3394. action_opts+=("--remove-orphans")
  3395. fi
  3396. fi
  3397. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3398. ;;
  3399. logs)
  3400. if ! array_member action_opts --tail; then ## force daemon mode for up
  3401. action_opts+=("--tail" "10")
  3402. fi
  3403. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3404. ;;
  3405. "")
  3406. launch_docker_compose "${compose_opts[@]}"
  3407. ;;
  3408. graph)
  3409. graph $SERVICE_PACK
  3410. ;;
  3411. config)
  3412. ## removing the services
  3413. services=($(get_master_services "${action_posargs[@]}")) || exit 1
  3414. ## forcing docker-compose config to output the config file to stdout and not stderr
  3415. out=$(launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}" 2>&1) || {
  3416. echo "$out"
  3417. exit 1
  3418. }
  3419. echo "$out"
  3420. warn "Runtime configuration modification (from relations) are not included here."
  3421. ;;
  3422. down)
  3423. if ! array_member action_opts --remove-orphans; then ## force daemon mode for up
  3424. debug "Adding a default argument of '--remove-orphans'"
  3425. action_opts+=("--remove-orphans")
  3426. fi
  3427. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${remainder_args[@]}"
  3428. ;;
  3429. *)
  3430. if [ "$is_service_action" ]; then
  3431. run_service_action "$SERVICE_PACK" "$action" "${remainder_args[@]}"
  3432. else
  3433. launch_docker_compose "${compose_opts[@]}" "$action" "${action_opts[@]}" "${action_posargs[@]}" "${remainder_args[@]}"
  3434. fi
  3435. ;;
  3436. esac || exit 1
  3437. if [ "$post_hook" -a "${#services_args[@]}" != 0 ]; then
  3438. run_service_hook post_deploy "${services_args[@]}" || exit 1
  3439. fi
  3440. clean_unused_docker_compose || return 1