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.

4007 lines
132 KiB

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