Compare commits
415 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 21e0ae63a6 | |||
| 370f40881d | |||
| fb71a7e4b0 | |||
| ef9a63b075 | |||
| faef059edf | |||
| ad9fbf7b6d | |||
| 3bd17b8069 | |||
| 99bf1487ae | |||
| c3b4f01c44 | |||
| 9d5c892023 | |||
| d8d1d25ec2 | |||
| d02d7e5e1d | |||
| 39f8ff62f0 | |||
| 9a434b0e54 | |||
| b5053d2659 | |||
| 0fe2ac6b90 | |||
| 95c924968a | |||
| 523a3bb26b | |||
| 96396b2e86 | |||
| 8749f0bd3d | |||
| bc92660e09 | |||
| 8b0637ddcc | |||
| bbdc6f5465 | |||
| bc5e1ede04 | |||
| 2b3daaf9f1 | |||
| 2b3df7e342 | |||
| 5e4d4188f4 | |||
| 1e8ffe4486 | |||
| 59389b84a2 | |||
| 4fae0bb68e | |||
| 9777a441e9 | |||
| 1a72edea5d | |||
| 96db636582 | |||
| 190ab7c08d | |||
| 6be133f55d | |||
| 5ffd470596 | |||
| 2119dc40ab | |||
| 0df1c4cdcc | |||
| 2658695a35 | |||
| 1ac1635b3d | |||
| 4a2806f6d1 | |||
| 0a264b9b41 | |||
| a3379d6785 | |||
| 6260b75031 | |||
| 3ffb69bfb0 | |||
| 1da8f848f2 | |||
| 6ed4626df9 | |||
| c07f9ec62e | |||
| fd5b0e6831 | |||
| a4cea1b4f3 | |||
| c0b52b92d5 | |||
| 12018b3685 | |||
| a91fb873e4 | |||
| a6aa610165 | |||
| 6c87bdb9fb | |||
| b9250a41a2 | |||
| a967986a18 | |||
| c743c7b03f | |||
| a9c61b4b0b | |||
| 206d359dcd | |||
| 2d8c3692ec | |||
| 7769263c2e | |||
| 89f7c76c4e | |||
| c7771f98f5 | |||
| 299f1c906e | |||
| d3f68ae4e8 | |||
| 193abbe6b1 | |||
| 02b215128e | |||
| dc03db7423 | |||
| 1df0f8912a | |||
| e4112d888c | |||
| 53f9bd6d88 | |||
| 43c2a0d9b0 | |||
| e0c7ceedd5 | |||
| 2642c64303 | |||
| 1acafabb5b | |||
| 19b2deb2cf | |||
| ce6701fb33 | |||
| 0121929164 | |||
| bc96f8f212 | |||
| 459508c9d9 | |||
| 4a27cc63a8 | |||
| 0a6840273a | |||
| 76ef84f83b | |||
| 66946df756 | |||
| 556fac3002 | |||
| 1ad7df2df3 | |||
| a3d010c5f0 | |||
| 12503dc55a | |||
| 7d10a71cc0 | |||
| 3d3d1b5679 | |||
| 5240ab4949 | |||
| 19aebd399f | |||
| 04e03f4d06 | |||
| 2e2a8a1d5d | |||
| a2b2e0fe34 | |||
| af2905d245 | |||
| c3f0041efd | |||
| 083f6001eb | |||
| 2d57ec6ee0 | |||
| fb6a9be954 | |||
| c1e2c9826f | |||
| b00b61e967 | |||
| ac147b5a6f | |||
| 1850a332ed | |||
| 20ff9717bc | |||
| c2fbf93365 | |||
| cf5e8e8f26 | |||
| c600cc1f60 | |||
| c6a9ebc71c | |||
| 1f0f2f8569 | |||
| 5104ad3d0b | |||
| a6dbda1ea8 | |||
| 1edb8014bc | |||
| 845195b7ed | |||
| 2c9fcd7c14 | |||
| 4f9b63aa09 | |||
| a8e92971d0 | |||
| b54e477602 | |||
| 959fb08a89 | |||
| 6ac012aa3c | |||
| 3e93b31f75 | |||
| 08df208149 | |||
| 936ed73a45 | |||
| 8fee536260 | |||
| 01b4792974 | |||
| ad80bb3735 | |||
| f5f269bfd5 | |||
| 5b16769057 | |||
| 009bd410af | |||
| bcfcd7a134 | |||
| bf1276f767 | |||
| 9fa7a18351 | |||
| 50e8ee4549 | |||
| 3b5a1a8b9a | |||
| f661d9429f | |||
| ac4b109872 | |||
| b2c6e51a43 | |||
| ee2336a24b | |||
| 1e85b1cb5f | |||
| 5c6d69a69c | |||
| 299808aaaf | |||
| 7071adc774 | |||
| 8d678eed19 | |||
| ab7abd9686 | |||
| a58ce74ed0 | |||
| 2c8c2cfa14 | |||
| 0ceea1b792 | |||
| 07f2bfff6a | |||
| b9ee14f6d7 | |||
| 393fc10a69 | |||
| 1c937e58f7 | |||
| 70bbdfe760 | |||
| efe7b17d21 | |||
| 166e80bb96 | |||
| 6ac537210b | |||
| 596a39c0f5 | |||
| d118bcc717 | |||
| 48be4032a2 | |||
| 2d545c87cd | |||
| 0b48ba54f8 | |||
| c3d87289bb | |||
| 0d96627ffb | |||
| 61acc7494a | |||
| 96d5288667 | |||
| b8cd3c59f1 | |||
| 91632b52bb | |||
| d39c0e3745 | |||
| 180eaea195 | |||
| 69ed2d7117 | |||
| c420f3c909 | |||
| 0a2dea05a9 | |||
| 293c89d392 | |||
| bb5ef0c8b2 | |||
| 8f44cdc284 | |||
| 53028ed50a | |||
| 17e152c601 | |||
| 2ba6aabd4a | |||
| 98207c904d | |||
| d2b825a8ae | |||
| 913b8b37fe | |||
| f494c5ba31 | |||
| b9503685f0 | |||
| 0f4143c0e0 | |||
| 8839ed1f95 | |||
| 41b4038ad5 | |||
| 88d21eb23a | |||
| e0be7e4d4f | |||
| 0c189265e8 | |||
| b1f8cdf385 | |||
| 428a60870a | |||
| af2d6579c5 | |||
| 0f3da73ef1 | |||
| fecc9416ab | |||
| a7915db4c3 | |||
| 3a4e841c73 | |||
| bcf6ff1c08 | |||
| ad7a104ab4 | |||
| 639359f393 | |||
| 91e310b7e3 | |||
| 5b30ad01ce | |||
| 8f4f9338a9 | |||
| 67bbce3c36 | |||
| 180c3d9ae1 | |||
| 7a5883d404 | |||
| c90acefacb | |||
| d6799e08d8 | |||
| c44dccc34b | |||
| 7f1695c457 | |||
| e500d9ee26 | |||
| d5ce578929 | |||
| 3f8fe3a368 | |||
| 6b4c6fc062 | |||
| e239d6f633 | |||
| 0bbe2befce | |||
| fa4e048169 | |||
| 4f9f21f7f2 | |||
| 480176ba2d | |||
| 1190c0f6d2 | |||
| 720a284db5 | |||
| 83fdffbcef | |||
| 0ee7a49d31 | |||
| 02db5994fe | |||
| 1d7a84e8ae | |||
| a0e3dc7040 | |||
| 43495d70c7 | |||
| fa586b493c | |||
| 30cdc1430e | |||
| 27673a23e9 | |||
| 95fc299733 | |||
| 4e702eedc9 | |||
| 8ff83f2f1a | |||
| 4b8f0ad112 | |||
| dbc8bbeb6a | |||
| b3e856f40d | |||
| 8e1937fe75 | |||
| 073514fc21 | |||
| dab222d95f | |||
| a827894274 | |||
| 9a8d813d14 | |||
| e391fa94f9 | |||
| 509185dfbe | |||
| 4b1b7a8561 | |||
| b330ccca5d | |||
| 05f1237a6d | |||
| 1c270b7e39 | |||
| 1b39e9d03c | |||
| 655a2e5404 | |||
| 9c80eea045 | |||
| 175ad1dd0b | |||
| 728e97700f | |||
| 94a0fbf953 | |||
| b056e7b2b9 | |||
| 6e927f20f9 | |||
| 301f163a44 | |||
| 474652ea51 | |||
| 1bc731e782 | |||
| 292b85b5ef | |||
| dce98d50da | |||
| 10a14a8c50 | |||
| bcb5965617 | |||
| f772b3d39f | |||
| 27db8c0afe | |||
| 0e5c77d2be | |||
| 0280727985 | |||
| b4abebce00 | |||
| d89afe58d4 | |||
| c855546b9f | |||
| 7d6ee4c166 | |||
| 2fbd9d8f8c | |||
| 18e101a04e | |||
| e594421322 | |||
| 0d4bfda2fb | |||
| b83c026cdc | |||
| 46caf31075 | |||
| 2b9d696b49 | |||
| 70afff6e3b | |||
| 01bbda13e5 | |||
| c5a8f6635f | |||
| 6f441c55dc | |||
| 7b34d6cba5 | |||
| 70f9c6482f | |||
| aed6149c8c | |||
| 0834a184b8 | |||
| f61295f76c | |||
| 0920a40751 | |||
| e0b5bd75f8 | |||
| 96e188d7c4 | |||
| 1336c91865 | |||
| 9568e46f05 | |||
| 3187129672 | |||
| 44bd354eae | |||
| 94caf8b8db | |||
| 3ff1966cab | |||
| a3842155c5 | |||
| 02b3b4f80c | |||
| 0882290595 | |||
| b8d9f4ba92 | |||
| 1462c5caa5 | |||
| 58c08c855f | |||
| 9a4763ceee | |||
| f8200a6386 | |||
| e35320f8ee | |||
| 5b52e5e331 | |||
| 6ebd9f1037 | |||
| 99ab16d7be | |||
| e675b35cda | |||
| ddd7acec49 | |||
| e7aa08564b | |||
| 93ccdb8024 | |||
| 501645f918 | |||
| 4fd9d30c98 | |||
| e2b9c16959 | |||
| 4ba85c40cc | |||
| cca95f613b | |||
| 5b50a66c6c | |||
| dd508280f0 | |||
| 2927d0ca15 | |||
| d35e2400b2 | |||
| 47ed599db7 | |||
| f899f4cbe4 | |||
| b3231d2bed | |||
| c24c327151 | |||
| 5e17d7ba80 | |||
| 0261dbfe3d | |||
| 4301f741db | |||
| 7e743c74dc | |||
| ad0b055245 | |||
| 27db3e6f70 | |||
| 4994b7a9ea | |||
| 080f2c0616 | |||
| d469cc04b6 | |||
| e0a25d04ac | |||
| b0f2c79944 | |||
| d2bc40f78d | |||
| 9e54f11960 | |||
| 6eda1f743f | |||
| 6787decef1 | |||
| d56d45a2ab | |||
| fcf16a163a | |||
| dc39c819a3 | |||
| 1048b09487 | |||
| 3806e97404 | |||
| c396f9508a | |||
| b9933f6cb2 | |||
| 0ba4b5eda6 | |||
| 18d2c350de | |||
| f8f9fd11cd | |||
| b422e6f12e | |||
| f8d5082bdd | |||
| ffe677e55a | |||
| 84eefa57bc | |||
| ad77371e38 | |||
| c524acb2df | |||
| 3edfe535c6 | |||
| d3b99e8e39 | |||
| 3c03f21419 | |||
| 5c95c21727 | |||
| a6b578b648 | |||
| 8af824df41 | |||
| 58ab25919e | |||
| 215848f476 | |||
| f9c7766073 | |||
| f976212ec9 | |||
| 8c88e168c1 | |||
| a78c854404 | |||
| 8a5af2f80e | |||
| f7aa26d418 | |||
| b5ff1a9926 | |||
| 729c83ee72 | |||
| 00434f4ac9 | |||
| 2cd9173bfb | |||
| 7ba3ae077f | |||
| a6497b2c6e | |||
| 07956c2299 | |||
| 77d3a1ad4d | |||
| 2e0ff9a582 | |||
| a65d8f1f4c | |||
| 424234c2d1 | |||
| 3bfe0c16d0 | |||
| e5f944c2f8 | |||
| d81a1818d6 | |||
| 921b34235e | |||
| a0cf9cff2a | |||
| 3105609d39 | |||
| 254a292362 | |||
| 95e16f01c1 | |||
| df21b5d1b4 | |||
| c4be60c29f | |||
| ff18181064 | |||
| b167de3096 | |||
| 9dd187e29d | |||
| 413bd0f43b | |||
| 3c3606d516 | |||
| b5dc04e62c | |||
| 234a327a03 | |||
| 90b32c7377 | |||
| 0fc6a63564 | |||
| 5138681c13 | |||
| d6304f4f1d | |||
| 082335df5d | |||
| be506661a5 | |||
| 38385adf22 | |||
| bbcfb47d28 | |||
| 32dd456ac6 | |||
| 4d2765e5f2 | |||
| 000d8bba66 | |||
| 5f909dab76 | |||
| 56e63ff551 | |||
| f31b54582f | |||
| 5b256a92b3 | |||
| cd829bd79a | |||
| 5b97953bfb | |||
| afed762774 | |||
| 5324f29693 |
+282
-64
@@ -1,79 +1,297 @@
|
|||||||
version: 2.0
|
version: 2.1
|
||||||
workflows:
|
orbs:
|
||||||
version: 2
|
# NB: 1.7.2 is not the Go version, but the Orb version
|
||||||
build:
|
# https://circleci.com/developer/orbs/orb/circleci/go#usage-go-modules-cache
|
||||||
jobs:
|
go: circleci/go@1.7.2
|
||||||
- build-1.11
|
commands:
|
||||||
- build-1.12
|
setup-home-local-bin:
|
||||||
- build-latest
|
|
||||||
jobs:
|
|
||||||
# build-latest serves as the template
|
|
||||||
# we use YAML anchors & aliases to exchange the docker image (and hence Go version used for the build)
|
|
||||||
build-latest: &build-latest
|
|
||||||
description: Builds zrepl
|
|
||||||
parameters:
|
|
||||||
image:
|
|
||||||
description: "the docker image that the job should use"
|
|
||||||
type: string
|
|
||||||
docker:
|
|
||||||
- image: circleci/golang:latest
|
|
||||||
environment:
|
|
||||||
# required by lazy.sh
|
|
||||||
TERM: xterm
|
|
||||||
working_directory: /go/src/github.com/zrepl/zrepl
|
|
||||||
steps:
|
steps:
|
||||||
- run:
|
- run:
|
||||||
name: Setup environment variables
|
shell: /bin/bash -euo pipefail
|
||||||
command: |
|
command: |
|
||||||
# used by pip (for docs)
|
mkdir -p "$HOME/.local/bin"
|
||||||
echo 'export PATH="$HOME/.local/bin:$PATH"' >> $BASH_ENV
|
line='export PATH="$HOME/.local/bin:$PATH"'
|
||||||
|
if grep "$line" $BASH_ENV >/dev/null; then
|
||||||
|
echo "$line" >> $BASH_ENV
|
||||||
|
fi
|
||||||
|
|
||||||
- restore_cache:
|
invoke-lazy-sh:
|
||||||
keys:
|
parameters:
|
||||||
- source
|
subcommand:
|
||||||
- vendor
|
type: string
|
||||||
- protobuf
|
steps:
|
||||||
|
- run:
|
||||||
|
environment:
|
||||||
|
TERM: xterm
|
||||||
|
command: ./lazy.sh <<parameters.subcommand>>
|
||||||
|
|
||||||
|
apt-update-and-install-common-deps:
|
||||||
|
steps:
|
||||||
|
- run: sudo apt-get update
|
||||||
|
- run: sudo apt-get install -y gawk make
|
||||||
|
# CircleCI doesn't update its cimg/go images.
|
||||||
|
# So, need to update manually to get up-to-date trust chains.
|
||||||
|
# The need for this was required for cimg/go:1.12, but let's future proof this here and now.
|
||||||
|
- run: sudo apt-get install -y git ca-certificates
|
||||||
|
|
||||||
|
install-godep:
|
||||||
|
steps:
|
||||||
|
- apt-update-and-install-common-deps
|
||||||
|
- invoke-lazy-sh:
|
||||||
|
subcommand: godep
|
||||||
|
|
||||||
|
install-docdep:
|
||||||
|
steps:
|
||||||
|
- apt-update-and-install-common-deps
|
||||||
|
- run: sudo apt install python3 python3-pip libgirepository1.0-dev
|
||||||
|
- invoke-lazy-sh:
|
||||||
|
subcommand: docdep
|
||||||
|
|
||||||
|
docs-publish-sh:
|
||||||
|
parameters:
|
||||||
|
push:
|
||||||
|
type: boolean
|
||||||
|
steps:
|
||||||
|
- checkout
|
||||||
|
- run:
|
||||||
|
command: |
|
||||||
|
git config --global user.email "zreplbot@cschwarz.com"
|
||||||
|
git config --global user.name "zrepl-github-io-ci"
|
||||||
|
|
||||||
|
# https://circleci.com/docs/2.0/add-ssh-key/#adding-multiple-keys-with-blank-hostnames
|
||||||
|
- run: ssh-add -D
|
||||||
|
# the default circleci ssh config only additional ssh keys for Host !github.com
|
||||||
|
- run:
|
||||||
|
command: |
|
||||||
|
cat > ~/.ssh/config \<<EOF
|
||||||
|
Host *
|
||||||
|
IdentityFile /home/circleci/.ssh/id_rsa_458e62c517f6c480e40452126ce47421
|
||||||
|
EOF
|
||||||
|
- add_ssh_keys:
|
||||||
|
fingerprints:
|
||||||
|
# deploy key for zrepl.github.io
|
||||||
|
- "45:8e:62:c5:17:f6:c4:80:e4:04:52:12:6c:e4:74:21"
|
||||||
|
|
||||||
|
# caller must install-docdep
|
||||||
|
- when:
|
||||||
|
condition: << parameters.push >>
|
||||||
|
steps:
|
||||||
|
- run: bash -x docs/publish.sh -c -a -P
|
||||||
|
- when:
|
||||||
|
condition:
|
||||||
|
not: << parameters.push >>
|
||||||
|
steps:
|
||||||
|
- run: bash -x docs/publish.sh -c -a
|
||||||
|
|
||||||
|
parameters:
|
||||||
|
do_ci:
|
||||||
|
type: boolean
|
||||||
|
default: true
|
||||||
|
|
||||||
|
do_release:
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
|
release_docker_baseimage_tag:
|
||||||
|
type: string
|
||||||
|
default: "1.21"
|
||||||
|
|
||||||
|
workflows:
|
||||||
|
version: 2
|
||||||
|
|
||||||
|
ci:
|
||||||
|
when: << pipeline.parameters.do_ci >>
|
||||||
|
jobs:
|
||||||
|
- quickcheck-docs
|
||||||
|
- quickcheck-go: &quickcheck-go-smoketest
|
||||||
|
name: quickcheck-go-amd64-linux-1.21
|
||||||
|
goversion: &latest-go-release "1.21"
|
||||||
|
goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
- test-go-on-latest-go-release:
|
||||||
|
goversion: *latest-go-release
|
||||||
|
- quickcheck-go:
|
||||||
|
requires:
|
||||||
|
- quickcheck-go-amd64-linux-1.21 #quickcheck-go-smoketest.name
|
||||||
|
matrix: &quickcheck-go-matrix
|
||||||
|
alias: quickcheck-go-matrix
|
||||||
|
parameters:
|
||||||
|
goversion: [*latest-go-release, "1.20"]
|
||||||
|
goos: ["linux", "freebsd"]
|
||||||
|
goarch: ["amd64", "arm64"]
|
||||||
|
exclude:
|
||||||
|
# don't re-do quickcheck-go-smoketest
|
||||||
|
- goversion: *latest-go-release
|
||||||
|
goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
- platformtest:
|
||||||
|
matrix:
|
||||||
|
parameters:
|
||||||
|
goversion: [*latest-go-release]
|
||||||
|
goos: ["linux"]
|
||||||
|
goarch: ["amd64"]
|
||||||
|
requires:
|
||||||
|
- quickcheck-go-<< matrix.goarch >>-<< matrix.goos >>-<< matrix.goversion >>
|
||||||
|
|
||||||
|
release:
|
||||||
|
when: << pipeline.parameters.do_release >>
|
||||||
|
jobs:
|
||||||
|
- release-build
|
||||||
|
- release-deb:
|
||||||
|
requires:
|
||||||
|
- release-build
|
||||||
|
- release-rpm:
|
||||||
|
requires:
|
||||||
|
- release-build
|
||||||
|
- release-upload:
|
||||||
|
requires:
|
||||||
|
- release-build
|
||||||
|
- release-deb
|
||||||
|
- release-rpm
|
||||||
|
|
||||||
|
publish-zrepl.github.io:
|
||||||
|
jobs:
|
||||||
|
- publish-zrepl-github-io:
|
||||||
|
filters:
|
||||||
|
branches:
|
||||||
|
only:
|
||||||
|
- stable
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quickcheck-docs:
|
||||||
|
docker:
|
||||||
|
- image: cimg/base:2023.09
|
||||||
|
steps:
|
||||||
|
- checkout
|
||||||
|
- install-docdep
|
||||||
|
# do the current docs build
|
||||||
|
- run: make docs
|
||||||
|
# does the publish.sh script still work?
|
||||||
|
- docs-publish-sh:
|
||||||
|
push: false
|
||||||
|
|
||||||
|
quickcheck-go:
|
||||||
|
parameters:
|
||||||
|
goversion:
|
||||||
|
type: string
|
||||||
|
goos:
|
||||||
|
type: string
|
||||||
|
goarch:
|
||||||
|
type: string
|
||||||
|
docker:
|
||||||
|
- image: cimg/go:<<parameters.goversion>>
|
||||||
|
environment:
|
||||||
|
GOOS: <<parameters.goos>>
|
||||||
|
GOARCH: <<parameters.goarch>>
|
||||||
|
|
||||||
|
steps:
|
||||||
- checkout
|
- checkout
|
||||||
|
|
||||||
- save_cache:
|
- go/load-cache:
|
||||||
key: source
|
key: quickcheck-<<parameters.goversion>>
|
||||||
paths:
|
- install-godep
|
||||||
- ".git"
|
- run: go mod download
|
||||||
|
- run: cd build && go mod download
|
||||||
# install deps
|
- go/save-cache:
|
||||||
- run: wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip
|
key: quickcheck-<<parameters.goversion>>
|
||||||
- run: echo "6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807 protoc-3.6.1-linux-x86_64.zip" | sha256sum -c
|
|
||||||
- run: sudo unzip -d /usr protoc-3.6.1-linux-x86_64.zip
|
|
||||||
- save_cache:
|
|
||||||
key: protobuf
|
|
||||||
paths:
|
|
||||||
- "/usr/include/google/protobuf"
|
|
||||||
|
|
||||||
- run: sudo apt install python3 python3-pip libgirepository1.0-dev
|
|
||||||
- run: ./lazy.sh devsetup
|
|
||||||
|
|
||||||
- run: make vendordeps
|
- run: make formatcheck
|
||||||
- save_cache:
|
- run: make generate-platform-test-list
|
||||||
key: vendor
|
- run: make zrepl-bin test-platform-bin
|
||||||
paths:
|
|
||||||
- "./vendor"
|
|
||||||
|
|
||||||
- run: make
|
|
||||||
- run: make vet
|
- run: make vet
|
||||||
- run: make test
|
- run: make lint
|
||||||
- run: make release
|
|
||||||
|
|
||||||
|
- run: rm -f artifacts/generate-platform-test-list
|
||||||
- store_artifacts:
|
- store_artifacts:
|
||||||
path: ./artifacts/release
|
path: artifacts
|
||||||
when: always
|
- persist_to_workspace:
|
||||||
|
root: .
|
||||||
|
paths: [.]
|
||||||
|
|
||||||
|
platformtest:
|
||||||
|
parameters:
|
||||||
|
goversion:
|
||||||
|
type: string
|
||||||
|
goos:
|
||||||
|
type: string
|
||||||
|
goarch:
|
||||||
|
type: string
|
||||||
|
machine:
|
||||||
|
image: ubuntu-2204:current
|
||||||
|
resource_class: medium
|
||||||
|
environment:
|
||||||
|
GOOS: <<parameters.goos>>
|
||||||
|
GOARCH: <<parameters.goarch>>
|
||||||
|
steps:
|
||||||
|
- attach_workspace:
|
||||||
|
at: .
|
||||||
|
- run: sudo apt-get update
|
||||||
|
- run: sudo apt-get install -y zfsutils-linux
|
||||||
|
- run: sudo zfs version
|
||||||
|
- run: sudo make test-platform GOOS="$GOOS" GOARCH="$GOARCH"
|
||||||
|
|
||||||
build-1.11:
|
test-go-on-latest-go-release:
|
||||||
<<: *build-latest
|
parameters:
|
||||||
|
goversion:
|
||||||
|
type: string
|
||||||
docker:
|
docker:
|
||||||
- image: circleci/golang:1.11
|
- image: cimg/go:<<parameters.goversion>>
|
||||||
build-1.12:
|
steps:
|
||||||
<<: *build-latest
|
- checkout
|
||||||
|
- go/load-cache:
|
||||||
|
key: make-test-go
|
||||||
|
- run: make test-go
|
||||||
|
- go/save-cache:
|
||||||
|
key: make-test-go
|
||||||
|
|
||||||
|
release-build:
|
||||||
|
machine:
|
||||||
|
image: ubuntu-2004:202201-02
|
||||||
|
steps:
|
||||||
|
- checkout
|
||||||
|
- run: make release-docker RELEASE_DOCKER_BASEIMAGE_TAG=<<pipeline.parameters.release_docker_baseimage_tag>>
|
||||||
|
- persist_to_workspace:
|
||||||
|
root: .
|
||||||
|
paths: [.]
|
||||||
|
release-deb:
|
||||||
|
machine:
|
||||||
|
image: ubuntu-2004:202201-02
|
||||||
|
steps:
|
||||||
|
- attach_workspace:
|
||||||
|
at: .
|
||||||
|
- run: make debs-docker
|
||||||
|
- persist_to_workspace:
|
||||||
|
root: .
|
||||||
|
paths:
|
||||||
|
- "artifacts/*.deb"
|
||||||
|
|
||||||
|
release-rpm:
|
||||||
|
machine:
|
||||||
|
image: ubuntu-2004:202201-02
|
||||||
|
steps:
|
||||||
|
- attach_workspace:
|
||||||
|
at: .
|
||||||
|
- run: make rpms-docker
|
||||||
|
- persist_to_workspace:
|
||||||
|
root: .
|
||||||
|
paths:
|
||||||
|
- "artifacts/*.rpm"
|
||||||
|
|
||||||
|
release-upload:
|
||||||
docker:
|
docker:
|
||||||
- image: circleci/golang:1.12
|
- image: cimg/base:2020.08
|
||||||
|
steps:
|
||||||
|
- attach_workspace:
|
||||||
|
at: .
|
||||||
|
- run: make wrapup-and-checksum
|
||||||
|
- store_artifacts:
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
publish-zrepl-github-io:
|
||||||
|
docker:
|
||||||
|
- image: cimg/base:2023.09
|
||||||
|
steps:
|
||||||
|
- checkout
|
||||||
|
- install-docdep
|
||||||
|
- docs-publish-sh:
|
||||||
|
push: true
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
import os
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
circle_token = os.environ.get('CIRCLE_TOKEN')
|
||||||
|
if not circle_token:
|
||||||
|
raise ValueError('CIRCLE_TOKEN environment variable not set')
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description='Download artifacts from CircleCI')
|
||||||
|
parser.add_argument('build_num', type=str, help='Build number')
|
||||||
|
parser.add_argument('dst', type=Path, help='Destination directory')
|
||||||
|
parser.add_argument('--prefix', type=str, default='', help='Filter for prefix')
|
||||||
|
parser.add_argument('--match', type=str, default='.*', help='Only include paths matching the given regex')
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
res = requests.get(
|
||||||
|
f"https://circleci.com/api/v1.1/project/github/zrepl/zrepl/{args.build_num}/artifacts",
|
||||||
|
headers={
|
||||||
|
"Circle-Token": circle_token,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
res.raise_for_status()
|
||||||
|
|
||||||
|
# https://circleci.com/docs/api/v1/index.html#artifacts-of-a-job
|
||||||
|
# [ {
|
||||||
|
# "path" : "raw-test-output/go-test-report.xml",
|
||||||
|
# "pretty_path" : "raw-test-output/go-test-report.xml",
|
||||||
|
# "node_index" : 0,
|
||||||
|
# "url" : "https://24-88881093-gh.circle-artifacts.com/0/raw-test-output/go-test-report.xml"
|
||||||
|
# }, {
|
||||||
|
# "path" : "raw-test-output/go-test.out",
|
||||||
|
# "pretty_path" : "raw-test-output/go-test.out",
|
||||||
|
# "node_index" : 0,
|
||||||
|
# "url" : "https://24-88881093-gh.circle-artifacts.com/0/raw-test-output/go-test.out"
|
||||||
|
# } ]
|
||||||
|
res = res.json()
|
||||||
|
|
||||||
|
for artifact in res:
|
||||||
|
if not artifact["pretty_path"].startswith(args.prefix):
|
||||||
|
continue
|
||||||
|
if not re.match(args.match, artifact["pretty_path"]):
|
||||||
|
continue
|
||||||
|
stripped = artifact["pretty_path"][len(args.prefix):]
|
||||||
|
print(f"Downloading {artifact['pretty_path']} to {args.dst / stripped}")
|
||||||
|
artifact_rel = Path(stripped)
|
||||||
|
artifact_dst = args.dst / artifact_rel
|
||||||
|
artifact_dst.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
res = requests.get(
|
||||||
|
artifact["url"],
|
||||||
|
headers={
|
||||||
|
"Circle-Token": circle_token,
|
||||||
|
},
|
||||||
|
stream=True,
|
||||||
|
)
|
||||||
|
res.raise_for_status()
|
||||||
|
|
||||||
|
total_size = int(res.headers.get("Content-Length", 0))
|
||||||
|
block_size = 128 * 1024
|
||||||
|
with open(artifact_dst, "wb") as f:
|
||||||
|
progress = 0
|
||||||
|
start_time = time.time()
|
||||||
|
for chunk in res.iter_content(chunk_size=block_size):
|
||||||
|
f.write(chunk)
|
||||||
|
progress += len(chunk)
|
||||||
|
percent = progress / total_size * 100
|
||||||
|
elapsed_time = time.time() - start_time
|
||||||
|
if elapsed_time >= 5:
|
||||||
|
print(f"Downloaded {progress}/{total_size} bytes ({percent:.2f}%)", end="\r")
|
||||||
|
start_time = time.time()
|
||||||
|
print(f"Downloaded {progress}/{total_size} bytes ({percent:.2f}%)")
|
||||||
|
print("Download complete!")
|
||||||
|
|
||||||
|
print("All files downloaded")
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
COMMIT="$1"
|
||||||
|
GO_VERSION="$2"
|
||||||
|
|
||||||
|
curl -v -X POST https://api.github.com/repos/zrepl/debian-binary-packaging/dispatches \
|
||||||
|
-H 'Accept: application/vnd.github.v3+json' \
|
||||||
|
-H "Authorization: token $GITHUB_ACCESS_TOKEN" \
|
||||||
|
--data '{"event_type": "push", "client_payload": { "zrepl_main_repo_commit": "'"$COMMIT"'", "go_version": "'"$GO_VERSION"'" }}'
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
github: problame
|
||||||
|
patreon: zrepl
|
||||||
|
liberapay: zrepl
|
||||||
|
custom: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R5QSXJVYHGX96
|
||||||
|
ko_fi: problame
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
linters:
|
||||||
|
enable:
|
||||||
|
- goimports
|
||||||
|
|
||||||
|
issues:
|
||||||
|
exclude-rules:
|
||||||
|
- path: _test\.go
|
||||||
|
linters:
|
||||||
|
- errcheck
|
||||||
|
# Disable staticcheck 'Empty body in an if or else branch' as it's useful
|
||||||
|
# to put a comment into an empty else-clause that explains why whatever
|
||||||
|
# is done in the if-caluse is not necessary if the condition is false.
|
||||||
|
- linters:
|
||||||
|
- staticcheck
|
||||||
|
text: "SA9003:"
|
||||||
|
|
||||||
-69
@@ -1,69 +0,0 @@
|
|||||||
dist: xenial
|
|
||||||
services:
|
|
||||||
- docker
|
|
||||||
|
|
||||||
env: # for allow_failures: https://docs.travis-ci.com/user/customizing-the-build/
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
|
|
||||||
- language: go
|
|
||||||
name: "Build in Docker (docs/installation.rst)"
|
|
||||||
script:
|
|
||||||
- sudo docker build -t zrepl_build -f build.Dockerfile .
|
|
||||||
- |
|
|
||||||
sudo docker run -it --rm \
|
|
||||||
-v "${PWD}:/go/src/github.com/zrepl/zrepl" \
|
|
||||||
--user "$(id -u):$(id -g)" \
|
|
||||||
zrepl_build make vendordeps release
|
|
||||||
|
|
||||||
- &zrepl_build_template
|
|
||||||
language: go
|
|
||||||
go_import_path: github.com/zrepl/zrepl
|
|
||||||
before_install:
|
|
||||||
- wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip
|
|
||||||
- echo "6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807 protoc-3.6.1-linux-x86_64.zip" | sha256sum -c
|
|
||||||
- sudo unzip -d /usr protoc-3.6.1-linux-x86_64.zip
|
|
||||||
- ./lazy.sh godep
|
|
||||||
- make vendordeps
|
|
||||||
script:
|
|
||||||
- make
|
|
||||||
- make vet
|
|
||||||
- make test
|
|
||||||
- make artifacts/zrepl-freebsd-amd64
|
|
||||||
- make artifacts/zrepl-linux-amd64
|
|
||||||
- make artifacts/zrepl-darwin-amd64
|
|
||||||
go:
|
|
||||||
- "1.11"
|
|
||||||
|
|
||||||
- <<: *zrepl_build_template
|
|
||||||
go:
|
|
||||||
- "1.12"
|
|
||||||
|
|
||||||
- <<: *zrepl_build_template
|
|
||||||
go:
|
|
||||||
- "master"
|
|
||||||
|
|
||||||
- &zrepl_docs_template
|
|
||||||
language: python
|
|
||||||
python:
|
|
||||||
- "3.4"
|
|
||||||
install:
|
|
||||||
- sudo apt-get install libgirepository1.0-dev
|
|
||||||
- pip install -r docs/requirements.txt
|
|
||||||
script:
|
|
||||||
- make docs
|
|
||||||
- <<: *zrepl_docs_template
|
|
||||||
python:
|
|
||||||
- "3.5"
|
|
||||||
- <<: *zrepl_docs_template
|
|
||||||
python:
|
|
||||||
- "3.6"
|
|
||||||
- <<: *zrepl_docs_template
|
|
||||||
python:
|
|
||||||
- "3.7"
|
|
||||||
|
|
||||||
|
|
||||||
allow_failures:
|
|
||||||
- <<: *zrepl_build_template
|
|
||||||
go:
|
|
||||||
- "master"
|
|
||||||
Generated
-477
@@ -1,477 +0,0 @@
|
|||||||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
|
||||||
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:8cf2cf1ab10480b5e0df950dac1517aaabde05d055d9d955652997ae4b9ecbbf"
|
|
||||||
name = "github.com/alvaroloes/enumer"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "6bcfe2edaac32ad71b88ce4cf92d34cd643e4ecb"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:c0bec5f9b98d0bc872ff5e834fac186b807b656683bd29cb82fb207a1513fabb"
|
|
||||||
name = "github.com/beorn7/perks"
|
|
||||||
packages = ["quantile"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "3a771d992973f24aa725d07868b467d1ddfceafb"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:56c130d885a4aacae1dd9c7b71cfe39912c7ebc1ff7d2b46083c8812996dc43b"
|
|
||||||
name = "github.com/davecgh/go-spew"
|
|
||||||
packages = ["spew"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "346938d642f2ec3594ed81d874461961cd0faa76"
|
|
||||||
version = "v1.1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:e988ed0ca0d81f4d28772760c02ee95084961311291bdfefc1b04617c178b722"
|
|
||||||
name = "github.com/fatih/color"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "5b77d2a35fb0ede96d138fc9a99f5c9b6aef11b4"
|
|
||||||
version = "v1.7.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:5d0a2385edf4ba44f3b7b76bc0436ceb8f62bf55aa5d540a9eb9ec6c58d86809"
|
|
||||||
name = "github.com/ftrvxmtrx/fd"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "c6d800382fff6dc1412f34269f71b7f83bd059ad"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:4416ad04caf950d004921268f777e418f8c328080ccf6a91e799f977dc128808"
|
|
||||||
name = "github.com/gdamore/encoding"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "b23993cbb6353f0e6aa98d0ee318a34728f628b9"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:d8088c614a5bffaf38a40c116226e7d230750bafb77942dca25eab779ceeaf1f"
|
|
||||||
name = "github.com/gdamore/tcell"
|
|
||||||
packages = [
|
|
||||||
".",
|
|
||||||
"termbox",
|
|
||||||
"terminfo",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "de7e78efa4a71b3f36c7154989c529dbdf9ae623"
|
|
||||||
version = "v1.1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:6a4a01d58b227c4b6b11111b9f172ec5c17682b82724e58e6daf3f19f4faccd8"
|
|
||||||
name = "github.com/go-logfmt/logfmt"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5"
|
|
||||||
version = "v0.3.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:3dd078fda7500c341bc26cfbc6c6a34614f295a2457149fc1045cab767cbcf18"
|
|
||||||
name = "github.com/golang/protobuf"
|
|
||||||
packages = [
|
|
||||||
"proto",
|
|
||||||
"protoc-gen-go",
|
|
||||||
"protoc-gen-go/descriptor",
|
|
||||||
"protoc-gen-go/generator",
|
|
||||||
"protoc-gen-go/generator/internal/remap",
|
|
||||||
"protoc-gen-go/grpc",
|
|
||||||
"protoc-gen-go/plugin",
|
|
||||||
"ptypes",
|
|
||||||
"ptypes/any",
|
|
||||||
"ptypes/duration",
|
|
||||||
"ptypes/timestamp",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
|
|
||||||
version = "v1.2.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:ad92aa49f34cbc3546063c7eb2cabb55ee2278b72842eda80e2a20a8a06a8d73"
|
|
||||||
name = "github.com/google/uuid"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "0cd6bf5da1e1c83f8b45653022c74f71af0538a4"
|
|
||||||
version = "v1.1.1"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:cb09475f771b9167fb9333629f5d6a7161572602ea040f1094602b0dc8709878"
|
|
||||||
name = "github.com/jinzhu/copier"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "db4671f3a9b8df855e993f7c94ec5ef1ffb0a23b"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:1ed9eeebdf24aadfbca57eb50e6455bd1d2474525e0f0d4454de8c8e9bc7ee9a"
|
|
||||||
name = "github.com/kr/logfmt"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:591a2778aa6e896980757ea87e659b3aa13d8c0e790310614028463a31c0998b"
|
|
||||||
name = "github.com/kr/pretty"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "cfb55aafdaf3ec08f0db22699ab822c50091b1c4"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:109e0a9b9e74c5c8adf94a2dc4dd4a9ca2a183d4d87ffecd4e62db69a5ede55a"
|
|
||||||
name = "github.com/kr/text"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "7cafcd837844e784b526369c9bce262804aebc60"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:863ba095ae0954100963826333bd1503c169424bb798d9ce800d9f6651f4c234"
|
|
||||||
name = "github.com/lucasb-eyer/go-colorful"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "345fbb3dbcdb252d9985ee899a84963c0fa24c82"
|
|
||||||
version = "v1.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:9ea83adf8e96d6304f394d40436f2eb44c1dc3250d223b74088cc253a6cd0a1c"
|
|
||||||
name = "github.com/mattn/go-colorable"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072"
|
|
||||||
version = "v0.0.9"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:78229b46ddb7434f881390029bd1af7661294af31f6802e0e1bedaad4ab0af3c"
|
|
||||||
name = "github.com/mattn/go-isatty"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
|
|
||||||
version = "v0.0.3"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:82b912465c1da0668582a7d1117339c278e786c2536b3c3623029a0c7141c2d0"
|
|
||||||
name = "github.com/mattn/go-runewidth"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "ce7b0b5c7b45a81508558cd1dba6bb1e4ddb51bb"
|
|
||||||
version = "v0.0.3"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:4c23ced97a470b17d9ffd788310502a077b9c1f60221a85563e49696276b4147"
|
|
||||||
name = "github.com/matttproud/golang_protobuf_extensions"
|
|
||||||
packages = ["pbutil"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "3247c84500bff8d9fb6d579d800f20b3e091582c"
|
|
||||||
version = "v1.0.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:4ff67dde814694496d7aa31be44b900f9717a10c8bc9136b13f49c8ef97f439a"
|
|
||||||
name = "github.com/montanaflynn/stats"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "63fbb2597b7a13043b453a4b819945badb8f8926"
|
|
||||||
version = "v0.5.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:f60ff065b58bd53e641112b38bbda9d2684deb828393c7ffb89c69a1ee301d17"
|
|
||||||
name = "github.com/pascaldekloe/name"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "0fd16699aae1833640fca52a937944c6f3b1d58c"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:7365acd48986e205ccb8652cc746f09c8b7876030d53710ea6ef7d0bd0dcd7ca"
|
|
||||||
name = "github.com/pkg/errors"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
|
|
||||||
version = "v0.8.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:1cbc6b98173422a756ae79e485952cb37a0a460c710541c75d3e9961c5a60782"
|
|
||||||
name = "github.com/pkg/profile"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "5b67d428864e92711fcbd2f8629456121a56d91f"
|
|
||||||
version = "v1.2.1"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:256484dbbcd271f9ecebc6795b2df8cad4c458dd0f5fd82a8c2fa0c29f233411"
|
|
||||||
name = "github.com/pmezard/go-difflib"
|
|
||||||
packages = ["difflib"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
|
|
||||||
version = "v1.0.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:fa72f780ae3b4820ed12cef7a034291ab10d83e2da4ab5ba81afa44d5bf3a529"
|
|
||||||
name = "github.com/problame/go-netssh"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "09d6bc45d284784cb3e5aaa1998513f37eb19cc6"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:ebf8ffdde9bdbf9c83e22121875c68c01d821776523546554b2a3ff6f72773ab"
|
|
||||||
name = "github.com/prometheus/client_golang"
|
|
||||||
packages = [
|
|
||||||
"prometheus",
|
|
||||||
"prometheus/promhttp",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "e11c6ff8170beca9d5fd8b938e71165eeec53ac6"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:60aca47f4eeeb972f1b9da7e7db51dee15ff6c59f7b401c1588b8e6771ba15ef"
|
|
||||||
name = "github.com/prometheus/client_model"
|
|
||||||
packages = ["go"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:af21ee3e0a8212f17bb317cd7237f9920bcb2641a291ac111f30f63b3cab817f"
|
|
||||||
name = "github.com/prometheus/common"
|
|
||||||
packages = [
|
|
||||||
"expfmt",
|
|
||||||
"internal/bitbucket.org/ww/goautoneg",
|
|
||||||
"model",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "d0f7cd64bda49e08b22ae8a730aa57aa0db125d6"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:61df0898746840afc7be5dc2c3eeec83022fab70df11ecee5b16c85e912cf5ed"
|
|
||||||
name = "github.com/prometheus/procfs"
|
|
||||||
packages = [
|
|
||||||
".",
|
|
||||||
"internal/util",
|
|
||||||
"nfs",
|
|
||||||
"xfs",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "8b1c2da0d56deffdbb9e48d4414b4e674bd8083e"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:3962f553b77bf6c03fc07cd687a22dd3b00fe11aa14d31194f5505f5bb65cdc8"
|
|
||||||
name = "github.com/sergi/go-diff"
|
|
||||||
packages = ["diffmatchpatch"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "1744e2970ca51c86172c8190fadad617561ed6e7"
|
|
||||||
version = "v1.0.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:146327ce93be37e68bd3ff8541090d96da8cb3adc9e35d57570e9170a29f6bf6"
|
|
||||||
name = "github.com/spf13/cobra"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "b78744579491c1ceeaaa3b40205e56b0591b93a3"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:261bc565833ef4f02121450d74eb88d5ae4bd74bfe5d0e862cddb8550ec35000"
|
|
||||||
name = "github.com/spf13/pflag"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66"
|
|
||||||
version = "v1.0.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:3926a4ec9a4ff1a072458451aa2d9b98acd059a45b38f7335d31e06c3d6a0159"
|
|
||||||
name = "github.com/stretchr/testify"
|
|
||||||
packages = [
|
|
||||||
"assert",
|
|
||||||
"require",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "69483b4bd14f5845b5a1e55bca19e954e827f1d0"
|
|
||||||
version = "v1.1.4"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:f80053a92d9ac874ad97d665d3005c1118ed66e9e88401361dc32defe6bef21c"
|
|
||||||
name = "github.com/theckman/goconstraint"
|
|
||||||
packages = ["go1.11/gte"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "93babf24513d0e8277635da8169fcc5a46ae3f6a"
|
|
||||||
version = "v1.11.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:529ed3f98838f69e13761788d0cc71b44e130058fab13bae2ce09f7a176bced4"
|
|
||||||
name = "github.com/yudai/gojsondiff"
|
|
||||||
packages = [
|
|
||||||
".",
|
|
||||||
"formatter",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "7b1b7adf999dab73a6eb02669c3d82dbb27a3dd6"
|
|
||||||
version = "1.0.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:9857bb2293f372b2181004d8b62179bbdb4ab0982ec6f762abe6cf2bfedaff85"
|
|
||||||
name = "github.com/yudai/golcs"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "ecda9a501e8220fae3b4b600c3db4b0ba22cfc68"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "v2"
|
|
||||||
digest = "1:6b8a6afafde7ed31cd0c577ba40d88ce39e8f1c5eb76d7836be7d5b74f1c534a"
|
|
||||||
name = "github.com/zrepl/yaml-config"
|
|
||||||
packages = ["."]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "08227ad854131f7dfcdfb12579fb73dd8a38a03a"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:ea539c13b066dac72a940b62f37600a20ab8e88057397c78f3197c1a48475425"
|
|
||||||
name = "golang.org/x/net"
|
|
||||||
packages = [
|
|
||||||
"context",
|
|
||||||
"http/httpguts",
|
|
||||||
"http2",
|
|
||||||
"http2/hpack",
|
|
||||||
"idna",
|
|
||||||
"internal/timeseries",
|
|
||||||
"trace",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "351d144fa1fc0bd934e2408202be0c29f25e35a0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:f358024b019f87eecaadcb098113a40852c94fe58ea670ef3c3e2d2c7bd93db1"
|
|
||||||
name = "golang.org/x/sys"
|
|
||||||
packages = ["unix"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "4ed8d59d0b35e1e29334a206d1b3f38b1e5dfb31"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:5acd3512b047305d49e8763eef7ba423901e85d5dd2fd1e71778a0ea8de10bd4"
|
|
||||||
name = "golang.org/x/text"
|
|
||||||
packages = [
|
|
||||||
"collate",
|
|
||||||
"collate/build",
|
|
||||||
"encoding",
|
|
||||||
"encoding/internal/identifier",
|
|
||||||
"internal/colltab",
|
|
||||||
"internal/gen",
|
|
||||||
"internal/tag",
|
|
||||||
"internal/triegen",
|
|
||||||
"internal/ucd",
|
|
||||||
"language",
|
|
||||||
"secure/bidirule",
|
|
||||||
"transform",
|
|
||||||
"unicode/bidi",
|
|
||||||
"unicode/cldr",
|
|
||||||
"unicode/norm",
|
|
||||||
"unicode/rangetable",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
|
|
||||||
version = "v0.3.0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:4cd780b2ee42c8eac9c02bfb6e6b52dcbaef770774458c8938f5cbfb73a7b6d3"
|
|
||||||
name = "golang.org/x/tools"
|
|
||||||
packages = ["cmd/stringer"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "d0ca3933b724e6be513276cc2edb34e10d667438"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
branch = "master"
|
|
||||||
digest = "1:5fc6c317675b746d0c641b29aa0aab5fcb403c0d07afdbf0de86b0d447a0502a"
|
|
||||||
name = "google.golang.org/genproto"
|
|
||||||
packages = ["googleapis/rpc/status"]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "bd91e49a0898e27abb88c339b432fa53d7497ac0"
|
|
||||||
|
|
||||||
[[projects]]
|
|
||||||
digest = "1:d141efe4aaad714e3059c340901aab3147b6253e58c85dafbcca3dd8b0e88ad6"
|
|
||||||
name = "google.golang.org/grpc"
|
|
||||||
packages = [
|
|
||||||
".",
|
|
||||||
"balancer",
|
|
||||||
"balancer/base",
|
|
||||||
"balancer/roundrobin",
|
|
||||||
"binarylog/grpc_binarylog_v1",
|
|
||||||
"codes",
|
|
||||||
"connectivity",
|
|
||||||
"credentials",
|
|
||||||
"credentials/internal",
|
|
||||||
"encoding",
|
|
||||||
"encoding/proto",
|
|
||||||
"grpclog",
|
|
||||||
"internal",
|
|
||||||
"internal/backoff",
|
|
||||||
"internal/binarylog",
|
|
||||||
"internal/channelz",
|
|
||||||
"internal/envconfig",
|
|
||||||
"internal/grpcrand",
|
|
||||||
"internal/grpcsync",
|
|
||||||
"internal/syscall",
|
|
||||||
"internal/transport",
|
|
||||||
"keepalive",
|
|
||||||
"metadata",
|
|
||||||
"naming",
|
|
||||||
"peer",
|
|
||||||
"resolver",
|
|
||||||
"resolver/dns",
|
|
||||||
"resolver/passthrough",
|
|
||||||
"stats",
|
|
||||||
"status",
|
|
||||||
"tap",
|
|
||||||
]
|
|
||||||
pruneopts = ""
|
|
||||||
revision = "df014850f6dee74ba2fc94874043a9f3f75fbfd8"
|
|
||||||
version = "v1.17.0"
|
|
||||||
|
|
||||||
[solve-meta]
|
|
||||||
analyzer-name = "dep"
|
|
||||||
analyzer-version = 1
|
|
||||||
input-imports = [
|
|
||||||
"github.com/alvaroloes/enumer",
|
|
||||||
"github.com/fatih/color",
|
|
||||||
"github.com/gdamore/tcell/termbox",
|
|
||||||
"github.com/go-logfmt/logfmt",
|
|
||||||
"github.com/golang/protobuf/proto",
|
|
||||||
"github.com/golang/protobuf/protoc-gen-go",
|
|
||||||
"github.com/google/uuid",
|
|
||||||
"github.com/jinzhu/copier",
|
|
||||||
"github.com/kr/pretty",
|
|
||||||
"github.com/mattn/go-isatty",
|
|
||||||
"github.com/montanaflynn/stats",
|
|
||||||
"github.com/pkg/errors",
|
|
||||||
"github.com/pkg/profile",
|
|
||||||
"github.com/problame/go-netssh",
|
|
||||||
"github.com/prometheus/client_golang/prometheus",
|
|
||||||
"github.com/prometheus/client_golang/prometheus/promhttp",
|
|
||||||
"github.com/spf13/cobra",
|
|
||||||
"github.com/spf13/pflag",
|
|
||||||
"github.com/stretchr/testify/assert",
|
|
||||||
"github.com/stretchr/testify/require",
|
|
||||||
"github.com/yudai/gojsondiff",
|
|
||||||
"github.com/yudai/gojsondiff/formatter",
|
|
||||||
"github.com/zrepl/yaml-config",
|
|
||||||
"golang.org/x/net/context",
|
|
||||||
"golang.org/x/sys/unix",
|
|
||||||
"golang.org/x/tools/cmd/stringer",
|
|
||||||
"google.golang.org/grpc",
|
|
||||||
"google.golang.org/grpc/codes",
|
|
||||||
"google.golang.org/grpc/credentials",
|
|
||||||
"google.golang.org/grpc/keepalive",
|
|
||||||
"google.golang.org/grpc/peer",
|
|
||||||
"google.golang.org/grpc/status",
|
|
||||||
]
|
|
||||||
solver-name = "gps-cdcl"
|
|
||||||
solver-version = 1
|
|
||||||
-65
@@ -1,65 +0,0 @@
|
|||||||
ignored = [
|
|
||||||
"github.com/inconshreveable/mousetrap",
|
|
||||||
]
|
|
||||||
|
|
||||||
required = [
|
|
||||||
"golang.org/x/tools/cmd/stringer",
|
|
||||||
"github.com/alvaroloes/enumer",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
branch = "master"
|
|
||||||
name = "github.com/jinzhu/copier"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
branch = "master"
|
|
||||||
name = "github.com/kr/pretty"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/pkg/errors"
|
|
||||||
version = "0.8.0"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
branch = "master"
|
|
||||||
name = "github.com/spf13/cobra"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/stretchr/testify"
|
|
||||||
version = "1.1.4"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
branch = "v2"
|
|
||||||
name = "github.com/zrepl/yaml-config"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/go-logfmt/logfmt"
|
|
||||||
version = "*"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/problame/go-netssh"
|
|
||||||
branch = "master"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/prometheus/client_golang"
|
|
||||||
branch = "master"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/golang/protobuf"
|
|
||||||
version = "1"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/fatih/color"
|
|
||||||
version = "1.7.0"
|
|
||||||
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "github.com/gdamore/tcell"
|
|
||||||
version = "1.0.0"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
name = "google.golang.org/grpc"
|
|
||||||
version = "1"
|
|
||||||
|
|
||||||
[[constraint]]
|
|
||||||
version = "1.1.0"
|
|
||||||
name = "github.com/google/uuid"
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
.PHONY: generate build test vet cover release docs docs-clean clean vendordeps
|
.PHONY: generate build test vet cover release docs docs-clean clean format lint platformtest
|
||||||
.DEFAULT_GOAL := build
|
.PHONY: release release-noarch
|
||||||
|
.DEFAULT_GOAL := zrepl-bin
|
||||||
|
|
||||||
ARTIFACTDIR := artifacts
|
ARTIFACTDIR := artifacts
|
||||||
|
|
||||||
@@ -12,87 +13,352 @@ ifndef _ZREPL_VERSION
|
|||||||
$(error cannot infer variable ZREPL_VERSION using git and variable is not overriden by make invocation)
|
$(error cannot infer variable ZREPL_VERSION using git and variable is not overriden by make invocation)
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
|
ZREPL_PACKAGE_RELEASE := 1
|
||||||
|
|
||||||
|
GO := go
|
||||||
|
GOOS ?= $(shell bash -c 'source <($(GO) env) && echo "$$GOOS"')
|
||||||
|
GOARCH ?= $(shell bash -c 'source <($(GO) env) && echo "$$GOARCH"')
|
||||||
|
GOARM ?= $(shell bash -c 'source <($(GO) env) && echo "$$GOARM"')
|
||||||
|
GOHOSTOS ?= $(shell bash -c 'source <($(GO) env) && echo "$$GOHOSTOS"')
|
||||||
|
GOHOSTARCH ?= $(shell bash -c 'source <($(GO) env) && echo "$$GOHOSTARCH"')
|
||||||
|
GO_ENV_VARS := GO111MODULE=on CGO_ENABLED=0
|
||||||
GO_LDFLAGS := "-X github.com/zrepl/zrepl/version.zreplVersion=$(_ZREPL_VERSION)"
|
GO_LDFLAGS := "-X github.com/zrepl/zrepl/version.zreplVersion=$(_ZREPL_VERSION)"
|
||||||
|
GO_MOD_READONLY := -mod=readonly
|
||||||
|
GO_EXTRA_BUILDFLAGS :=
|
||||||
|
GO_BUILDFLAGS := $(GO_MOD_READONLY) $(GO_EXTRA_BUILDFLAGS)
|
||||||
|
GO_BUILD := $(GO_ENV_VARS) $(GO) build $(GO_BUILDFLAGS) -ldflags $(GO_LDFLAGS)
|
||||||
|
GOLANGCI_LINT := golangci-lint
|
||||||
|
GOCOVMERGE := gocovmerge
|
||||||
|
RELEASE_DOCKER_BASEIMAGE_TAG ?= 1.21
|
||||||
|
RELEASE_DOCKER_BASEIMAGE ?= golang:$(RELEASE_DOCKER_BASEIMAGE_TAG)
|
||||||
|
|
||||||
GO_BUILD := go build -ldflags $(GO_LDFLAGS)
|
ifneq ($(GOARM),)
|
||||||
|
ZREPL_TARGET_TUPLE := $(GOOS)-$(GOARCH)v$(GOARM)
|
||||||
|
else
|
||||||
|
ZREPL_TARGET_TUPLE := $(GOOS)-$(GOARCH)
|
||||||
|
endif
|
||||||
|
|
||||||
RELEASE_BINS := $(ARTIFACTDIR)/zrepl-freebsd-amd64
|
.PHONY: printvars
|
||||||
RELEASE_BINS += $(ARTIFACTDIR)/zrepl-linux-amd64
|
printvars:
|
||||||
RELEASE_BINS += $(ARTIFACTDIR)/zrepl-darwin-amd64
|
@echo GOOS=$(GOOS)
|
||||||
|
@echo GOARCH=$(GOARCH)
|
||||||
RELEASE_NOARCH := $(ARTIFACTDIR)/zrepl-noarch.tar
|
@echo GOARM=$(GOARM)
|
||||||
THIS_PLATFORM_RELEASE_BIN := $(shell bash -c 'source <(go env) && echo "zrepl-$${GOOS}-$${GOARCH}"' )
|
|
||||||
|
|
||||||
vendordeps:
|
|
||||||
dep ensure -v -vendor-only
|
|
||||||
|
|
||||||
generate: #not part of the build, must do that manually
|
|
||||||
protoc -I=replication/logic/pdu --go_out=plugins=grpc:replication/logic/pdu replication/logic/pdu/pdu.proto
|
|
||||||
go generate -x ./...
|
|
||||||
|
|
||||||
build:
|
|
||||||
@echo "INFO: In case of missing dependencies, run 'make vendordeps'"
|
|
||||||
$(GO_BUILD) -o "$(ARTIFACTDIR)/zrepl"
|
|
||||||
|
|
||||||
test:
|
|
||||||
go test ./...
|
|
||||||
|
|
||||||
vet:
|
|
||||||
# for each supported platform to cover conditional compilation
|
|
||||||
GOOS=linux go vet ./...
|
|
||||||
GOOS=darwin go vet ./...
|
|
||||||
GOOS=freebsd go vet ./...
|
|
||||||
|
|
||||||
$(ARTIFACTDIR):
|
|
||||||
mkdir -p "$@"
|
|
||||||
|
|
||||||
$(ARTIFACTDIR)/docs: $(ARTIFACTDIR)
|
|
||||||
mkdir -p "$@"
|
|
||||||
|
|
||||||
$(ARTIFACTDIR)/bash_completion: $(RELEASE_BINS)
|
|
||||||
artifacts/$(THIS_PLATFORM_RELEASE_BIN) bashcomp "$@"
|
|
||||||
|
|
||||||
$(ARTIFACTDIR)/go_version.txt:
|
|
||||||
go version > $@
|
|
||||||
|
|
||||||
docs: $(ARTIFACTDIR)/docs
|
|
||||||
make -C docs \
|
|
||||||
html \
|
|
||||||
BUILDDIR=../artifacts/docs \
|
|
||||||
|
|
||||||
docs-clean:
|
|
||||||
make -C docs \
|
|
||||||
clean \
|
|
||||||
BUILDDIR=../artifacts/docs
|
|
||||||
|
|
||||||
|
|
||||||
.PHONY: $(RELEASE_BINS)
|
##################### PRODUCING A RELEASE #############
|
||||||
# TODO: two wildcards possible
|
.PHONY: release wrapup-and-checksum check-git-clean sign clean
|
||||||
$(RELEASE_BINS): $(ARTIFACTDIR)/zrepl-%-amd64: generate $(ARTIFACTDIR) vet test
|
|
||||||
@echo "INFO: In case of missing dependencies, run 'make vendordeps'"
|
|
||||||
GOOS=$* GOARCH=amd64 $(GO_BUILD) -o "$(ARTIFACTDIR)/zrepl-$*-amd64"
|
|
||||||
|
|
||||||
$(RELEASE_NOARCH): docs $(ARTIFACTDIR)/bash_completion $(ARTIFACTDIR)/go_version.txt
|
release: clean
|
||||||
|
# no cross-platform support for target test
|
||||||
|
$(MAKE) test-go
|
||||||
|
$(MAKE) _run_make_foreach_target_tuple RUN_MAKE_FOREACH_TARGET_TUPLE_ARG="vet"
|
||||||
|
$(MAKE) _run_make_foreach_target_tuple RUN_MAKE_FOREACH_TARGET_TUPLE_ARG="lint"
|
||||||
|
$(MAKE) _run_make_foreach_target_tuple RUN_MAKE_FOREACH_TARGET_TUPLE_ARG="zrepl-bin"
|
||||||
|
$(MAKE) _run_make_foreach_target_tuple RUN_MAKE_FOREACH_TARGET_TUPLE_ARG="test-platform-bin"
|
||||||
|
$(MAKE) noarch
|
||||||
|
|
||||||
|
release-docker: $(ARTIFACTDIR)
|
||||||
|
sed 's/FROM.*!SUBSTITUTED_BY_MAKEFILE/FROM $(RELEASE_DOCKER_BASEIMAGE)/' build.Dockerfile > artifacts/release-docker.Dockerfile
|
||||||
|
docker build -t zrepl_release --pull -f artifacts/release-docker.Dockerfile .
|
||||||
|
docker run --rm -i -v $(CURDIR):/src -u $$(id -u):$$(id -g) \
|
||||||
|
zrepl_release \
|
||||||
|
make release \
|
||||||
|
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) \
|
||||||
|
ZREPL_VERSION=$(ZREPL_VERSION) ZREPL_PACKAGE_RELEASE=$(ZREPL_PACKAGE_RELEASE)
|
||||||
|
|
||||||
|
debs-docker:
|
||||||
|
$(MAKE) _debs_or_rpms_docker _DEB_OR_RPM=deb
|
||||||
|
rpms-docker:
|
||||||
|
$(MAKE) _debs_or_rpms_docker _DEB_OR_RPM=rpm
|
||||||
|
_debs_or_rpms_docker: # artifacts/_zrepl.zsh_completion artifacts/bash_completion docs zrepl-bin
|
||||||
|
$(MAKE) $(_DEB_OR_RPM)-docker GOOS=linux GOARCH=amd64
|
||||||
|
$(MAKE) $(_DEB_OR_RPM)-docker GOOS=linux GOARCH=arm64
|
||||||
|
$(MAKE) $(_DEB_OR_RPM)-docker GOOS=linux GOARCH=arm GOARM=7
|
||||||
|
$(MAKE) $(_DEB_OR_RPM)-docker GOOS=linux GOARCH=386
|
||||||
|
|
||||||
|
rpm: $(ARTIFACTDIR) # artifacts/_zrepl.zsh_completion artifacts/bash_completion docs zrepl-bin
|
||||||
|
$(eval _ZREPL_RPM_VERSION := $(subst -,.,$(_ZREPL_VERSION)))
|
||||||
|
$(eval _ZREPL_RPM_TOPDIR_ABS := $(CURDIR)/$(ARTIFACTDIR)/rpmbuild)
|
||||||
|
rm -rf "$(_ZREPL_RPM_TOPDIR_ABS)"
|
||||||
|
mkdir "$(_ZREPL_RPM_TOPDIR_ABS)"
|
||||||
|
for d in BUILD BUILDROOT RPMS SOURCES SPECS SRPMS; do \
|
||||||
|
mkdir -p "$(_ZREPL_RPM_TOPDIR_ABS)/$$d"; \
|
||||||
|
done
|
||||||
|
sed \
|
||||||
|
-e "s/^Version:.*/Version: $(_ZREPL_RPM_VERSION)/g" \
|
||||||
|
-e "s/^Release:.*/Release: $(ZREPL_PACKAGE_RELEASE)/g" \
|
||||||
|
packaging/rpm/zrepl.spec \
|
||||||
|
> $(_ZREPL_RPM_TOPDIR_ABS)/SPECS/zrepl.spec
|
||||||
|
|
||||||
|
# see /usr/lib/rpm/platform
|
||||||
|
ifeq ($(GOARCH),amd64)
|
||||||
|
$(eval _ZREPL_RPMBUILD_TARGET := x86_64)
|
||||||
|
else ifeq ($(GOARCH), 386)
|
||||||
|
$(eval _ZREPL_RPMBUILD_TARGET := i386)
|
||||||
|
else ifeq ($(GOARCH), arm64)
|
||||||
|
$(eval _ZREPL_RPMBUILD_TARGET := aarch64)
|
||||||
|
else ifeq ($(GOARCH), arm)
|
||||||
|
$(eval _ZREPL_RPMBUILD_TARGET := armv7hl)
|
||||||
|
else
|
||||||
|
$(eval _ZREPL_RPMBUILD_TARGET := $(GOARCH))
|
||||||
|
endif
|
||||||
|
rpmbuild \
|
||||||
|
--build-in-place \
|
||||||
|
--define "_sourcedir $(CURDIR)" \
|
||||||
|
--define "_topdir $(_ZREPL_RPM_TOPDIR_ABS)" \
|
||||||
|
--define "_zrepl_binary_filename zrepl-$(ZREPL_TARGET_TUPLE)" \
|
||||||
|
--target $(_ZREPL_RPMBUILD_TARGET) \
|
||||||
|
-bb "$(_ZREPL_RPM_TOPDIR_ABS)"/SPECS/zrepl.spec
|
||||||
|
cp "$(_ZREPL_RPM_TOPDIR_ABS)"/RPMS/$(_ZREPL_RPMBUILD_TARGET)/zrepl-$(_ZREPL_RPM_VERSION)*.rpm $(ARTIFACTDIR)/
|
||||||
|
|
||||||
|
rpm-docker:
|
||||||
|
docker build -t zrepl_rpm_pkg --pull -f packaging/rpm/Dockerfile .
|
||||||
|
docker run --rm -i -v $(CURDIR):/build/src -u $$(id -u):$$(id -g) \
|
||||||
|
zrepl_rpm_pkg \
|
||||||
|
make rpm \
|
||||||
|
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) \
|
||||||
|
ZREPL_VERSION=$(ZREPL_VERSION) ZREPL_PACKAGE_RELEASE=$(ZREPL_PACKAGE_RELEASE)
|
||||||
|
|
||||||
|
|
||||||
|
deb: $(ARTIFACTDIR) # artifacts/_zrepl.zsh_completion artifacts/bash_completion docs zrepl-bin
|
||||||
|
|
||||||
|
cp packaging/deb/debian/changelog.template packaging/deb/debian/changelog
|
||||||
|
sed -i 's/DATE_DASH_R_OUTPUT/$(shell date -R)/' packaging/deb/debian/changelog
|
||||||
|
VERSION="$(subst -,.,$(_ZREPL_VERSION))-$(ZREPL_PACKAGE_RELEASE)"; \
|
||||||
|
export VERSION="$${VERSION#v}"; \
|
||||||
|
sed -i 's/VERSION/'"$$VERSION"'/' packaging/deb/debian/changelog
|
||||||
|
|
||||||
|
ifeq ($(GOARCH), arm)
|
||||||
|
$(eval DEB_HOST_ARCH := armhf)
|
||||||
|
else ifeq ($(GOARCH), 386)
|
||||||
|
$(eval DEB_HOST_ARCH := i386)
|
||||||
|
else
|
||||||
|
$(eval DEB_HOST_ARCH := $(GOARCH))
|
||||||
|
endif
|
||||||
|
|
||||||
|
export ZREPL_DPKG_ZREPL_BINARY_FILENAME=zrepl-$(ZREPL_TARGET_TUPLE); \
|
||||||
|
dpkg-buildpackage -b --no-sign --host-arch $(DEB_HOST_ARCH)
|
||||||
|
cp ../*.deb artifacts/
|
||||||
|
|
||||||
|
deb-docker:
|
||||||
|
docker build -t zrepl_debian_pkg --pull -f packaging/deb/Dockerfile .
|
||||||
|
# Use a small open file limit to make fakeroot work. If we don't
|
||||||
|
# specify it, docker daemon will use its file limit. I don't know
|
||||||
|
# what changed (Docker, its systemd service, its Go version). But I
|
||||||
|
# observed fakeroot iterating close(i) up to i > 1000000, which costs
|
||||||
|
# a good amount of CPU time and makes the build slow.
|
||||||
|
docker run --rm -i -v $(CURDIR):/build/src -u $$(id -u):$$(id -g) \
|
||||||
|
--ulimit nofile=1024:1024 \
|
||||||
|
zrepl_debian_pkg \
|
||||||
|
make deb \
|
||||||
|
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) \
|
||||||
|
ZREPL_VERSION=$(ZREPL_VERSION) ZREPL_PACKAGE_RELEASE=$(ZREPL_PACKAGE_RELEASE)
|
||||||
|
|
||||||
|
# expects `release`, `deb` & `rpm` targets to have run before
|
||||||
|
NOARCH_TARBALL := $(ARTIFACTDIR)/zrepl-noarch.tar
|
||||||
|
wrapup-and-checksum:
|
||||||
|
rm -f $(NOARCH_TARBALL)
|
||||||
tar --mtime='1970-01-01' --sort=name \
|
tar --mtime='1970-01-01' --sort=name \
|
||||||
--transform 's/$(ARTIFACTDIR)/zrepl-$(_ZREPL_VERSION)-noarch/' \
|
--transform 's/$(ARTIFACTDIR)/zrepl-$(_ZREPL_VERSION)-noarch/' \
|
||||||
-acf $@ \
|
--transform 's#dist#zrepl-$(_ZREPL_VERSION)-noarch/dist#' \
|
||||||
|
--transform 's#config/samples#zrepl-$(_ZREPL_VERSION)-noarch/config#' \
|
||||||
|
-acf $(NOARCH_TARBALL) \
|
||||||
$(ARTIFACTDIR)/docs/html \
|
$(ARTIFACTDIR)/docs/html \
|
||||||
$(ARTIFACTDIR)/bash_completion \
|
$(ARTIFACTDIR)/bash_completion \
|
||||||
$(ARTIFACTDIR)/go_version.txt
|
$(ARTIFACTDIR)/_zrepl.zsh_completion \
|
||||||
|
$(ARTIFACTDIR)/go_env.txt \
|
||||||
release: $(RELEASE_BINS) $(RELEASE_NOARCH)
|
dist \
|
||||||
|
config/samples
|
||||||
rm -rf "$(ARTIFACTDIR)/release"
|
rm -rf "$(ARTIFACTDIR)/release"
|
||||||
mkdir -p "$(ARTIFACTDIR)/release"
|
mkdir -p "$(ARTIFACTDIR)/release"
|
||||||
cp $^ "$(ARTIFACTDIR)/release"
|
cp -l $(ARTIFACTDIR)/zrepl* \
|
||||||
|
$(ARTIFACTDIR)/platformtest-* \
|
||||||
|
"$(ARTIFACTDIR)/release"
|
||||||
cd "$(ARTIFACTDIR)/release" && sha512sum $$(ls | sort) > sha512sum.txt
|
cd "$(ARTIFACTDIR)/release" && sha512sum $$(ls | sort) > sha512sum.txt
|
||||||
|
|
||||||
|
check-git-clean:
|
||||||
@# note that we use ZREPL_VERSION and not _ZREPL_VERSION because we want to detect the override
|
@# note that we use ZREPL_VERSION and not _ZREPL_VERSION because we want to detect the override
|
||||||
@if git describe --always --dirty 2>/dev/null | grep dirty >/dev/null; then \
|
@if git describe --always --dirty 2>/dev/null | grep dirty >/dev/null; then \
|
||||||
echo '[INFO] either git reports checkout is dirty or git is not installed or this is not a git checkout'; \
|
echo '[INFO] either git reports checkout is dirty or git is not installed or this is not a git checkout'; \
|
||||||
if [ "$(ZREPL_VERSION)" = "" ]; then \
|
if [ "$(ZREPL_VERSION)" = "" ]; then \
|
||||||
echo '[WARN] git checkout is dirty and make variable ZREPL_VERSION was not used to override'; \
|
echo '[WARN] git checkout is dirty and make variable ZREPL_VERSION was not used to override'; \
|
||||||
|
git status; \
|
||||||
|
echo "git diff:"; \
|
||||||
|
git diff | cat; \
|
||||||
exit 1; \
|
exit 1; \
|
||||||
fi; \
|
fi; \
|
||||||
fi;
|
fi;
|
||||||
|
|
||||||
|
tag-release:
|
||||||
|
test -n "$(ZREPL_TAG_VERSION)" || exit 1
|
||||||
|
git tag -u '328A6627FA98061D!' -m "$(ZREPL_TAG_VERSION)" "$(ZREPL_TAG_VERSION)"
|
||||||
|
|
||||||
|
sign:
|
||||||
|
gpg -u '328A6627FA98061D!' \
|
||||||
|
--armor \
|
||||||
|
--detach-sign $(ARTIFACTDIR)/release/sha512sum.txt
|
||||||
|
|
||||||
clean: docs-clean
|
clean: docs-clean
|
||||||
rm -rf "$(ARTIFACTDIR)"
|
rm -rf "$(ARTIFACTDIR)"
|
||||||
|
|
||||||
|
download-circleci-release:
|
||||||
|
rm -rf "$(ARTIFACTDIR)"
|
||||||
|
mkdir -p "$(ARTIFACTDIR)/release"
|
||||||
|
python3 .circleci/download_artifacts.py --prefix 'artifacts/release/' "$(BUILD_NUM)" "$(ARTIFACTDIR)/release"
|
||||||
|
|
||||||
|
##################### MULTI-ARCH HELPERS #####################
|
||||||
|
|
||||||
|
_run_make_foreach_target_tuple:
|
||||||
|
if [ "$(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG)" = "" ]; then \
|
||||||
|
echo "RUN_MAKE_FOREACH_TARGET_TUPLE_ARG must be set"; \
|
||||||
|
exit 1; \
|
||||||
|
fi
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=freebsd GOARCH=amd64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=freebsd GOARCH=386
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=freebsd GOARCH=arm GOARM=7
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=freebsd GOARCH=arm64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=linux GOARCH=amd64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=linux GOARCH=arm64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=linux GOARCH=arm GOARM=7
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=linux GOARCH=386
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=darwin GOARCH=amd64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=solaris GOARCH=amd64
|
||||||
|
$(MAKE) $(RUN_MAKE_FOREACH_TARGET_TUPLE_ARG) GOOS=illumos GOARCH=amd64
|
||||||
|
|
||||||
|
##################### REGULAR TARGETS #####################
|
||||||
|
.PHONY: lint test-go test-platform cover-merge cover-html vet zrepl-bin test-platform-bin generate-platform-test-list
|
||||||
|
|
||||||
|
lint:
|
||||||
|
$(GO_ENV_VARS) $(GOLANGCI_LINT) run ./...
|
||||||
|
|
||||||
|
vet:
|
||||||
|
$(GO_ENV_VARS) $(GO) vet $(GO_BUILDFLAGS) ./...
|
||||||
|
|
||||||
|
test-go: $(ARTIFACTDIR)
|
||||||
|
rm -f "$(ARTIFACTDIR)/gotest.cover"
|
||||||
|
ifeq ($(COVER),1)
|
||||||
|
$(GO_ENV_VARS) $(GO) test $(GO_BUILDFLAGS) \
|
||||||
|
-coverpkg github.com/zrepl/zrepl/... \
|
||||||
|
-covermode atomic \
|
||||||
|
-coverprofile "$(ARTIFACTDIR)/gotest.cover" \
|
||||||
|
./...
|
||||||
|
else
|
||||||
|
$(GO_ENV_VARS) $(GO) test $(GO_BUILDFLAGS) \
|
||||||
|
./...
|
||||||
|
endif
|
||||||
|
|
||||||
|
zrepl-bin:
|
||||||
|
$(GO_BUILD) -o "$(ARTIFACTDIR)/zrepl-$(ZREPL_TARGET_TUPLE)"
|
||||||
|
|
||||||
|
generate-platform-test-list:
|
||||||
|
$(GO_BUILD) -o $(ARTIFACTDIR)/generate-platform-test-list ./platformtest/tests/gen
|
||||||
|
|
||||||
|
COVER_PLATFORM_BIN_PATH := $(ARTIFACTDIR)/platformtest-cover-$(ZREPL_TARGET_TUPLE)
|
||||||
|
cover-platform-bin:
|
||||||
|
$(GO_ENV_VARS) $(GO) test $(GO_BUILDFLAGS) \
|
||||||
|
-c -o "$(COVER_PLATFORM_BIN_PATH)" \
|
||||||
|
-covermode=atomic -cover -coverpkg github.com/zrepl/zrepl/... \
|
||||||
|
./platformtest/harness
|
||||||
|
cover-platform:
|
||||||
|
# do not track dependency on cover-platform-bin to allow build of binary outside of test VM
|
||||||
|
export _TEST_PLATFORM_CMD="$(COVER_PLATFORM_BIN_PATH) \
|
||||||
|
-test.coverprofile \"$(ARTIFACTDIR)/platformtest.cover\" \
|
||||||
|
-test.v \
|
||||||
|
__DEVEL--i-heard-you-like-tests"; \
|
||||||
|
$(MAKE) _test-or-cover-platform-impl
|
||||||
|
|
||||||
|
TEST_PLATFORM_BIN_PATH := $(ARTIFACTDIR)/platformtest-$(ZREPL_TARGET_TUPLE)
|
||||||
|
test-platform-bin:
|
||||||
|
$(GO_BUILD) -o "$(TEST_PLATFORM_BIN_PATH)" ./platformtest/harness
|
||||||
|
test-platform:
|
||||||
|
export _TEST_PLATFORM_CMD="\"$(TEST_PLATFORM_BIN_PATH)\""; \
|
||||||
|
$(MAKE) _test-or-cover-platform-impl
|
||||||
|
|
||||||
|
ZREPL_PLATFORMTEST_POOLNAME := zreplplatformtest
|
||||||
|
ZREPL_PLATFORMTEST_IMAGEPATH := /tmp/zreplplatformtest.pool.img
|
||||||
|
ZREPL_PLATFORMTEST_MOUNTPOINT := /tmp/zreplplatformtest.pool
|
||||||
|
ZREPL_PLATFORMTEST_ZFS_LOG := /tmp/zreplplatformtest.zfs.log
|
||||||
|
# ZREPL_PLATFORMTEST_STOP_AND_KEEP := -failure.stop-and-keep-pool
|
||||||
|
ZREPL_PLATFORMTEST_ARGS :=
|
||||||
|
_test-or-cover-platform-impl: $(ARTIFACTDIR)
|
||||||
|
ifndef _TEST_PLATFORM_CMD
|
||||||
|
$(error _TEST_PLATFORM_CMD is undefined, caller 'cover-platform' or 'test-platform' should have defined it)
|
||||||
|
endif
|
||||||
|
rm -f "$(ZREPL_PLATFORMTEST_ZFS_LOG)"
|
||||||
|
rm -f "$(ARTIFACTDIR)/platformtest.cover"
|
||||||
|
platformtest/logmockzfs/logzfsenv "$(ZREPL_PLATFORMTEST_ZFS_LOG)" `which zfs` \
|
||||||
|
$(_TEST_PLATFORM_CMD) \
|
||||||
|
-poolname "$(ZREPL_PLATFORMTEST_POOLNAME)" \
|
||||||
|
-imagepath "$(ZREPL_PLATFORMTEST_IMAGEPATH)" \
|
||||||
|
-mountpoint "$(ZREPL_PLATFORMTEST_MOUNTPOINT)" \
|
||||||
|
$(ZREPL_PLATFORMTEST_STOP_AND_KEEP) \
|
||||||
|
$(ZREPL_PLATFORMTEST_ARGS)
|
||||||
|
|
||||||
|
cover-merge: $(ARTIFACTDIR)
|
||||||
|
$(GOCOVMERGE) $(ARTIFACTDIR)/platformtest.cover $(ARTIFACTDIR)/gotest.cover > $(ARTIFACTDIR)/merged.cover
|
||||||
|
cover-html: cover-merge
|
||||||
|
$(GO) tool cover -html "$(ARTIFACTDIR)/merged.cover" -o "$(ARTIFACTDIR)/merged.cover.html"
|
||||||
|
|
||||||
|
cover-full:
|
||||||
|
test "$$(id -u)" = "0" || echo "MUST RUN AS ROOT" 1>&2
|
||||||
|
$(MAKE) test-go COVER=1
|
||||||
|
$(MAKE) cover-platform-bin
|
||||||
|
$(MAKE) cover-platform
|
||||||
|
$(MAKE) cover-html
|
||||||
|
|
||||||
|
##################### DEV TARGETS #####################
|
||||||
|
# not part of the build, must do that manually
|
||||||
|
.PHONY: generate formatcheck format
|
||||||
|
|
||||||
|
generate: generate-platform-test-list
|
||||||
|
protoc -I=replication/logic/pdu --go_out=replication/logic/pdu --go-grpc_out=replication/logic/pdu replication/logic/pdu/pdu.proto
|
||||||
|
protoc -I=rpc/grpcclientidentity/example --go_out=rpc/grpcclientidentity/example/pdu --go-grpc_out=rpc/grpcclientidentity/example/pdu rpc/grpcclientidentity/example/grpcauth.proto
|
||||||
|
$(GO_ENV_VARS) $(GO) generate $(GO_BUILDFLAGS) -x ./...
|
||||||
|
|
||||||
|
GOIMPORTS := goimports -srcdir . -local 'github.com/zrepl/zrepl'
|
||||||
|
FINDSRCFILES := find . -type f -name '*.go' -not -path "./vendor/*" -not -name '*.pb.go' -not -name '*_enumer.go'
|
||||||
|
|
||||||
|
formatcheck:
|
||||||
|
@# goimports doesn't have a knob to exit with non-zero status code if formatting is needed
|
||||||
|
@# see https://go-review.googlesource.com/c/tools/+/237378
|
||||||
|
@ affectedfiles=$$($(GOIMPORTS) -l $(shell $(FINDSRCFILES)) | tee /dev/stderr | wc -l); test "$$affectedfiles" = 0
|
||||||
|
|
||||||
|
format:
|
||||||
|
@ $(GOIMPORTS) -w -d $(shell $(FINDSRCFILES))
|
||||||
|
|
||||||
|
##################### NOARCH #####################
|
||||||
|
.PHONY: noarch $(ARTIFACTDIR)/bash_completion $(ARTIFACTDIR)/_zrepl.zsh_completion $(ARTIFACTDIR)/go_env.txt docs docs-clean
|
||||||
|
|
||||||
|
|
||||||
|
$(ARTIFACTDIR):
|
||||||
|
mkdir -p "$@"
|
||||||
|
$(ARTIFACTDIR)/docs: $(ARTIFACTDIR)
|
||||||
|
mkdir -p "$@"
|
||||||
|
|
||||||
|
noarch: $(ARTIFACTDIR)/bash_completion $(ARTIFACTDIR)/_zrepl.zsh_completion $(ARTIFACTDIR)/go_env.txt docs
|
||||||
|
# pass
|
||||||
|
|
||||||
|
$(ARTIFACTDIR)/bash_completion:
|
||||||
|
$(MAKE) zrepl-bin GOOS=$(GOHOSTOS) GOARCH=$(GOHOSTARCH)
|
||||||
|
artifacts/zrepl-$(GOHOSTOS)-$(GOHOSTARCH) gencompletion bash "$@"
|
||||||
|
|
||||||
|
$(ARTIFACTDIR)/_zrepl.zsh_completion:
|
||||||
|
$(MAKE) zrepl-bin GOOS=$(GOHOSTOS) GOARCH=$(GOHOSTARCH)
|
||||||
|
artifacts/zrepl-$(GOHOSTOS)-$(GOHOSTARCH) gencompletion zsh "$@"
|
||||||
|
|
||||||
|
$(ARTIFACTDIR)/go_env.txt:
|
||||||
|
$(GO_ENV_VARS) $(GO) env > $@
|
||||||
|
$(GO) version >> $@
|
||||||
|
|
||||||
|
docs: $(ARTIFACTDIR)/docs
|
||||||
|
# https://www.sphinx-doc.org/en/master/man/sphinx-build.html
|
||||||
|
$(MAKE) -C docs \
|
||||||
|
html \
|
||||||
|
BUILDDIR=../artifacts/docs \
|
||||||
|
SPHINXOPTS="-W --keep-going -n"
|
||||||
|
|
||||||
|
docs-clean:
|
||||||
|
$(MAKE) -C docs \
|
||||||
|
clean \
|
||||||
|
BUILDDIR=../artifacts/docs
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
[](https://github.com/zrepl/zrepl/blob/master/LICENSE)
|
[](https://github.com/zrepl/zrepl/blob/master/LICENSE)
|
||||||
[](https://golang.org/)
|
[](https://golang.org/)
|
||||||
[](https://zrepl.github.io)
|
[](https://zrepl.github.io)
|
||||||
|
[](https://patreon.com/zrepl)
|
||||||
|
[](https://github.com/sponsors/problame)
|
||||||
|
[](https://liberapay.com/zrepl/donate)
|
||||||
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R5QSXJVYHGX96)
|
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R5QSXJVYHGX96)
|
||||||
[](https://liberapay.com/zrepl/donate)
|
|
||||||
[](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fgithub.com%2Fzrepl%2Fzrepl)
|
[](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fgithub.com%2Fzrepl%2Fzrepl)
|
||||||
|
[](https://matrix.to/#/#zrepl:matrix.org)
|
||||||
|
|
||||||
# zrepl
|
# zrepl
|
||||||
zrepl is a one-stop ZFS backup & replication solution.
|
zrepl is a one-stop ZFS backup & replication solution.
|
||||||
@@ -19,91 +22,92 @@ zrepl is a one-stop ZFS backup & replication solution.
|
|||||||
|
|
||||||
## Feature Requests
|
## Feature Requests
|
||||||
|
|
||||||
1. Does you feature request require default values / some kind of configuration?
|
1. Does your feature request require default values / some kind of configuration?
|
||||||
If so, think of an expressive configuration example.
|
If so, think of an expressive configuration example.
|
||||||
2. Think of at least one use case that generalizes from your concrete application.
|
2. Think of at least one use case that generalizes from your concrete application.
|
||||||
3. Open an issue on GitHub with example conf & use case attached.
|
3. Open an issue on GitHub with example conf & use case attached.
|
||||||
|
4. **Optional**: [Post a bounty](https://www.bountysource.com/teams/zrepl) on the issue, or [contact Christian Schwarz](https://cschwarz.com) for contract work.
|
||||||
|
|
||||||
The above does not apply if you already implemented everything.
|
The above does not apply if you already implemented everything.
|
||||||
Check out the *Coding Workflow* section below for details.
|
Check out the *Coding Workflow* section below for details.
|
||||||
|
|
||||||
## Package Maintainer Information
|
## Building, Releasing, Downstream-Packaging
|
||||||
|
|
||||||
* Follow the steps in `docs/installation.rst -> Compiling from Source` and read the Makefile / shell scripts used in this process.
|
This section provides an overview of the zrepl build & release process.
|
||||||
* Make sure your distro is compatible with the paths in `docs/installation.rst`.
|
Check out `docs/installation/compile-from-source.rst` for build-from-source instructions.
|
||||||
|
|
||||||
|
### Overview
|
||||||
|
|
||||||
|
zrepl is written in [Go](https://golang.org) and uses [Go modules](https://github.com/golang/go/wiki/Modules) to manage dependencies.
|
||||||
|
The documentation is written in [ReStructured Text](http://docutils.sourceforge.net/rst.html) using the [Sphinx](https://www.sphinx-doc.org) framework.
|
||||||
|
|
||||||
|
Install **build dependencies** using `./lazy.sh devsetup`.
|
||||||
|
`lazy.sh` uses `python3-pip` to fetch the build dependencies for the docs - you might want to use a [venv](https://docs.python.org/3/library/venv.html).
|
||||||
|
If you just want to install the Go dependencies, run `./lazy.sh godep`.
|
||||||
|
|
||||||
|
The **test suite** is split into pure **Go tests** (`make test-go`) and **platform tests** that interact with ZFS and thus generally **require root privileges** (`sudo make test-platform`).
|
||||||
|
Platform tests run on their own pool with the name `zreplplatformtest`, which is created using the file vdev in `/tmp`.
|
||||||
|
|
||||||
|
For a full **code coverage** profile, run `make test-go COVER=1 && sudo make test-platform && make cover-merge`.
|
||||||
|
An HTML report can be generated using `make cover-html`.
|
||||||
|
|
||||||
|
**Code generation** is triggered by `make generate`. Generated code is committed to the source tree.
|
||||||
|
|
||||||
|
### Build & Release Process
|
||||||
|
|
||||||
|
**The `Makefile` is catering to the needs of developers & CI, not distro packagers**.
|
||||||
|
It provides phony targets for
|
||||||
|
* local development (building, running tests, etc)
|
||||||
|
* building a release in Docker (used by the CI & release management)
|
||||||
|
* building .deb and .rpm packages out of the release artifacts.
|
||||||
|
|
||||||
|
**Build tooling & dependencies** are documented as code in `lazy.sh`.
|
||||||
|
Go dependencies are then fetched by the go command and pip dependencies are pinned through a `requirements.txt`.
|
||||||
|
|
||||||
|
**We use CircleCI for continuous integration**.
|
||||||
|
There are two workflows:
|
||||||
|
|
||||||
|
* `ci` runs for every commit / branch / tag pushed to GitHub.
|
||||||
|
It is supposed to run very fast (<5min and provides quick feedback to developers).
|
||||||
|
It runs formatting checks, lints and tests on the most important OSes / architectures.
|
||||||
|
Artifacts are published to minio.cschwarz.com (see GitHub Commit Status).
|
||||||
|
|
||||||
|
* `release` runs
|
||||||
|
* on manual triggers through the CircleCI API (in order to produce a release)
|
||||||
|
* periodically on `master`
|
||||||
|
Artifacts are published to minio.cschwarz.com (see GitHub Commit Status).
|
||||||
|
|
||||||
|
**Releases** are issued via Git tags + GitHub Releases feature.
|
||||||
|
The procedure to issue a release is as follows:
|
||||||
|
* Issue the source release:
|
||||||
|
* Git tag the release on the `master` branch.
|
||||||
|
* Push the tag.
|
||||||
|
* Run `./docs/publish.sh` to re-build & push zrepl.github.io.
|
||||||
|
* Issue the official binary release:
|
||||||
|
* Run the `release` pipeline (triggered via CircleCI API)
|
||||||
|
* Download the artifacts to the release manager's machine.
|
||||||
|
* Create a GitHub release, edit the changelog, upload all the release artifacts, including .rpm and .deb files.
|
||||||
|
* Issue the GitHub release.
|
||||||
|
* Add the .rpm and .deb files to the official zrepl repos, publish those.
|
||||||
|
|
||||||
|
**Official binary releases are not re-built when Go receives an update. If the Go update is critical to zrepl (e.g. a Go security update that affects zrepl), we'd issue a new source release**.
|
||||||
|
The rationale for this is that whereas distros provide a mechanism for this (`$zrepl_source_release-$distro_package_revision`), GitHub Releases doesn't which means we'd need to update the existing GitHub release's assets, which nobody would notice (no RSS feed updates, etc.).
|
||||||
|
Downstream packagers can read the changelog to determine whether they want to push that minor release into their distro or simply skip it.
|
||||||
|
|
||||||
|
### Additional Notes to Distro Package Maintainers
|
||||||
|
|
||||||
|
* Run the platform tests (Docs -> Usage -> Platform Tests) **on a test system** to validate that zrepl's abstractions on top of ZFS work with the system ZFS.
|
||||||
* Ship a default config that adheres to your distro's `hier` and logging system.
|
* Ship a default config that adheres to your distro's `hier` and logging system.
|
||||||
* Ship a service manager file and _please_ try to upstream it to this repository.
|
* Ship a service manager file and _please_ try to upstream it to this repository.
|
||||||
* `dist/systemd` contains a Systemd unit template.
|
* `dist/systemd` contains a Systemd unit template.
|
||||||
* Ship other material provided in `./dist`, e.g. in `/usr/share/zrepl/`.
|
* Ship other material provided in `./dist`, e.g. in `/usr/share/zrepl/`.
|
||||||
* Use `make release ZREPL_VERSION='mydistro-1.2.3_1'`
|
* Have a look at the `Makefile`'s `ZREPL_VERSION` variable and how it passed to Go's `ldFlags`.
|
||||||
* Your distro's name and any versioning supplemental to zrepl's (e.g. package revision) should be in this string
|
This is how `zrepl version` knows what version number to show.
|
||||||
|
Your build system should set the `ldFlags` flags appropriately and add a prefix or suffix that indicates that the given zrepl binary is a distro build, not an official one.
|
||||||
* Make sure you are informed about new zrepl versions, e.g. by subscribing to GitHub's release RSS feed.
|
* Make sure you are informed about new zrepl versions, e.g. by subscribing to GitHub's release RSS feed.
|
||||||
|
|
||||||
## Developer Documentation
|
|
||||||
|
|
||||||
zrepl is written in [Go](https://golang.org) and uses [`dep`](https://github.com/golang/dep) to manage dependencies.
|
## Contributing Code
|
||||||
The documentation is written in [ReStructured Text](http://docutils.sourceforge.net/rst.html) using the [Sphinx](https://www.sphinx-doc.org) framework.
|
|
||||||
|
|
||||||
To get started, run `./lazy.sh devsetup` to easily install build dependencies and read `docs/installation.rst -> Compiling from Source`.
|
|
||||||
|
|
||||||
### Overall Architecture
|
|
||||||
|
|
||||||
The application architecture is documented as part of the user docs in the *Implementation* section (`docs/content/impl`).
|
|
||||||
Make sure to develop an understanding how zrepl is typically used by studying the user docs first.
|
|
||||||
|
|
||||||
### Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
├── artifacts # build artifcats generate by make
|
|
||||||
├── cli # wrapper around CLI package cobra
|
|
||||||
├── client # all subcommands that are not `daemon`
|
|
||||||
├── config # config data types (=> package yaml-config)
|
|
||||||
│ └── samples
|
|
||||||
├── daemon # the implementation of `zrepl daemon` subcommand
|
|
||||||
│ ├── filters
|
|
||||||
│ ├── job # job implementations
|
|
||||||
│ ├── logging # logging outlets + formatters
|
|
||||||
│ ├── nethelpers
|
|
||||||
│ ├── prometheus
|
|
||||||
│ ├── pruner # pruner implementation
|
|
||||||
│ ├── snapper # snapshotter implementation
|
|
||||||
├── docs # sphinx-based documentation
|
|
||||||
├── dist # supplemental material for users & package maintainers
|
|
||||||
│ ├── **/*.rst # documentation in reStructuredText
|
|
||||||
│ ├── sphinxconf
|
|
||||||
│ │ └── conf.py # sphinx config (see commit 445a280 why its not in docs/)
|
|
||||||
│ ├── requirements.txt # pip3 requirements to build documentation
|
|
||||||
│ ├── publish.sh # shell script for automated rendering & deploy to zrepl.github.io repo
|
|
||||||
│ └── public_git # checkout of zrepl.github.io managed by above shell script
|
|
||||||
├── endpoint # implementation of replication endpoints (=> package replication)
|
|
||||||
├── logger # our own logger package
|
|
||||||
├── pruning # pruning rules (the logic, not the actual execution)
|
|
||||||
│ └── retentiongrid
|
|
||||||
├── replication
|
|
||||||
│ ├── driver # the driver of the replication logic (status reporting, error handling)
|
|
||||||
│ ├── logic # planning & executing replication steps via rpc
|
|
||||||
| | └── pdu # the generated gRPC & protobuf code used in replication (and endpoints)
|
|
||||||
│ └── report # the JSON-serializable report datastructures exposed to the client
|
|
||||||
├── rpc # the hybrid gRPC + ./dataconn RPC client: connects to a remote replication.Endpoint
|
|
||||||
│ ├── dataconn # Bulk data-transfer RPC protocol
|
|
||||||
│ ├── grpcclientidentity # adaptor to inject package transport's 'client identity' concept into gRPC contexts
|
|
||||||
│ ├── netadaptor # adaptor to convert a package transport's Connecter and Listener into net.* primitives
|
|
||||||
│ ├── transportmux # TCP connecter and listener used to split control & data traffic
|
|
||||||
│ └── versionhandshake # replication protocol version handshake perfomed on newly established connections
|
|
||||||
├── tlsconf # abstraction for Go TLS server + client config
|
|
||||||
├── transport # transports implementation
|
|
||||||
│ ├── fromconfig
|
|
||||||
│ ├── local
|
|
||||||
│ ├── ssh
|
|
||||||
│ ├── tcp
|
|
||||||
│ └── tls
|
|
||||||
├── util
|
|
||||||
├── vendor # managed by dep
|
|
||||||
├── version # abstraction for versions (filled during build by Makefile)
|
|
||||||
└── zfs # zfs(8) wrappers
|
|
||||||
```
|
|
||||||
|
|
||||||
### Coding Workflow
|
|
||||||
|
|
||||||
* Open an issue when starting to hack on a new feature
|
* Open an issue when starting to hack on a new feature
|
||||||
* Commits should reference the issue they are related to
|
* Commits should reference the issue they are related to
|
||||||
@@ -113,9 +117,6 @@ Make sure to develop an understanding how zrepl is typically used by studying th
|
|||||||
|
|
||||||
Backward-incompatible changes must be documented in the git commit message and are listed in `docs/changelog.rst`.
|
Backward-incompatible changes must be documented in the git commit message and are listed in `docs/changelog.rst`.
|
||||||
|
|
||||||
* Config-breaking changes must contain a line `BREAK CONFIG` in the commit message
|
|
||||||
* Other breaking changes must contain a line `BREAK` in the commit message
|
|
||||||
|
|
||||||
### Glossary & Naming Inconsistencies
|
### Glossary & Naming Inconsistencies
|
||||||
|
|
||||||
In ZFS, *dataset* refers to the objects *filesystem*, *ZVOL* and *snapshot*. <br />
|
In ZFS, *dataset* refers to the objects *filesystem*, *ZVOL* and *snapshot*. <br />
|
||||||
@@ -132,4 +133,3 @@ variables and types are often named *dataset* when they in fact refer to a *file
|
|||||||
There will not be a big refactoring (an attempt was made, but it's destroying too much history without much gain).
|
There will not be a big refactoring (an attempt was made, but it's destroying too much history without much gain).
|
||||||
|
|
||||||
However, new contributions & patches should fix naming without further notice in the commit message.
|
However, new contributions & patches should fix naming without further notice in the commit message.
|
||||||
|
|
||||||
|
|||||||
+19
-14
@@ -1,12 +1,18 @@
|
|||||||
FROM golang:latest
|
FROM !SUBSTITUTED_BY_MAKEFILE
|
||||||
|
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y \
|
||||||
python3-pip \
|
python3-pip \
|
||||||
unzip
|
python3-venv \
|
||||||
|
unzip \
|
||||||
|
gawk
|
||||||
|
|
||||||
RUN wget https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protoc-3.6.1-linux-x86_64.zip
|
ADD build.installprotoc.bash ./
|
||||||
RUN echo "6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807 protoc-3.6.1-linux-x86_64.zip" | sha256sum -c
|
RUN bash build.installprotoc.bash
|
||||||
RUN unzip -d /usr protoc-3.6.1-linux-x86_64.zip
|
|
||||||
|
# setup venv
|
||||||
|
ENV VIRTUAL_ENV=/opt/venv
|
||||||
|
RUN python3 -m venv $VIRTUAL_ENV
|
||||||
|
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||||
|
|
||||||
ADD lazy.sh /tmp/lazy.sh
|
ADD lazy.sh /tmp/lazy.sh
|
||||||
ADD docs/requirements.txt /tmp/requirements.txt
|
ADD docs/requirements.txt /tmp/requirements.txt
|
||||||
@@ -14,18 +20,17 @@ ENV ZREPL_LAZY_DOCS_REQPATH=/tmp/requirements.txt
|
|||||||
RUN /tmp/lazy.sh docdep
|
RUN /tmp/lazy.sh docdep
|
||||||
|
|
||||||
# prepare volume mount of git checkout to /zrepl
|
# prepare volume mount of git checkout to /zrepl
|
||||||
RUN mkdir -p /go/src/github.com/zrepl/zrepl
|
RUN mkdir -p /src/github.com/zrepl/zrepl
|
||||||
RUN mkdir -p /.cache && chmod -R 0777 /.cache
|
RUN mkdir -p /.cache && chmod -R 0777 /.cache
|
||||||
WORKDIR /go/src/github.com/zrepl/zrepl
|
|
||||||
|
|
||||||
ADD Gopkg.toml Gopkg.lock ./
|
# $GOPATH is /go
|
||||||
|
# Go 1.12 doesn't use modules within GOPATH, but 1.13 and later do
|
||||||
|
# => store source outside of GOPATH
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
# godep will install the Go dependencies to vendor in order to then build and install
|
# Install build tools (e.g. protobuf generator, stringer) into $GOPATH/bin
|
||||||
# build dependencies like stringer to $GOPATH/bin.
|
ADD build/ /tmp/build
|
||||||
# However, since users volume-mount their Git checkout into /go/src/github.com/zrepl/zrepl
|
|
||||||
# the vendor directory will be empty at build time, allowing them to experiment with
|
|
||||||
# new checkouts, etc.
|
|
||||||
# Thus, we only use the vendored deps for building dependencies.
|
|
||||||
RUN /tmp/lazy.sh godep
|
RUN /tmp/lazy.sh godep
|
||||||
|
|
||||||
RUN chmod -R 0777 /go
|
RUN chmod -R 0777 /go
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
set -x
|
||||||
|
|
||||||
|
MACH=$(uname -m)
|
||||||
|
MACH="${MACH/aarch64/aarch_64}"
|
||||||
|
|
||||||
|
VERSION=3.6.1
|
||||||
|
FILENAME=protoc-"$VERSION"-linux-"$MACH".zip
|
||||||
|
|
||||||
|
if [ -e "$FILENAME" ]; then
|
||||||
|
echo "$FILENAME" already exists 1>&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
wget https://github.com/protocolbuffers/protobuf/releases/download/v"$VERSION"/"$FILENAME"
|
||||||
|
|
||||||
|
stat "$FILENAME"
|
||||||
|
|
||||||
|
sha256sum -c --ignore-missing <<EOF
|
||||||
|
6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807 protoc-3.6.1-linux-x86_64.zip
|
||||||
|
af8e5aaaf39ddec62ec8dd2be1b8d9602c6da66564883a16393ade5f71170922 protoc-3.6.1-linux-aarch_64.zip
|
||||||
|
EOF
|
||||||
|
|
||||||
|
unzip -d /usr "$FILENAME"
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
//+build windows
|
|
||||||
|
|
||||||
// This package cannot actually be built, and since the Travis
|
|
||||||
// tests run go test ./..., we have to avoid a build attempt.
|
|
||||||
// Windows is not supported atm, so this works ¯\_(ツ)_/¯
|
|
||||||
|
|
||||||
// This package is a pseudo-user of build-time dependencies for zrepl,
|
|
||||||
// mostly for various code-generation tools.
|
|
||||||
//
|
|
||||||
// The imports are necessary to satisfy go dep
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
_ "fmt"
|
|
||||||
_ "github.com/alvaroloes/enumer"
|
|
||||||
_ "github.com/golang/protobuf/protoc-gen-go"
|
|
||||||
_ "golang.org/x/tools/cmd/stringer"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
fmt.Println("just a placeholder")
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
module github.com/zrepl/zrepl/build
|
||||||
|
|
||||||
|
go 1.12
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/alvaroloes/enumer v1.1.1
|
||||||
|
github.com/breml/bidichk v0.2.6 // indirect
|
||||||
|
github.com/breml/errchkjson v0.3.5 // indirect
|
||||||
|
github.com/chavacava/garif v0.1.0 // indirect
|
||||||
|
github.com/daixiang0/gci v0.11.1 // indirect
|
||||||
|
github.com/golangci/golangci-lint v1.54.2
|
||||||
|
github.com/golangci/revgrep v0.5.0 // indirect
|
||||||
|
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||||
|
github.com/jgautheron/goconst v1.6.0 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||||
|
github.com/mattn/go-runewidth v0.0.15 // indirect
|
||||||
|
github.com/mgechev/revive v1.3.3 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||||
|
github.com/polyfloyd/go-errorlint v1.4.5 // indirect
|
||||||
|
github.com/prometheus/client_golang v1.16.0 // indirect
|
||||||
|
github.com/prometheus/common v0.44.0 // indirect
|
||||||
|
github.com/prometheus/procfs v0.11.1 // indirect
|
||||||
|
github.com/rivo/uniseg v0.4.4 // indirect
|
||||||
|
github.com/ryanrolds/sqlclosecheck v0.5.1 // indirect
|
||||||
|
github.com/spf13/viper v1.16.0 // indirect
|
||||||
|
github.com/stretchr/objx v0.5.1 // indirect
|
||||||
|
github.com/subosito/gotenv v1.6.0 // indirect
|
||||||
|
github.com/tetafro/godot v1.4.15 // indirect
|
||||||
|
github.com/wadey/gocovmerge v0.0.0-20160331181800-b5bfa59ec0ad
|
||||||
|
github.com/xen0n/gosmopolitan v1.2.2 // indirect
|
||||||
|
gitlab.com/bosi/decorder v0.4.1 // indirect
|
||||||
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
|
go.uber.org/zap v1.25.0 // indirect
|
||||||
|
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||||
|
golang.org/x/exp/typeparams v0.0.0-20230905200255-921286631fa9 // indirect
|
||||||
|
golang.org/x/tools v0.13.0
|
||||||
|
google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0
|
||||||
|
google.golang.org/protobuf v1.31.0
|
||||||
|
mvdan.cc/unparam v0.0.0-20230815095028-f7c6fb1088f0 // indirect
|
||||||
|
)
|
||||||
+2565
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
|||||||
|
//go:build tools
|
||||||
|
// +build tools
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
// the lines are parsed by lazy.sh, do not edit
|
||||||
|
import (
|
||||||
|
_ "github.com/alvaroloes/enumer"
|
||||||
|
_ "github.com/golangci/golangci-lint/cmd/golangci-lint"
|
||||||
|
_ "github.com/wadey/gocovmerge"
|
||||||
|
_ "golang.org/x/tools/cmd/goimports"
|
||||||
|
_ "golang.org/x/tools/cmd/stringer"
|
||||||
|
_ "google.golang.org/grpc/cmd/protoc-gen-go-grpc"
|
||||||
|
_ "google.golang.org/protobuf/cmd/protoc-gen-go"
|
||||||
|
)
|
||||||
+66
-29
@@ -1,11 +1,16 @@
|
|||||||
package cli
|
package cli
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"os"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var rootArgs struct {
|
var rootArgs struct {
|
||||||
@@ -17,38 +22,67 @@ var rootCmd = &cobra.Command{
|
|||||||
Short: "One-stop ZFS replication solution",
|
Short: "One-stop ZFS replication solution",
|
||||||
}
|
}
|
||||||
|
|
||||||
var bashcompCmd = &cobra.Command{
|
func init() {
|
||||||
Use: "bashcomp path/to/out/file",
|
rootCmd.PersistentFlags().StringVar(&rootArgs.configPath, "config", "", "config file path")
|
||||||
Short: "generate bash completions",
|
}
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
if len(args) != 1 {
|
var genCompletionCmd = &cobra.Command{
|
||||||
fmt.Fprintf(os.Stderr, "specify exactly one positional agument\n")
|
Use: "gencompletion",
|
||||||
cmd.Usage()
|
Short: "generate shell auto-completions",
|
||||||
os.Exit(1)
|
}
|
||||||
}
|
|
||||||
if err := rootCmd.GenBashCompletionFile(args[0]); err != nil {
|
type completionCmdInfo struct {
|
||||||
fmt.Fprintf(os.Stderr, "error generating bash completion: %s", err)
|
genFunc func(outpath string) error
|
||||||
os.Exit(1)
|
help string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var completionCmdMap = map[string]completionCmdInfo{
|
||||||
|
"zsh": {
|
||||||
|
rootCmd.GenZshCompletionFile,
|
||||||
|
" save to file `_zrepl` in your zsh's $fpath",
|
||||||
|
},
|
||||||
|
"bash": {
|
||||||
|
rootCmd.GenBashCompletionFile,
|
||||||
|
" save to a path and source that path in your .bashrc",
|
||||||
},
|
},
|
||||||
Hidden: true,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
rootCmd.PersistentFlags().StringVar(&rootArgs.configPath, "config", "", "config file path")
|
for sh, info := range completionCmdMap {
|
||||||
rootCmd.AddCommand(bashcompCmd)
|
sh, info := sh, info
|
||||||
|
genCompletionCmd.AddCommand(&cobra.Command{
|
||||||
|
Use: fmt.Sprintf("%s path/to/out/file", sh),
|
||||||
|
Short: fmt.Sprintf("generate %s completions", sh),
|
||||||
|
Example: info.help,
|
||||||
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
|
if len(args) != 1 {
|
||||||
|
fmt.Fprintf(os.Stderr, "specify exactly one positional agument\n")
|
||||||
|
err := cmd.Usage()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if err := info.genFunc(args[0]); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "error generating %s completion: %s", sh, err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
rootCmd.AddCommand(genCompletionCmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Subcommand struct {
|
type Subcommand struct {
|
||||||
Use string
|
Use string
|
||||||
Short string
|
Short string
|
||||||
Example string
|
Example string
|
||||||
NoRequireConfig bool
|
NoRequireConfig bool
|
||||||
Run func(subcommand *Subcommand, args []string) error
|
Run func(ctx context.Context, subcommand *Subcommand, args []string) error
|
||||||
SetupFlags func(f *pflag.FlagSet)
|
SetupFlags func(f *pflag.FlagSet)
|
||||||
SetupSubcommands func() []*Subcommand
|
SetupSubcommands func() []*Subcommand
|
||||||
|
|
||||||
config *config.Config
|
config *config.Config
|
||||||
configErr error
|
configErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +99,11 @@ func (s *Subcommand) Config() *config.Config {
|
|||||||
|
|
||||||
func (s *Subcommand) run(cmd *cobra.Command, args []string) {
|
func (s *Subcommand) run(cmd *cobra.Command, args []string) {
|
||||||
s.tryParseConfig()
|
s.tryParseConfig()
|
||||||
err := s.Run(s, args)
|
ctx := context.Background()
|
||||||
|
endTask := trace.WithTaskFromStackUpdateCtx(&ctx)
|
||||||
|
defer endTask()
|
||||||
|
err := s.Run(ctx, s, args)
|
||||||
|
endTask()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "%s\n", err)
|
fmt.Fprintf(os.Stderr, "%s\n", err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
@@ -93,8 +131,8 @@ func AddSubcommand(s *Subcommand) {
|
|||||||
|
|
||||||
func addSubcommandToCobraCmd(c *cobra.Command, s *Subcommand) {
|
func addSubcommandToCobraCmd(c *cobra.Command, s *Subcommand) {
|
||||||
cmd := cobra.Command{
|
cmd := cobra.Command{
|
||||||
Use: s.Use,
|
Use: s.Use,
|
||||||
Short: s.Short,
|
Short: s.Short,
|
||||||
Example: s.Example,
|
Example: s.Example,
|
||||||
}
|
}
|
||||||
if s.SetupSubcommands == nil {
|
if s.SetupSubcommands == nil {
|
||||||
@@ -110,7 +148,6 @@ func addSubcommandToCobraCmd(c *cobra.Command, s *Subcommand) {
|
|||||||
c.AddCommand(&cmd)
|
c.AddCommand(&cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
func Run() {
|
func Run() {
|
||||||
if err := rootCmd.Execute(); err != nil {
|
if err := rootCmd.Execute(); err != nil {
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
|
|||||||
+34
-15
@@ -1,41 +1,54 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/kr/pretty"
|
"github.com/kr/pretty"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
"github.com/zrepl/yaml-config"
|
"github.com/zrepl/yaml-config"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
"github.com/zrepl/zrepl/cli"
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/job"
|
"github.com/zrepl/zrepl/daemon/job"
|
||||||
"github.com/zrepl/zrepl/daemon/logging"
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
"os"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var configcheckArgs struct {
|
var configcheckArgs struct {
|
||||||
format string
|
format string
|
||||||
what string
|
what string
|
||||||
|
skipCertCheck bool
|
||||||
}
|
}
|
||||||
|
|
||||||
var ConfigcheckCmd = &cli.Subcommand{
|
var ConfigcheckCmd = &cli.Subcommand{
|
||||||
Use: "configcheck",
|
Use: "configcheck",
|
||||||
Short: "check if config can be parsed without errors",
|
Short: "check if config can be parsed without errors",
|
||||||
SetupFlags: func(f *pflag.FlagSet) {
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
f.StringVar(&configcheckArgs.format, "format", "", "dump parsed config object [pretty|yaml|json]")
|
f.StringVar(&configcheckArgs.format, "format", "", "dump parsed config object [pretty|yaml|json]")
|
||||||
f.StringVar(&configcheckArgs.what, "what", "all", "what to print [all|config|jobs|logging]")
|
f.StringVar(&configcheckArgs.what, "what", "all", "what to print [all|config|jobs|logging]")
|
||||||
|
f.BoolVar(&configcheckArgs.skipCertCheck, "skip-cert-check", false, "skip checking cert files")
|
||||||
},
|
},
|
||||||
Run: func(subcommand *cli.Subcommand, args []string) error {
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
formatMap := map[string]func(interface{}) {
|
formatMap := map[string]func(interface{}){
|
||||||
"": func(i interface{}) {},
|
"": func(i interface{}) {},
|
||||||
"pretty": func(i interface{}) { pretty.Println(i) },
|
"pretty": func(i interface{}) {
|
||||||
|
if _, err := pretty.Println(i); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
},
|
||||||
"json": func(i interface{}) {
|
"json": func(i interface{}) {
|
||||||
json.NewEncoder(os.Stdout).Encode(subcommand.Config())
|
if err := json.NewEncoder(os.Stdout).Encode(subcommand.Config()); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"yaml": func(i interface{}) {
|
"yaml": func(i interface{}) {
|
||||||
yaml.NewEncoder(os.Stdout).Encode(subcommand.Config())
|
if err := yaml.NewEncoder(os.Stdout).Encode(subcommand.Config()); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,8 +58,16 @@ var ConfigcheckCmd = &cli.Subcommand{
|
|||||||
}
|
}
|
||||||
|
|
||||||
var hadErr bool
|
var hadErr bool
|
||||||
|
|
||||||
|
parseFlags := config.ParseFlagsNone
|
||||||
|
|
||||||
|
if configcheckArgs.skipCertCheck {
|
||||||
|
parseFlags |= config.ParseFlagsNoCertCheck
|
||||||
|
}
|
||||||
|
|
||||||
// further: try to build jobs
|
// further: try to build jobs
|
||||||
confJobs, err := job.JobsFromConfig(subcommand.Config())
|
confJobs, err := job.JobsFromConfig(subcommand.Config(), parseFlags)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
err := errors.Wrap(err, "cannot build jobs from config")
|
err := errors.Wrap(err, "cannot build jobs from config")
|
||||||
if configcheckArgs.what == "jobs" {
|
if configcheckArgs.what == "jobs" {
|
||||||
@@ -71,12 +92,11 @@ var ConfigcheckCmd = &cli.Subcommand{
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
whatMap := map[string]func(){
|
||||||
whatMap := map[string]func() {
|
|
||||||
"all": func() {
|
"all": func() {
|
||||||
o := struct {
|
o := struct {
|
||||||
config *config.Config
|
config *config.Config
|
||||||
jobs []job.Job
|
jobs []job.Job
|
||||||
logging *logger.Outlets
|
logging *logger.Outlets
|
||||||
}{
|
}{
|
||||||
subcommand.Config(),
|
subcommand.Config(),
|
||||||
@@ -109,4 +129,3 @@ var ConfigcheckCmd = &cli.Subcommand{
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,10 +4,11 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"github.com/pkg/errors"
|
|
||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
func controlHttpClient(sockpath string) (client http.Client, err error) {
|
func controlHttpClient(sockpath string) (client http.Client, err error) {
|
||||||
@@ -35,7 +36,7 @@ func jsonRequestResponse(c http.Client, endpoint string, req interface{}, res in
|
|||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
var msg bytes.Buffer
|
var msg bytes.Buffer
|
||||||
io.CopyN(&msg, resp.Body, 4096)
|
_, _ = io.CopyN(&msg, resp.Body, 4096) // ignore error, just display what we got
|
||||||
return errors.Errorf("%s", msg.String())
|
return errors.Errorf("%s", msg.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+168
-8
@@ -4,8 +4,13 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/fatih/color"
|
||||||
|
"github.com/kr/pretty"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/job"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
"github.com/zrepl/zrepl/zfs"
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
"github.com/zrepl/zrepl/cli"
|
||||||
@@ -22,11 +27,6 @@ var (
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
type migration struct {
|
|
||||||
name string
|
|
||||||
method func(config *config.Config, args []string) error
|
|
||||||
}
|
|
||||||
|
|
||||||
var migrations = []*cli.Subcommand{
|
var migrations = []*cli.Subcommand{
|
||||||
&cli.Subcommand{
|
&cli.Subcommand{
|
||||||
Use: "0.0.X:0.1:placeholder",
|
Use: "0.0.X:0.1:placeholder",
|
||||||
@@ -35,20 +35,26 @@ var migrations = []*cli.Subcommand{
|
|||||||
f.BoolVar(&migratePlaceholder0_1Args.dryRun, "dry-run", false, "dry run")
|
f.BoolVar(&migratePlaceholder0_1Args.dryRun, "dry-run", false, "dry run")
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
&cli.Subcommand{
|
||||||
|
Use: "replication-cursor:v1-v2",
|
||||||
|
Run: doMigrateReplicationCursor,
|
||||||
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
|
f.BoolVar(&migrateReplicationCursorArgs.dryRun, "dry-run", false, "dry run")
|
||||||
|
},
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
var migratePlaceholder0_1Args struct {
|
var migratePlaceholder0_1Args struct {
|
||||||
dryRun bool
|
dryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func doMigratePlaceholder0_1(sc *cli.Subcommand, args []string) error {
|
func doMigratePlaceholder0_1(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
if len(args) != 0 {
|
if len(args) != 0 {
|
||||||
return fmt.Errorf("migration does not take arguments, got %v", args)
|
return fmt.Errorf("migration does not take arguments, got %v", args)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := sc.Config()
|
cfg := sc.Config()
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
allFSS, err := zfs.ZFSListMapping(ctx, zfs.NoFilter())
|
allFSS, err := zfs.ZFSListMapping(ctx, zfs.NoFilter())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "cannot list filesystems")
|
return errors.Wrap(err, "cannot list filesystems")
|
||||||
@@ -92,7 +98,7 @@ func doMigratePlaceholder0_1(sc *cli.Subcommand, args []string) error {
|
|||||||
}
|
}
|
||||||
for _, fs := range wi.fss {
|
for _, fs := range wi.fss {
|
||||||
fmt.Printf("\t%q ... ", fs.ToString())
|
fmt.Printf("\t%q ... ", fs.ToString())
|
||||||
r, err := zfs.ZFSMigrateHashBasedPlaceholderToCurrent(fs, migratePlaceholder0_1Args.dryRun)
|
r, err := zfs.ZFSMigrateHashBasedPlaceholderToCurrent(ctx, fs, migratePlaceholder0_1Args.dryRun)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("error: %s\n", err)
|
fmt.Printf("error: %s\n", err)
|
||||||
} else if !r.NeedsModification {
|
} else if !r.NeedsModification {
|
||||||
@@ -106,3 +112,157 @@ func doMigratePlaceholder0_1(sc *cli.Subcommand, args []string) error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var migrateReplicationCursorArgs struct {
|
||||||
|
dryRun bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var bold = color.New(color.Bold)
|
||||||
|
var succ = color.New(color.FgGreen)
|
||||||
|
var fail = color.New(color.FgRed)
|
||||||
|
|
||||||
|
var migrateReplicationCursorSkipSentinel = fmt.Errorf("skipping this filesystem")
|
||||||
|
|
||||||
|
func doMigrateReplicationCursor(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
|
if len(args) != 0 {
|
||||||
|
return fmt.Errorf("migration does not take arguments, got %v", args)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg := sc.Config()
|
||||||
|
jobs, err := job.JobsFromConfig(cfg, config.ParseFlagsNone)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("cannot parse config:\n%s\n\n", err)
|
||||||
|
fmt.Printf("NOTE: this migration was released together with a change in job name requirements.\n")
|
||||||
|
return fmt.Errorf("exiting migration after error")
|
||||||
|
}
|
||||||
|
|
||||||
|
v1cursorJobs := make([]job.Job, 0, len(cfg.Jobs))
|
||||||
|
for i, j := range cfg.Jobs {
|
||||||
|
if jobs[i].Name() != j.Name() {
|
||||||
|
panic("implementation error")
|
||||||
|
}
|
||||||
|
switch j.Ret.(type) {
|
||||||
|
case *config.PushJob:
|
||||||
|
v1cursorJobs = append(v1cursorJobs, jobs[i])
|
||||||
|
case *config.SourceJob:
|
||||||
|
v1cursorJobs = append(v1cursorJobs, jobs[i])
|
||||||
|
default:
|
||||||
|
fmt.Printf("ignoring job %q (%d/%d, type %T), not supposed to create v1 replication cursors\n", j.Name(), i, len(cfg.Jobs), j.Ret)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// scan all filesystems for v1 replication cursors
|
||||||
|
|
||||||
|
fss, err := zfs.ZFSListMapping(ctx, zfs.NoFilter())
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "list filesystems")
|
||||||
|
}
|
||||||
|
|
||||||
|
var hadError bool
|
||||||
|
for _, fs := range fss {
|
||||||
|
|
||||||
|
bold.Printf("INSPECT FILESYSTEM %q\n", fs.ToString())
|
||||||
|
|
||||||
|
err := doMigrateReplicationCursorFS(ctx, v1cursorJobs, fs)
|
||||||
|
if err == migrateReplicationCursorSkipSentinel {
|
||||||
|
bold.Printf("FILESYSTEM SKIPPED\n")
|
||||||
|
} else if err != nil {
|
||||||
|
hadError = true
|
||||||
|
fail.Printf("MIGRATION FAILED: %s\n", err)
|
||||||
|
} else {
|
||||||
|
succ.Printf("FILESYSTEM %q COMPLETE\n", fs.ToString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hadError {
|
||||||
|
fail.Printf("\n\none or more filesystems could not be migrated, please inspect output and or re-run migration")
|
||||||
|
return errors.Errorf("")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func doMigrateReplicationCursorFS(ctx context.Context, v1CursorJobs []job.Job, fs *zfs.DatasetPath) error {
|
||||||
|
|
||||||
|
var owningJob job.Job = nil
|
||||||
|
for _, job := range v1CursorJobs {
|
||||||
|
conf := job.SenderConfig()
|
||||||
|
if conf == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pass, err := conf.FSF.Filter(fs)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "filesystem filter error in job %q for fs %q", job.Name(), fs.ToString())
|
||||||
|
}
|
||||||
|
if !pass {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if owningJob != nil {
|
||||||
|
return errors.Errorf("jobs %q and %q both match %q\ncannot attribute replication cursor to either one", owningJob.Name(), job.Name(), fs)
|
||||||
|
}
|
||||||
|
owningJob = job
|
||||||
|
}
|
||||||
|
if owningJob == nil {
|
||||||
|
fmt.Printf("no job's Filesystems filter matches\n")
|
||||||
|
return migrateReplicationCursorSkipSentinel
|
||||||
|
}
|
||||||
|
fmt.Printf("identified owning job %q\n", owningJob.Name())
|
||||||
|
|
||||||
|
bookmarks, err := zfs.ZFSListFilesystemVersions(ctx, fs, zfs.ListFilesystemVersionsOptions{
|
||||||
|
Types: zfs.Bookmarks,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "list filesystem versions of %q", fs.ToString())
|
||||||
|
}
|
||||||
|
|
||||||
|
var oldCursor *zfs.FilesystemVersion
|
||||||
|
for i, fsv := range bookmarks {
|
||||||
|
_, _, err := endpoint.ParseReplicationCursorBookmarkName(fsv.ToAbsPath(fs))
|
||||||
|
if err != endpoint.ErrV1ReplicationCursor {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if oldCursor != nil {
|
||||||
|
fmt.Printf("unexpected v1 replication cursor candidate: %q", fsv.ToAbsPath(fs))
|
||||||
|
return errors.Wrap(err, "multiple filesystem versions identified as v1 replication cursors")
|
||||||
|
}
|
||||||
|
|
||||||
|
oldCursor = &bookmarks[i]
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
if oldCursor == nil {
|
||||||
|
bold.Printf("no v1 replication cursor found for filesystem %q\n", fs.ToString())
|
||||||
|
return migrateReplicationCursorSkipSentinel
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("found v1 replication cursor:\n%s\n", pretty.Sprint(oldCursor))
|
||||||
|
|
||||||
|
mostRecentNew, err := endpoint.GetMostRecentReplicationCursorOfJob(ctx, fs.ToString(), owningJob.SenderConfig().JobID)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "get most recent v2 replication cursor")
|
||||||
|
}
|
||||||
|
|
||||||
|
if mostRecentNew == nil {
|
||||||
|
return errors.Errorf("no v2 replication cursor found for job %q on filesystem %q", owningJob.SenderConfig().JobID, fs.ToString())
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("most recent v2 replication cursor:\n%#v", oldCursor)
|
||||||
|
|
||||||
|
if !(mostRecentNew.CreateTXG >= oldCursor.CreateTXG) {
|
||||||
|
return errors.Errorf("v1 replication cursor createtxg is higher than v2 cursor's, skipping this filesystem")
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("determined that v2 cursor is bookmark of same or newer version than v1 cursor\n")
|
||||||
|
fmt.Printf("destroying v1 cursor %q\n", oldCursor.ToAbsPath(fs))
|
||||||
|
|
||||||
|
if migrateReplicationCursorArgs.dryRun {
|
||||||
|
succ.Printf("DRY RUN\n")
|
||||||
|
} else {
|
||||||
|
if err := zfs.ZFSDestroyFilesystemVersion(ctx, fs, oldCursor); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
+4
-60
@@ -1,66 +1,10 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import "github.com/zrepl/zrepl/cli"
|
||||||
"errors"
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
|
||||||
"github.com/zrepl/zrepl/config"
|
|
||||||
"github.com/zrepl/zrepl/daemon"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
)
|
|
||||||
|
|
||||||
var pprofArgs struct {
|
|
||||||
daemon.PprofServerControlMsg
|
|
||||||
}
|
|
||||||
|
|
||||||
var PprofCmd = &cli.Subcommand{
|
var PprofCmd = &cli.Subcommand{
|
||||||
Use: "pprof off | [on TCP_LISTEN_ADDRESS]",
|
Use: "pprof",
|
||||||
Short: "start a http server exposing go-tool-compatible profiling endpoints at TCP_LISTEN_ADDRESS",
|
SetupSubcommands: func() []*cli.Subcommand {
|
||||||
Run: func(subcommand *cli.Subcommand, args []string) error {
|
return []*cli.Subcommand{PprofListenCmd, pprofActivityTraceCmd}
|
||||||
if len(args) < 1 {
|
|
||||||
goto enargs
|
|
||||||
}
|
|
||||||
switch args[0] {
|
|
||||||
case "on":
|
|
||||||
pprofArgs.Run = true
|
|
||||||
if len(args) != 2 {
|
|
||||||
return errors.New("must specify TCP_LISTEN_ADDRESS as second positional argument")
|
|
||||||
}
|
|
||||||
pprofArgs.HttpListenAddress = args[1]
|
|
||||||
case "off":
|
|
||||||
if len(args) != 1 {
|
|
||||||
goto enargs
|
|
||||||
}
|
|
||||||
pprofArgs.Run = false
|
|
||||||
}
|
|
||||||
|
|
||||||
RunPProf(subcommand.Config())
|
|
||||||
return nil
|
|
||||||
enargs:
|
|
||||||
return errors.New("invalid number of positional arguments")
|
|
||||||
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func RunPProf(conf *config.Config) {
|
|
||||||
log := log.New(os.Stderr, "", 0)
|
|
||||||
|
|
||||||
die := func() {
|
|
||||||
log.Printf("exiting after error")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
log.Printf("connecting to zrepl daemon")
|
|
||||||
|
|
||||||
httpc, err := controlHttpClient(conf.Global.Control.SockPath)
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("error creating http client: %s", err)
|
|
||||||
die()
|
|
||||||
}
|
|
||||||
err = jsonRequestResponse(httpc, daemon.ControlJobEndpointPProf, pprofArgs.PprofServerControlMsg, struct{}{})
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("error sending control message: %s", err)
|
|
||||||
die()
|
|
||||||
}
|
|
||||||
log.Printf("finished")
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/net/websocket"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
)
|
||||||
|
|
||||||
|
var pprofActivityTraceCmd = &cli.Subcommand{
|
||||||
|
Use: "activity-trace ZREPL_PPROF_HOST:ZREPL_PPROF_PORT",
|
||||||
|
Short: "attach to zrepl daemon with activated pprof listener and dump an activity-trace to stdout",
|
||||||
|
Run: runPProfActivityTrace,
|
||||||
|
}
|
||||||
|
|
||||||
|
func runPProfActivityTrace(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
log := log.New(os.Stderr, "", 0)
|
||||||
|
|
||||||
|
die := func() {
|
||||||
|
log.Printf("exiting after error")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(args) != 1 {
|
||||||
|
log.Printf("exactly one positional argument is required")
|
||||||
|
die()
|
||||||
|
}
|
||||||
|
|
||||||
|
url := "ws://" + args[0] + "/debug/zrepl/activity-trace" // FIXME dont' repeat that
|
||||||
|
|
||||||
|
log.Printf("attaching to activity trace stream %s", url)
|
||||||
|
ws, err := websocket.Dial(url, "", url)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error: %s", err)
|
||||||
|
die()
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(os.Stdout, ws)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon"
|
||||||
|
)
|
||||||
|
|
||||||
|
var pprofListenCmd struct {
|
||||||
|
daemon.PprofServerControlMsg
|
||||||
|
}
|
||||||
|
|
||||||
|
var PprofListenCmd = &cli.Subcommand{
|
||||||
|
Use: "listen off | [on TCP_LISTEN_ADDRESS]",
|
||||||
|
Short: "start a http server exposing go-tool-compatible profiling endpoints at TCP_LISTEN_ADDRESS",
|
||||||
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
if len(args) < 1 {
|
||||||
|
goto enargs
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "on":
|
||||||
|
pprofListenCmd.Run = true
|
||||||
|
if len(args) != 2 {
|
||||||
|
return errors.New("must specify TCP_LISTEN_ADDRESS as second positional argument")
|
||||||
|
}
|
||||||
|
pprofListenCmd.HttpListenAddress = args[1]
|
||||||
|
case "off":
|
||||||
|
if len(args) != 1 {
|
||||||
|
goto enargs
|
||||||
|
}
|
||||||
|
pprofListenCmd.Run = false
|
||||||
|
}
|
||||||
|
|
||||||
|
RunPProf(subcommand.Config())
|
||||||
|
return nil
|
||||||
|
enargs:
|
||||||
|
return errors.New("invalid number of positional arguments")
|
||||||
|
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func RunPProf(conf *config.Config) {
|
||||||
|
log := log.New(os.Stderr, "", 0)
|
||||||
|
|
||||||
|
die := func() {
|
||||||
|
log.Printf("exiting after error")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("connecting to zrepl daemon")
|
||||||
|
|
||||||
|
httpc, err := controlHttpClient(conf.Global.Control.SockPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error creating http client: %s", err)
|
||||||
|
die()
|
||||||
|
}
|
||||||
|
err = jsonRequestResponse(httpc, daemon.ControlJobEndpointPProf, pprofListenCmd.PprofServerControlMsg, struct{}{})
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("error sending control message: %s", err)
|
||||||
|
die()
|
||||||
|
}
|
||||||
|
log.Printf("finished")
|
||||||
|
}
|
||||||
+6
-3
@@ -1,7 +1,10 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
"github.com/zrepl/zrepl/cli"
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon"
|
"github.com/zrepl/zrepl/daemon"
|
||||||
@@ -10,7 +13,7 @@ import (
|
|||||||
var SignalCmd = &cli.Subcommand{
|
var SignalCmd = &cli.Subcommand{
|
||||||
Use: "signal [wakeup|reset] JOB",
|
Use: "signal [wakeup|reset] JOB",
|
||||||
Short: "wake up a job from wait state or abort its current invocation",
|
Short: "wake up a job from wait state or abort its current invocation",
|
||||||
Run: func(subcommand *cli.Subcommand, args []string) error {
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
return runSignalCmd(subcommand.Config(), args)
|
return runSignalCmd(subcommand.Config(), args)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -28,10 +31,10 @@ func runSignalCmd(config *config.Config, args []string) error {
|
|||||||
err = jsonRequestResponse(httpc, daemon.ControlJobEndpointSignal,
|
err = jsonRequestResponse(httpc, daemon.ControlJobEndpointSignal,
|
||||||
struct {
|
struct {
|
||||||
Name string
|
Name string
|
||||||
Op string
|
Op string
|
||||||
}{
|
}{
|
||||||
Name: args[1],
|
Name: args[1],
|
||||||
Op: args[0],
|
Op: args[0],
|
||||||
},
|
},
|
||||||
struct{}{},
|
struct{}{},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,641 +0,0 @@
|
|||||||
package client
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"github.com/gdamore/tcell/termbox"
|
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/spf13/pflag"
|
|
||||||
"github.com/zrepl/yaml-config"
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
|
||||||
"github.com/zrepl/zrepl/daemon"
|
|
||||||
"github.com/zrepl/zrepl/daemon/job"
|
|
||||||
"github.com/zrepl/zrepl/daemon/pruner"
|
|
||||||
"github.com/zrepl/zrepl/replication/report"
|
|
||||||
"io"
|
|
||||||
"math"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type byteProgressMeasurement struct {
|
|
||||||
time time.Time
|
|
||||||
val int64
|
|
||||||
}
|
|
||||||
|
|
||||||
type bytesProgressHistory struct {
|
|
||||||
last *byteProgressMeasurement // pointer as poor man's optional
|
|
||||||
changeCount int
|
|
||||||
lastChange time.Time
|
|
||||||
bpsAvg float64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *bytesProgressHistory) Update(currentVal int64) (bytesPerSecondAvg int64, changeCount int) {
|
|
||||||
|
|
||||||
if p.last == nil {
|
|
||||||
p.last = &byteProgressMeasurement{
|
|
||||||
time: time.Now(),
|
|
||||||
val: currentVal,
|
|
||||||
}
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
if p.last.val != currentVal {
|
|
||||||
p.changeCount++
|
|
||||||
p.lastChange = time.Now()
|
|
||||||
}
|
|
||||||
|
|
||||||
if time.Now().Sub(p.lastChange) > 3 * time.Second {
|
|
||||||
p.last = nil
|
|
||||||
return 0, 0
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
deltaV := currentVal - p.last.val;
|
|
||||||
deltaT := time.Now().Sub(p.last.time)
|
|
||||||
rate := float64(deltaV) / deltaT.Seconds()
|
|
||||||
|
|
||||||
factor := 0.3
|
|
||||||
p.bpsAvg = (1-factor) * p.bpsAvg + factor * rate
|
|
||||||
|
|
||||||
p.last.time = time.Now()
|
|
||||||
p.last.val = currentVal
|
|
||||||
|
|
||||||
return int64(p.bpsAvg), p.changeCount
|
|
||||||
}
|
|
||||||
|
|
||||||
type tui struct {
|
|
||||||
x, y int
|
|
||||||
indent int
|
|
||||||
|
|
||||||
lock sync.Mutex //For report and error
|
|
||||||
report map[string]job.Status
|
|
||||||
err error
|
|
||||||
|
|
||||||
replicationProgress map[string]*bytesProgressHistory // by job name
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTui() tui {
|
|
||||||
return tui{
|
|
||||||
replicationProgress: make(map[string]*bytesProgressHistory, 0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) moveCursor(x, y int) {
|
|
||||||
t.x += x
|
|
||||||
t.y += y
|
|
||||||
}
|
|
||||||
|
|
||||||
const INDENT_MULTIPLIER = 4
|
|
||||||
|
|
||||||
func (t *tui) moveLine(dl int, col int) {
|
|
||||||
t.y += dl
|
|
||||||
t.x = t.indent*INDENT_MULTIPLIER + col
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) write(text string) {
|
|
||||||
for _, c := range text {
|
|
||||||
if c == '\n' {
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
termbox.SetCell(t.x, t.y, c, termbox.ColorDefault, termbox.ColorDefault)
|
|
||||||
t.x += 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) printf(text string, a ...interface{}) {
|
|
||||||
t.write(fmt.Sprintf(text, a...))
|
|
||||||
}
|
|
||||||
|
|
||||||
func wrap(s string, width int) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for len(s) > 0 {
|
|
||||||
rem := width
|
|
||||||
if rem > len(s) {
|
|
||||||
rem = len(s)
|
|
||||||
}
|
|
||||||
if idx := strings.IndexAny(s, "\n\r"); idx != -1 && idx < rem {
|
|
||||||
rem = idx+1
|
|
||||||
}
|
|
||||||
untilNewline := strings.TrimRight(s[:rem], "\n\r")
|
|
||||||
s = s[rem:]
|
|
||||||
if len(untilNewline) == 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b.WriteString(untilNewline)
|
|
||||||
b.WriteString("\n")
|
|
||||||
}
|
|
||||||
return strings.TrimRight(b.String(), "\n\r")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) printfDrawIndentedAndWrappedIfMultiline(format string, a ...interface{}) {
|
|
||||||
whole := fmt.Sprintf(format, a...)
|
|
||||||
width, _ := termbox.Size()
|
|
||||||
if !strings.ContainsAny(whole, "\n\r") && t.x + len(whole) <= width {
|
|
||||||
t.printf(format, a...)
|
|
||||||
} else {
|
|
||||||
t.addIndent(1)
|
|
||||||
t.newline()
|
|
||||||
t.write(wrap(whole, width - INDENT_MULTIPLIER*t.indent))
|
|
||||||
t.addIndent(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) newline() {
|
|
||||||
t.moveLine(1, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) setIndent(indent int) {
|
|
||||||
t.indent = indent
|
|
||||||
t.moveLine(0, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) addIndent(indent int) {
|
|
||||||
t.indent += indent
|
|
||||||
t.moveLine(0, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
var statusFlags struct {
|
|
||||||
Raw bool
|
|
||||||
}
|
|
||||||
|
|
||||||
var StatusCmd = &cli.Subcommand{
|
|
||||||
Use: "status",
|
|
||||||
Short: "show job activity or dump as JSON for monitoring",
|
|
||||||
SetupFlags: func(f *pflag.FlagSet) {
|
|
||||||
f.BoolVar(&statusFlags.Raw, "raw", false, "dump raw status description from zrepl daemon")
|
|
||||||
},
|
|
||||||
Run: runStatus,
|
|
||||||
}
|
|
||||||
|
|
||||||
func runStatus(s *cli.Subcommand, args []string) error {
|
|
||||||
httpc, err := controlHttpClient(s.Config().Global.Control.SockPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if statusFlags.Raw {
|
|
||||||
resp, err := httpc.Get("http://unix"+daemon.ControlJobEndpointStatus)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
fmt.Fprintf(os.Stderr, "Received error response:\n")
|
|
||||||
io.CopyN(os.Stderr, resp.Body, 4096)
|
|
||||||
return errors.Errorf("exit")
|
|
||||||
}
|
|
||||||
if _, err := io.Copy(os.Stdout, resp.Body); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
t := newTui()
|
|
||||||
t.lock.Lock()
|
|
||||||
t.err = errors.New("Got no report yet")
|
|
||||||
t.lock.Unlock()
|
|
||||||
|
|
||||||
err = termbox.Init()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer termbox.Close()
|
|
||||||
|
|
||||||
update := func() {
|
|
||||||
m := make(map[string]job.Status)
|
|
||||||
|
|
||||||
err2 := jsonRequestResponse(httpc, daemon.ControlJobEndpointStatus,
|
|
||||||
struct{}{},
|
|
||||||
&m,
|
|
||||||
)
|
|
||||||
|
|
||||||
t.lock.Lock()
|
|
||||||
t.err = err2
|
|
||||||
t.report = m
|
|
||||||
t.lock.Unlock()
|
|
||||||
t.draw()
|
|
||||||
}
|
|
||||||
update()
|
|
||||||
|
|
||||||
ticker := time.NewTicker(500 * time.Millisecond)
|
|
||||||
defer ticker.Stop()
|
|
||||||
go func() {
|
|
||||||
for _ = range ticker.C {
|
|
||||||
update()
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
termbox.HideCursor()
|
|
||||||
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
|
|
||||||
|
|
||||||
loop:
|
|
||||||
for {
|
|
||||||
switch ev := termbox.PollEvent(); ev.Type {
|
|
||||||
case termbox.EventKey:
|
|
||||||
switch ev.Key {
|
|
||||||
case termbox.KeyEsc:
|
|
||||||
break loop
|
|
||||||
case termbox.KeyCtrlC:
|
|
||||||
break loop
|
|
||||||
}
|
|
||||||
case termbox.EventResize:
|
|
||||||
t.draw()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) getReplicationProgresHistory(jobName string) *bytesProgressHistory {
|
|
||||||
p, ok := t.replicationProgress[jobName]
|
|
||||||
if !ok {
|
|
||||||
p = &bytesProgressHistory{}
|
|
||||||
t.replicationProgress[jobName] = p
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) draw() {
|
|
||||||
t.lock.Lock()
|
|
||||||
defer t.lock.Unlock()
|
|
||||||
|
|
||||||
termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
|
|
||||||
t.x = 0
|
|
||||||
t.y = 0
|
|
||||||
t.indent = 0
|
|
||||||
|
|
||||||
if t.err != nil {
|
|
||||||
t.write(t.err.Error())
|
|
||||||
} else {
|
|
||||||
//Iterate over map in alphabetical order
|
|
||||||
keys := make([]string, len(t.report))
|
|
||||||
i := 0
|
|
||||||
for k, _ := range t.report {
|
|
||||||
keys[i] = k
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
sort.Strings(keys)
|
|
||||||
|
|
||||||
for _, k := range keys {
|
|
||||||
v := t.report[k]
|
|
||||||
if len(k) == 0 || daemon.IsInternalJobName(k) { //Internal job
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
t.setIndent(0)
|
|
||||||
|
|
||||||
t.printf("Job: %s", k)
|
|
||||||
t.setIndent(1)
|
|
||||||
t.newline()
|
|
||||||
t.printf("Type: %s", v.Type)
|
|
||||||
t.setIndent(1)
|
|
||||||
t.newline()
|
|
||||||
|
|
||||||
if v.Type == job.TypePush || v.Type == job.TypePull {
|
|
||||||
activeStatus, ok := v.JobSpecific.(*job.ActiveSideStatus)
|
|
||||||
if !ok || activeStatus == nil {
|
|
||||||
t.printf("ActiveSideStatus is null")
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
t.printf("Replication:")
|
|
||||||
t.newline()
|
|
||||||
t.addIndent(1)
|
|
||||||
t.renderReplicationReport(activeStatus.Replication, t.getReplicationProgresHistory(k))
|
|
||||||
t.addIndent(-1)
|
|
||||||
|
|
||||||
t.printf("Pruning Sender:")
|
|
||||||
t.newline()
|
|
||||||
t.addIndent(1)
|
|
||||||
t.renderPrunerReport(activeStatus.PruningSender)
|
|
||||||
t.addIndent(-1)
|
|
||||||
|
|
||||||
t.printf("Pruning Receiver:")
|
|
||||||
t.newline()
|
|
||||||
t.addIndent(1)
|
|
||||||
t.renderPrunerReport(activeStatus.PruningReceiver)
|
|
||||||
t.addIndent(-1)
|
|
||||||
} else if v.Type == job.TypeSnap {
|
|
||||||
snapStatus, ok := v.JobSpecific.(*job.SnapJobStatus)
|
|
||||||
if !ok || snapStatus == nil {
|
|
||||||
t.printf("SnapJobStatus is null")
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
t.printf("Pruning snapshots:")
|
|
||||||
t.newline()
|
|
||||||
t.addIndent(1)
|
|
||||||
t.renderPrunerReport(snapStatus.Pruning)
|
|
||||||
t.addIndent(-1)
|
|
||||||
} else {
|
|
||||||
t.printf("No status representation for job type '%s', dumping as YAML", v.Type)
|
|
||||||
t.newline()
|
|
||||||
asYaml, err := yaml.Marshal(v.JobSpecific)
|
|
||||||
if err != nil {
|
|
||||||
t.printf("Error marshaling status to YAML: %s", err)
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
t.write(string(asYaml))
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
termbox.Flush()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) renderReplicationReport(rep *report.Report, history *bytesProgressHistory) {
|
|
||||||
if rep == nil {
|
|
||||||
t.printf("...\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if rep.WaitReconnectError != nil {
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("Connectivity: %s", rep.WaitReconnectError)
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
if !rep.WaitReconnectSince.IsZero() {
|
|
||||||
delta := rep.WaitReconnectUntil.Sub(time.Now()).Round(time.Second)
|
|
||||||
if rep.WaitReconnectUntil.IsZero() || delta > 0 {
|
|
||||||
var until string
|
|
||||||
if rep.WaitReconnectUntil.IsZero() {
|
|
||||||
until = "waiting indefinitely"
|
|
||||||
} else {
|
|
||||||
until = fmt.Sprintf("hard fail in %s @ %s", delta, rep.WaitReconnectUntil)
|
|
||||||
}
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("Connectivity: reconnecting with exponential backoff (since %s) (%s)",
|
|
||||||
rep.WaitReconnectSince, until)
|
|
||||||
} else {
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("Connectivity: reconnects reached hard-fail timeout @ %s", rep.WaitReconnectUntil)
|
|
||||||
}
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO visualize more than the latest attempt by folding all attempts into one
|
|
||||||
if len(rep.Attempts) == 0 {
|
|
||||||
t.printf("no attempts made yet")
|
|
||||||
return
|
|
||||||
} else {
|
|
||||||
t.printf("Attempt #%d", len(rep.Attempts))
|
|
||||||
if len(rep.Attempts) > 1 {
|
|
||||||
t.printf(". Previous attempts failed with the follwing statuses:")
|
|
||||||
t.newline()
|
|
||||||
t.addIndent(1)
|
|
||||||
for i, a := range rep.Attempts[:len(rep.Attempts)-1] {
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("#%d: %s (failed at %s) (ran %s)", i + 1, a.State, a.FinishAt, a.FinishAt.Sub(a.StartAt))
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
t.addIndent(-1)
|
|
||||||
} else {
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
latest := rep.Attempts[len(rep.Attempts)-1]
|
|
||||||
sort.Slice(latest.Filesystems, func(i, j int) bool {
|
|
||||||
return latest.Filesystems[i].Info.Name < latest.Filesystems[j].Info.Name
|
|
||||||
})
|
|
||||||
|
|
||||||
t.printf("Status: %s", latest.State)
|
|
||||||
t.newline()
|
|
||||||
if latest.State == report.AttemptPlanningError {
|
|
||||||
t.printf("Problem: ")
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("%s", latest.PlanError)
|
|
||||||
t.newline()
|
|
||||||
} else if latest.State == report.AttemptFanOutError {
|
|
||||||
t.printf("Problem: one or more of the filesystems encountered errors")
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
|
|
||||||
if latest.State != report.AttemptPlanning && latest.State != report.AttemptPlanningError {
|
|
||||||
// Draw global progress bar
|
|
||||||
// Progress: [---------------]
|
|
||||||
expected, replicated := latest.BytesSum()
|
|
||||||
rate, changeCount := history.Update(replicated)
|
|
||||||
t.write("Progress: ")
|
|
||||||
t.drawBar(50, replicated, expected, changeCount)
|
|
||||||
t.write(fmt.Sprintf(" %s / %s @ %s/s", ByteCountBinary(replicated), ByteCountBinary(expected), ByteCountBinary(rate)))
|
|
||||||
t.newline()
|
|
||||||
|
|
||||||
var maxFSLen int
|
|
||||||
for _, fs := range latest.Filesystems {
|
|
||||||
if len(fs.Info.Name) > maxFSLen {
|
|
||||||
maxFSLen = len(fs.Info.Name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, fs := range latest.Filesystems {
|
|
||||||
t.printFilesystemStatus(fs, false, maxFSLen) // FIXME bring 'active' flag back
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) renderPrunerReport(r *pruner.Report) {
|
|
||||||
if r == nil {
|
|
||||||
t.printf("...\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
state, err := pruner.StateString(r.State)
|
|
||||||
if err != nil {
|
|
||||||
t.printf("Status: %q (parse error: %q)\n", r.State, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
t.printf("Status: %s", state)
|
|
||||||
t.newline()
|
|
||||||
|
|
||||||
if r.Error != "" {
|
|
||||||
t.printf("Error: %s\n", r.Error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type commonFS struct {
|
|
||||||
*pruner.FSReport
|
|
||||||
completed bool
|
|
||||||
}
|
|
||||||
all := make([]commonFS, 0, len(r.Pending) + len(r.Completed))
|
|
||||||
for i := range r.Pending {
|
|
||||||
all = append(all, commonFS{&r.Pending[i], false})
|
|
||||||
}
|
|
||||||
for i := range r.Completed {
|
|
||||||
all = append(all, commonFS{&r.Completed[i], true})
|
|
||||||
}
|
|
||||||
|
|
||||||
switch state {
|
|
||||||
case pruner.Plan: fallthrough
|
|
||||||
case pruner.PlanErr:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(all) == 0 {
|
|
||||||
t.printf("nothing to do\n")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var totalDestroyCount, completedDestroyCount int
|
|
||||||
var maxFSname int
|
|
||||||
for _, fs := range all {
|
|
||||||
totalDestroyCount += len(fs.DestroyList)
|
|
||||||
if fs.completed {
|
|
||||||
completedDestroyCount += len(fs.DestroyList)
|
|
||||||
}
|
|
||||||
if maxFSname < len(fs.Filesystem) {
|
|
||||||
maxFSname = len(fs.Filesystem)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// global progress bar
|
|
||||||
progress := int(math.Round(80 * float64(completedDestroyCount) / float64(totalDestroyCount)))
|
|
||||||
t.write("Progress: ")
|
|
||||||
t.write("[")
|
|
||||||
t.write(times("=", progress))
|
|
||||||
t.write(">")
|
|
||||||
t.write(times("-", 80 - progress))
|
|
||||||
t.write("]")
|
|
||||||
t.printf(" %d/%d snapshots", completedDestroyCount, totalDestroyCount)
|
|
||||||
t.newline()
|
|
||||||
|
|
||||||
sort.SliceStable(all, func(i, j int) bool {
|
|
||||||
return strings.Compare(all[i].Filesystem, all[j].Filesystem) == -1
|
|
||||||
})
|
|
||||||
|
|
||||||
// Draw a table-like representation of 'all'
|
|
||||||
for _, fs := range all {
|
|
||||||
t.write(rightPad(fs.Filesystem, maxFSname, " "))
|
|
||||||
t.write(" ")
|
|
||||||
if !fs.SkipReason.NotSkipped() {
|
|
||||||
t.printf("skipped: %s\n", fs.SkipReason)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if fs.LastError != "" {
|
|
||||||
if strings.ContainsAny(fs.LastError, "\r\n") {
|
|
||||||
t.printf("ERROR:")
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("%s\n", fs.LastError)
|
|
||||||
} else {
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("ERROR: %s\n", fs.LastError)
|
|
||||||
}
|
|
||||||
t.newline()
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
pruneRuleActionStr := fmt.Sprintf("(destroy %d of %d snapshots)",
|
|
||||||
len(fs.DestroyList), len(fs.SnapshotList))
|
|
||||||
|
|
||||||
if fs.completed {
|
|
||||||
t.printf( "Completed %s\n", pruneRuleActionStr)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
t.write("Pending ") // whitespace is padding 10
|
|
||||||
if len(fs.DestroyList) == 1 {
|
|
||||||
t.write(fs.DestroyList[0].Name)
|
|
||||||
} else {
|
|
||||||
t.write(pruneRuleActionStr)
|
|
||||||
}
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func times(str string, n int) (out string) {
|
|
||||||
for i := 0; i < n; i++ {
|
|
||||||
out += str
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func rightPad(str string, length int, pad string) string {
|
|
||||||
if len(str) > length {
|
|
||||||
return str[:length]
|
|
||||||
}
|
|
||||||
return str + times(pad, length-len(str))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
func leftPad(str string, length int, pad string) string {
|
|
||||||
if len(str) > length {
|
|
||||||
return str[len(str)-length:]
|
|
||||||
}
|
|
||||||
return times(pad, length-len(str)) + str
|
|
||||||
}
|
|
||||||
|
|
||||||
var arrowPositions = `>\|/`
|
|
||||||
|
|
||||||
// changeCount = 0 indicates stall / no progresss
|
|
||||||
func (t *tui) drawBar(length int, bytes, totalBytes int64, changeCount int) {
|
|
||||||
var completedLength int
|
|
||||||
if totalBytes > 0 {
|
|
||||||
completedLength = int(int64(length) * bytes / totalBytes)
|
|
||||||
if completedLength > length {
|
|
||||||
completedLength = length
|
|
||||||
}
|
|
||||||
} else if totalBytes == bytes {
|
|
||||||
completedLength = length
|
|
||||||
}
|
|
||||||
|
|
||||||
t.write("[")
|
|
||||||
t.write(times("=", completedLength))
|
|
||||||
t.write( string(arrowPositions[changeCount%len(arrowPositions)]))
|
|
||||||
t.write(times("-", length-completedLength))
|
|
||||||
t.write("]")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *tui) printFilesystemStatus(rep *report.FilesystemReport, active bool, maxFS int) {
|
|
||||||
|
|
||||||
expected, replicated := rep.BytesSum()
|
|
||||||
status := fmt.Sprintf("%s (step %d/%d, %s/%s)",
|
|
||||||
strings.ToUpper(string(rep.State)),
|
|
||||||
rep.CurrentStep, len(rep.Steps),
|
|
||||||
ByteCountBinary(replicated), ByteCountBinary(expected),
|
|
||||||
)
|
|
||||||
|
|
||||||
activeIndicator := " "
|
|
||||||
if active {
|
|
||||||
activeIndicator = "*"
|
|
||||||
}
|
|
||||||
t.printf("%s %s %s ",
|
|
||||||
activeIndicator,
|
|
||||||
rightPad(rep.Info.Name, maxFS, " "),
|
|
||||||
status)
|
|
||||||
|
|
||||||
next := ""
|
|
||||||
if err := rep.Error(); err != nil {
|
|
||||||
next = err.Err
|
|
||||||
} else if rep.State != report.FilesystemDone {
|
|
||||||
if nextStep := rep.NextStep(); nextStep != nil {
|
|
||||||
if nextStep.IsIncremental() {
|
|
||||||
next = fmt.Sprintf("next: %s => %s", nextStep.Info.From, nextStep.Info.To)
|
|
||||||
} else {
|
|
||||||
next = fmt.Sprintf("next: %s (full)", nextStep.Info.To)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
next = "" // individual FSes may still be in planning state
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
t.printfDrawIndentedAndWrappedIfMultiline("%s", next)
|
|
||||||
|
|
||||||
t.newline()
|
|
||||||
}
|
|
||||||
|
|
||||||
func ByteCountBinary(b int64) string {
|
|
||||||
const unit = 1024
|
|
||||||
if b < unit {
|
|
||||||
return fmt.Sprintf("%d B", b)
|
|
||||||
}
|
|
||||||
div, exp := int64(unit), 0
|
|
||||||
for n := b / unit; n >= unit; n /= unit {
|
|
||||||
div *= unit
|
|
||||||
exp++
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
h *http.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(network, addr string) (*Client, error) {
|
||||||
|
httpc, err := makeControlHttpClient(func(_ context.Context) (net.Conn, error) { return net.Dial(network, addr) })
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Client{httpc}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Status() (s daemon.Status, _ error) {
|
||||||
|
err := jsonRequestResponse(c.h, daemon.ControlJobEndpointStatus,
|
||||||
|
struct{}{},
|
||||||
|
&s,
|
||||||
|
)
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) StatusRaw() ([]byte, error) {
|
||||||
|
var r json.RawMessage
|
||||||
|
err := jsonRequestResponse(c.h, daemon.ControlJobEndpointStatus, struct{}{}, &r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) signal(job, sig string) error {
|
||||||
|
return jsonRequestResponse(c.h, daemon.ControlJobEndpointSignal,
|
||||||
|
struct {
|
||||||
|
Name string
|
||||||
|
Op string
|
||||||
|
}{
|
||||||
|
Name: job,
|
||||||
|
Op: sig,
|
||||||
|
},
|
||||||
|
struct{}{},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) SignalWakeup(job string) error {
|
||||||
|
return c.signal(job, "wakeup")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) SignalReset(job string) error {
|
||||||
|
return c.signal(job, "reset")
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeControlHttpClient(dialfunc func(context.Context) (net.Conn, error)) (client *http.Client, err error) {
|
||||||
|
return &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||||
|
return dialfunc(ctx)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func jsonRequestResponse(c *http.Client, endpoint string, req interface{}, res interface{}) error {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
encodeErr := json.NewEncoder(&buf).Encode(req)
|
||||||
|
if encodeErr != nil {
|
||||||
|
return encodeErr
|
||||||
|
}
|
||||||
|
|
||||||
|
hreq, err := http.NewRequest("POST", "http://unix"+endpoint, &buf)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
hreq.Header.Set("Content-Type", "application/json")
|
||||||
|
// Prevent EOF errors when client request frequency and server keepalive close are at the same time.
|
||||||
|
// Found this by watching http.Server.ConnState changes, then found
|
||||||
|
// https://stackoverflow.com/questions/17714494/golang-http-request-results-in-eof-errors-when-making-multiple-requests-successi
|
||||||
|
// Note: The issue seems even more prounounced with local TCP sockets than unix domain sockets. So, I used that for debugging.
|
||||||
|
hreq.Close = true
|
||||||
|
resp, err := c.Do(hreq)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
var msg bytes.Buffer
|
||||||
|
_, _ = io.CopyN(&msg, resp.Body, 4096) // ignore error, just display what we got
|
||||||
|
return errors.Errorf("%s", msg.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
decodeError := json.NewDecoder(resp.Body).Decode(&res)
|
||||||
|
if decodeError != nil {
|
||||||
|
return decodeError
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package status
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/mattn/go-isatty"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/client/status/client"
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon"
|
||||||
|
"github.com/zrepl/zrepl/util/choices"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Client interface {
|
||||||
|
Status() (daemon.Status, error)
|
||||||
|
StatusRaw() ([]byte, error)
|
||||||
|
SignalWakeup(job string) error
|
||||||
|
SignalReset(job string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type statusFlags struct {
|
||||||
|
Mode choices.Choices
|
||||||
|
Job string
|
||||||
|
Delay time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
var statusv2Flags statusFlags
|
||||||
|
|
||||||
|
type statusv2Mode int
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusV2ModeInteractive statusv2Mode = 1 + iota
|
||||||
|
StatusV2ModeDump
|
||||||
|
StatusV2ModeRaw
|
||||||
|
StatusV2ModeLegacy
|
||||||
|
)
|
||||||
|
|
||||||
|
var Subcommand = &cli.Subcommand{
|
||||||
|
Use: "status",
|
||||||
|
Short: "retrieve & display daemon status information",
|
||||||
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
|
statusv2Flags.Mode.Init(
|
||||||
|
"interactive", StatusV2ModeInteractive,
|
||||||
|
"dump", StatusV2ModeDump,
|
||||||
|
"raw", StatusV2ModeRaw,
|
||||||
|
"legacy", StatusV2ModeLegacy,
|
||||||
|
)
|
||||||
|
statusv2Flags.Mode.SetTypeString("mode")
|
||||||
|
statusv2Flags.Mode.SetDefaultValue(StatusV2ModeInteractive)
|
||||||
|
f.Var(&statusv2Flags.Mode, "mode", statusv2Flags.Mode.Usage())
|
||||||
|
f.StringVar(&statusv2Flags.Job, "job", "", "only show specified job (works in \"dump\" and \"interactive\" mode)")
|
||||||
|
f.DurationVarP(&statusv2Flags.Delay, "delay", "d", 1*time.Second, "use -d 3s for 3 seconds delay (minimum delay is 1s)")
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
return runStatusV2Command(ctx, subcommand.Config(), args)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func runStatusV2Command(ctx context.Context, config *config.Config, args []string) error {
|
||||||
|
|
||||||
|
c, err := client.New("unix", config.Global.Control.SockPath)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "connect to daemon socket at %q", config.Global.Control.SockPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
mode := statusv2Flags.Mode.Value().(statusv2Mode)
|
||||||
|
|
||||||
|
if !isatty.IsTerminal(os.Stdout.Fd()) && mode != StatusV2ModeDump && mode != StatusV2ModeRaw {
|
||||||
|
dumpmode, err := statusv2Flags.Mode.InputForChoice(StatusV2ModeDump)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
rawmode, err := statusv2Flags.Mode.InputForChoice(StatusV2ModeRaw)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return errors.Errorf("error: stdout is not a tty, please use --mode %s or --mode %s", dumpmode, rawmode)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch mode {
|
||||||
|
case StatusV2ModeInteractive:
|
||||||
|
return interactive(c, statusv2Flags)
|
||||||
|
case StatusV2ModeDump:
|
||||||
|
return dump(c, statusv2Flags.Job)
|
||||||
|
case StatusV2ModeRaw:
|
||||||
|
return raw(c)
|
||||||
|
case StatusV2ModeLegacy:
|
||||||
|
return legacy(c, statusv2Flags)
|
||||||
|
default:
|
||||||
|
panic("unreachable")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package status
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell"
|
||||||
|
"github.com/mattn/go-isatty"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/client/status/viewmodel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func dump(c Client, job string) error {
|
||||||
|
s, err := c.Status()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if job != "" {
|
||||||
|
if _, ok := s.Jobs[job]; !ok {
|
||||||
|
return errors.Errorf("job %q not found", job)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
width := (1 << 31) - 1
|
||||||
|
wrap := false
|
||||||
|
hline := strings.Repeat("-", 80)
|
||||||
|
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||||
|
wrap = true
|
||||||
|
screen, err := tcell.NewScreen()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "get terminal dimensions")
|
||||||
|
}
|
||||||
|
if err := screen.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "init screen")
|
||||||
|
}
|
||||||
|
width, _ = screen.Size()
|
||||||
|
screen.Fini()
|
||||||
|
hline = strings.Repeat("-", width)
|
||||||
|
}
|
||||||
|
|
||||||
|
m := viewmodel.New()
|
||||||
|
params := viewmodel.Params{
|
||||||
|
Report: s.Jobs,
|
||||||
|
ReportFetchError: nil,
|
||||||
|
SelectedJob: nil,
|
||||||
|
FSFilter: func(s string) bool { return true },
|
||||||
|
DetailViewWidth: width,
|
||||||
|
DetailViewWrap: wrap,
|
||||||
|
ShortKeybindingOverview: "",
|
||||||
|
}
|
||||||
|
m.Update(params)
|
||||||
|
for _, j := range m.Jobs() {
|
||||||
|
if job != "" && j.Name() != job {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
params.SelectedJob = j
|
||||||
|
m.Update(params)
|
||||||
|
fmt.Println(m.SelectedJob().FullDescription())
|
||||||
|
if job != "" {
|
||||||
|
return nil
|
||||||
|
} else {
|
||||||
|
fmt.Println(hline)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,347 @@
|
|||||||
|
package status
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
tview "gitlab.com/tslocum/cview"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/client/status/viewmodel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func interactive(c Client, flag statusFlags) error {
|
||||||
|
|
||||||
|
// Set this so we don't overwrite the default terminal colors
|
||||||
|
// See https://github.com/rivo/tview/blob/master/styles.go
|
||||||
|
tview.Styles.PrimitiveBackgroundColor = tcell.ColorDefault
|
||||||
|
tview.Styles.ContrastBackgroundColor = tcell.ColorDefault
|
||||||
|
tview.Styles.PrimaryTextColor = tcell.ColorDefault
|
||||||
|
tview.Styles.BorderColor = tcell.ColorDefault
|
||||||
|
app := tview.NewApplication()
|
||||||
|
|
||||||
|
jobDetailSplit := tview.NewFlex()
|
||||||
|
jobMenu := tview.NewTreeView()
|
||||||
|
jobMenuRoot := tview.NewTreeNode("jobs")
|
||||||
|
jobMenuRoot.SetSelectable(true)
|
||||||
|
jobMenu.SetRoot(jobMenuRoot)
|
||||||
|
jobMenu.SetCurrentNode(jobMenuRoot)
|
||||||
|
jobMenu.SetSelectedTextColor(tcell.ColorGreen)
|
||||||
|
jobTextDetail := tview.NewTextView()
|
||||||
|
jobTextDetail.SetWrap(false)
|
||||||
|
|
||||||
|
jobMenu.SetBorder(true)
|
||||||
|
jobTextDetail.SetBorder(true)
|
||||||
|
|
||||||
|
toolbarSplit := tview.NewFlex()
|
||||||
|
toolbarSplit.SetDirection(tview.FlexRow)
|
||||||
|
inputBarContainer := tview.NewFlex()
|
||||||
|
fsFilterInput := tview.NewInputField()
|
||||||
|
fsFilterInput.SetBorder(false)
|
||||||
|
fsFilterInput.SetFieldBackgroundColor(tcell.ColorDefault)
|
||||||
|
inputBarLabel := tview.NewTextView()
|
||||||
|
inputBarLabel.SetText("[::b]FILTER ")
|
||||||
|
inputBarLabel.SetDynamicColors(true)
|
||||||
|
inputBarContainer.AddItem(inputBarLabel, 7, 1, false)
|
||||||
|
inputBarContainer.AddItem(fsFilterInput, 0, 10, false)
|
||||||
|
toolbarSplit.AddItem(inputBarContainer, 1, 0, false)
|
||||||
|
toolbarSplit.AddItem(jobDetailSplit, 0, 10, false)
|
||||||
|
|
||||||
|
bottombar := tview.NewFlex()
|
||||||
|
bottombar.SetDirection(tview.FlexColumn)
|
||||||
|
bottombarDateView := tview.NewTextView()
|
||||||
|
bottombar.AddItem(bottombarDateView, len(time.Now().String()), 0, false)
|
||||||
|
bottomBarStatus := tview.NewTextView()
|
||||||
|
bottomBarStatus.SetDynamicColors(true)
|
||||||
|
bottomBarStatus.SetTextAlign(tview.AlignRight)
|
||||||
|
bottombar.AddItem(bottomBarStatus, 0, 10, false)
|
||||||
|
toolbarSplit.AddItem(bottombar, 1, 0, false)
|
||||||
|
|
||||||
|
tabbableWithJobMenu := []tview.Primitive{jobMenu, jobTextDetail, fsFilterInput}
|
||||||
|
tabbableWithoutJobMenu := []tview.Primitive{jobTextDetail, fsFilterInput}
|
||||||
|
var tabbable []tview.Primitive
|
||||||
|
tabbableActiveIndex := 0
|
||||||
|
tabbableRedraw := func() {
|
||||||
|
if len(tabbable) == 0 {
|
||||||
|
app.SetFocus(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tabbableActiveIndex >= len(tabbable) {
|
||||||
|
app.SetFocus(tabbable[0])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
app.SetFocus(tabbable[tabbableActiveIndex])
|
||||||
|
}
|
||||||
|
tabbableCycle := func() {
|
||||||
|
if len(tabbable) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
tabbableActiveIndex = (tabbableActiveIndex + 1) % len(tabbable)
|
||||||
|
app.SetFocus(tabbable[tabbableActiveIndex])
|
||||||
|
tabbableRedraw()
|
||||||
|
}
|
||||||
|
|
||||||
|
jobMenuVisisble := false
|
||||||
|
reconfigureJobDetailSplit := func(setJobMenuVisible bool) {
|
||||||
|
if jobMenuVisisble == setJobMenuVisible {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
jobMenuVisisble = setJobMenuVisible
|
||||||
|
if setJobMenuVisible {
|
||||||
|
jobDetailSplit.RemoveItem(jobTextDetail)
|
||||||
|
jobDetailSplit.AddItem(jobMenu, 0, 1, true)
|
||||||
|
jobDetailSplit.AddItem(jobTextDetail, 0, 5, false)
|
||||||
|
tabbable = tabbableWithJobMenu
|
||||||
|
} else {
|
||||||
|
jobDetailSplit.RemoveItem(jobMenu)
|
||||||
|
tabbable = tabbableWithoutJobMenu
|
||||||
|
}
|
||||||
|
tabbableRedraw()
|
||||||
|
}
|
||||||
|
|
||||||
|
showModal := func(m *tview.Modal, modalDoneFunc func(idx int, label string)) {
|
||||||
|
preModalFocus := app.GetFocus()
|
||||||
|
m.SetDoneFunc(func(idx int, label string) {
|
||||||
|
if modalDoneFunc != nil {
|
||||||
|
modalDoneFunc(idx, label)
|
||||||
|
}
|
||||||
|
app.SetRoot(toolbarSplit, true)
|
||||||
|
app.SetFocus(preModalFocus)
|
||||||
|
app.Draw()
|
||||||
|
})
|
||||||
|
app.SetRoot(m, true)
|
||||||
|
app.Draw()
|
||||||
|
}
|
||||||
|
|
||||||
|
app.SetRoot(toolbarSplit, true)
|
||||||
|
// initial focus
|
||||||
|
tabbableActiveIndex = len(tabbable)
|
||||||
|
tabbableCycle()
|
||||||
|
reconfigureJobDetailSplit(true)
|
||||||
|
|
||||||
|
m := viewmodel.New()
|
||||||
|
params := &viewmodel.Params{
|
||||||
|
Report: nil,
|
||||||
|
SelectedJob: nil,
|
||||||
|
FSFilter: func(_ string) bool { return true },
|
||||||
|
DetailViewWidth: 100,
|
||||||
|
DetailViewWrap: false,
|
||||||
|
ShortKeybindingOverview: "[::b]Q[::-] quit [::b]<TAB>[::-] switch panes [::b]W[::-] wrap lines [::b]Shift+M[::-] toggle navbar [::b]Shift+S[::-] signal job [::b]</>[::-] filter filesystems",
|
||||||
|
}
|
||||||
|
paramsMtx := &sync.Mutex{}
|
||||||
|
var redraw func()
|
||||||
|
viewmodelupdate := func(cb func(*viewmodel.Params)) {
|
||||||
|
paramsMtx.Lock()
|
||||||
|
defer paramsMtx.Unlock()
|
||||||
|
cb(params)
|
||||||
|
m.Update(*params)
|
||||||
|
}
|
||||||
|
redraw = func() {
|
||||||
|
jobs := m.Jobs()
|
||||||
|
if flag.Job != "" {
|
||||||
|
job_found := false
|
||||||
|
for _, job := range jobs {
|
||||||
|
if strings.Compare(flag.Job, job.Name()) == 0 {
|
||||||
|
jobs = []*viewmodel.Job{job}
|
||||||
|
job_found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !job_found {
|
||||||
|
jobs = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
redrawJobsList := false
|
||||||
|
var selectedJobN *tview.TreeNode
|
||||||
|
if len(jobMenuRoot.GetChildren()) == len(jobs) {
|
||||||
|
for i, jobN := range jobMenuRoot.GetChildren() {
|
||||||
|
if jobN.GetReference().(*viewmodel.Job) != jobs[i] {
|
||||||
|
redrawJobsList = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if jobN.GetReference().(*viewmodel.Job) == m.SelectedJob() {
|
||||||
|
selectedJobN = jobN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
redrawJobsList = true
|
||||||
|
}
|
||||||
|
if redrawJobsList {
|
||||||
|
selectedJobN = nil
|
||||||
|
children := make([]*tview.TreeNode, len(jobs))
|
||||||
|
for i := range jobs {
|
||||||
|
jobN := tview.NewTreeNode(jobs[i].JobTreeTitle())
|
||||||
|
jobN.SetReference(jobs[i])
|
||||||
|
jobN.SetSelectable(true)
|
||||||
|
children[i] = jobN
|
||||||
|
jobN.SetSelectedFunc(func() {
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
p.SelectedJob = jobN.GetReference().(*viewmodel.Job)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if jobs[i] == m.SelectedJob() {
|
||||||
|
selectedJobN = jobN
|
||||||
|
}
|
||||||
|
}
|
||||||
|
jobMenuRoot.SetChildren(children)
|
||||||
|
}
|
||||||
|
|
||||||
|
if selectedJobN != nil && jobMenu.GetCurrentNode() != selectedJobN {
|
||||||
|
jobMenu.SetCurrentNode(selectedJobN)
|
||||||
|
} else if selectedJobN == nil {
|
||||||
|
// select something, otherwise selection breaks (likely bug in tview)
|
||||||
|
jobMenu.SetCurrentNode(jobMenuRoot)
|
||||||
|
}
|
||||||
|
|
||||||
|
if selJ := m.SelectedJob(); selJ != nil {
|
||||||
|
jobTextDetail.SetText(selJ.FullDescription())
|
||||||
|
} else {
|
||||||
|
jobTextDetail.SetText("please select a job")
|
||||||
|
}
|
||||||
|
|
||||||
|
bottombardatestring := m.DateString()
|
||||||
|
bottombarDateView.SetText(bottombardatestring)
|
||||||
|
bottombar.ResizeItem(bottombarDateView, len(bottombardatestring), 0)
|
||||||
|
|
||||||
|
bottomBarStatus.SetText(m.BottomBarStatus())
|
||||||
|
|
||||||
|
app.Draw()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
app.Suspend(func() {
|
||||||
|
panic(err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
st, err := c.Status()
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
p.Report = st.Jobs
|
||||||
|
p.ReportFetchError = err
|
||||||
|
})
|
||||||
|
app.QueueUpdateDraw(redraw)
|
||||||
|
|
||||||
|
time.Sleep(flag.Delay)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
jobMenu.SetChangedFunc(func(jobN *tview.TreeNode) {
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
p.SelectedJob, _ = jobN.GetReference().(*viewmodel.Job)
|
||||||
|
})
|
||||||
|
redraw()
|
||||||
|
jobTextDetail.ScrollToBeginning()
|
||||||
|
})
|
||||||
|
jobMenu.SetSelectedFunc(func(jobN *tview.TreeNode) {
|
||||||
|
app.SetFocus(jobTextDetail)
|
||||||
|
})
|
||||||
|
|
||||||
|
app.SetBeforeDrawFunc(func(screen tcell.Screen) bool {
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
_, _, p.DetailViewWidth, _ = jobTextDetail.GetInnerRect()
|
||||||
|
})
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
|
||||||
|
app.SetInputCapture(func(e *tcell.EventKey) *tcell.EventKey {
|
||||||
|
if e.Key() == tcell.KeyTab {
|
||||||
|
tabbableCycle()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if e.Key() == tcell.KeyRune && app.GetFocus() == fsFilterInput {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
if e.Key() == tcell.KeyRune && e.Rune() == '/' {
|
||||||
|
if app.GetFocus() != fsFilterInput {
|
||||||
|
app.SetFocus(fsFilterInput)
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
if e.Key() == tcell.KeyRune && e.Rune() == 'M' {
|
||||||
|
reconfigureJobDetailSplit(!jobMenuVisisble)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if e.Key() == tcell.KeyRune && e.Rune() == 'q' {
|
||||||
|
app.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
if e.Key() == tcell.KeyRune && e.Rune() == 'S' {
|
||||||
|
job, ok := jobMenu.GetCurrentNode().GetReference().(*viewmodel.Job)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
signals := []string{"wakeup", "reset"}
|
||||||
|
clientFuncs := []func(job string) error{c.SignalWakeup, c.SignalReset}
|
||||||
|
sigMod := tview.NewModal()
|
||||||
|
sigMod.SetBackgroundColor(tcell.ColorDefault)
|
||||||
|
sigMod.SetBorder(true)
|
||||||
|
sigMod.GetForm().SetButtonTextColorFocused(tcell.ColorGreen)
|
||||||
|
sigMod.AddButtons(signals)
|
||||||
|
sigMod.SetText(fmt.Sprintf("Send a signal to job %q", job.Name()))
|
||||||
|
showModal(sigMod, func(idx int, _ string) {
|
||||||
|
go func() {
|
||||||
|
if idx == -1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err := clientFuncs[idx](job.Name())
|
||||||
|
if err != nil {
|
||||||
|
app.QueueUpdate(func() {
|
||||||
|
me := tview.NewModal()
|
||||||
|
me.SetText(fmt.Sprintf("signal error: %s", err))
|
||||||
|
me.AddButtons([]string{"Close"})
|
||||||
|
showModal(me, nil)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return e
|
||||||
|
})
|
||||||
|
|
||||||
|
fsFilterInput.SetChangedFunc(func(searchterm string) {
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
p.FSFilter = func(fs string) bool {
|
||||||
|
r, err := regexp.Compile(searchterm)
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return r.MatchString(fs)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
redraw()
|
||||||
|
jobTextDetail.ScrollToBeginning()
|
||||||
|
})
|
||||||
|
fsFilterInput.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
|
||||||
|
if event.Key() == tcell.KeyEnter {
|
||||||
|
app.SetFocus(jobTextDetail)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return event
|
||||||
|
})
|
||||||
|
|
||||||
|
jobTextDetail.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
|
||||||
|
if event.Key() == tcell.KeyRune && event.Rune() == 'w' {
|
||||||
|
// toggle wrapping
|
||||||
|
viewmodelupdate(func(p *viewmodel.Params) {
|
||||||
|
p.DetailViewWrap = !p.DetailViewWrap
|
||||||
|
})
|
||||||
|
redraw()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return event
|
||||||
|
})
|
||||||
|
|
||||||
|
return app.Run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package status
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gdamore/tcell/v2"
|
||||||
|
"github.com/mattn/go-isatty"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
tview "gitlab.com/tslocum/cview"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/client/status/viewmodel"
|
||||||
|
)
|
||||||
|
|
||||||
|
func legacy(c Client, flag statusFlags) error {
|
||||||
|
|
||||||
|
// Set this so we don't overwrite the default terminal colors
|
||||||
|
// See https://github.com/rivo/tview/blob/master/styles.go
|
||||||
|
tview.Styles.PrimitiveBackgroundColor = tcell.ColorDefault
|
||||||
|
tview.Styles.ContrastBackgroundColor = tcell.ColorDefault
|
||||||
|
tview.Styles.PrimaryTextColor = tcell.ColorDefault
|
||||||
|
tview.Styles.BorderColor = tcell.ColorDefault
|
||||||
|
app := tview.NewApplication()
|
||||||
|
|
||||||
|
textView := tview.NewTextView()
|
||||||
|
textView.SetWrap(true)
|
||||||
|
textView.SetScrollable(true) // so that it allows us to set scroll position
|
||||||
|
textView.SetScrollBarVisibility(tview.ScrollBarNever)
|
||||||
|
|
||||||
|
app.SetRoot(textView, true)
|
||||||
|
|
||||||
|
width := (1 << 31) - 1
|
||||||
|
wrap := false
|
||||||
|
if isatty.IsTerminal(os.Stdout.Fd()) {
|
||||||
|
wrap = true
|
||||||
|
screen, err := tcell.NewScreen()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "get terminal dimensions")
|
||||||
|
}
|
||||||
|
if err := screen.Init(); err != nil {
|
||||||
|
return errors.Wrap(err, "init screen")
|
||||||
|
}
|
||||||
|
width, _ = screen.Size()
|
||||||
|
screen.Fini()
|
||||||
|
}
|
||||||
|
|
||||||
|
paramsMtx := &sync.Mutex{}
|
||||||
|
params := viewmodel.Params{
|
||||||
|
Report: nil,
|
||||||
|
ReportFetchError: nil,
|
||||||
|
SelectedJob: nil,
|
||||||
|
FSFilter: func(s string) bool { return true },
|
||||||
|
DetailViewWidth: width,
|
||||||
|
DetailViewWrap: wrap,
|
||||||
|
ShortKeybindingOverview: "",
|
||||||
|
}
|
||||||
|
|
||||||
|
redraw := func() {
|
||||||
|
textView.Clear()
|
||||||
|
|
||||||
|
paramsMtx.Lock()
|
||||||
|
defer paramsMtx.Unlock()
|
||||||
|
|
||||||
|
if params.ReportFetchError != nil {
|
||||||
|
fmt.Fprintln(textView, params.ReportFetchError.Error())
|
||||||
|
} else if params.Report != nil {
|
||||||
|
m := viewmodel.New()
|
||||||
|
m.Update(params)
|
||||||
|
for _, j := range m.Jobs() {
|
||||||
|
if flag.Job != "" && j.Name() != flag.Job {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
params.SelectedJob = j
|
||||||
|
m.Update(params)
|
||||||
|
fmt.Fprintln(textView, m.SelectedJob().FullDescription())
|
||||||
|
if flag.Job != "" {
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
hline := strings.Repeat("-", params.DetailViewWidth)
|
||||||
|
fmt.Fprintln(textView, hline)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Fprintln(textView, "waiting for request results")
|
||||||
|
}
|
||||||
|
textView.ScrollToBeginning()
|
||||||
|
}
|
||||||
|
|
||||||
|
app.SetBeforeDrawFunc(func(screen tcell.Screen) bool {
|
||||||
|
// sync resizes to `params`
|
||||||
|
paramsMtx.Lock()
|
||||||
|
_, _, newWidth, _ := textView.GetInnerRect()
|
||||||
|
if newWidth != params.DetailViewWidth {
|
||||||
|
params.DetailViewWidth = newWidth
|
||||||
|
app.QueueUpdateDraw(redraw)
|
||||||
|
}
|
||||||
|
paramsMtx.Unlock()
|
||||||
|
|
||||||
|
textView.ScrollToBeginning() // has the effect of inhibiting user scrolls
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
app.Suspend(func() {
|
||||||
|
panic(err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
st, err := c.Status()
|
||||||
|
paramsMtx.Lock()
|
||||||
|
params.Report = st.Jobs
|
||||||
|
params.ReportFetchError = err
|
||||||
|
paramsMtx.Unlock()
|
||||||
|
|
||||||
|
app.QueueUpdateDraw(redraw)
|
||||||
|
|
||||||
|
time.Sleep(flag.Delay)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return app.Run()
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package status
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func raw(c Client) error {
|
||||||
|
b, err := c.StatusRaw()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := io.Copy(os.Stdout, bytes.NewReader(b)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package viewmodel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
func ByteCountBinaryUint(b uint64) string {
|
||||||
|
if b > math.MaxInt64 {
|
||||||
|
panic(b)
|
||||||
|
}
|
||||||
|
return ByteCountBinary(int64(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ByteCountBinary(b int64) string {
|
||||||
|
const unit = 1024
|
||||||
|
if b < unit {
|
||||||
|
return fmt.Sprintf("%d B", b)
|
||||||
|
}
|
||||||
|
div, exp := unit, 0
|
||||||
|
for n := b / unit; n >= unit; n /= unit {
|
||||||
|
div *= unit
|
||||||
|
exp++
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package viewmodel
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
type byteProgressMeasurement struct {
|
||||||
|
time time.Time
|
||||||
|
val uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
type bytesProgressHistory struct {
|
||||||
|
last *byteProgressMeasurement // pointer as poor man's optional
|
||||||
|
changeCount int
|
||||||
|
lastChange time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *bytesProgressHistory) Update(currentVal uint64) (bytesPerSecondAvg int64, changeCount int) {
|
||||||
|
|
||||||
|
if p.last == nil {
|
||||||
|
p.last = &byteProgressMeasurement{
|
||||||
|
time: time.Now(),
|
||||||
|
val: currentVal,
|
||||||
|
}
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.last.val != currentVal {
|
||||||
|
p.changeCount++
|
||||||
|
p.lastChange = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
if time.Since(p.lastChange) > 3*time.Second {
|
||||||
|
p.last = nil
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var deltaV int64
|
||||||
|
if currentVal >= p.last.val {
|
||||||
|
deltaV = int64(currentVal - p.last.val)
|
||||||
|
} else {
|
||||||
|
deltaV = -int64(p.last.val - currentVal)
|
||||||
|
}
|
||||||
|
deltaT := time.Since(p.last.time)
|
||||||
|
rate := float64(deltaV) / deltaT.Seconds()
|
||||||
|
|
||||||
|
p.last.time = time.Now()
|
||||||
|
p.last.val = currentVal
|
||||||
|
|
||||||
|
return int64(rate), p.changeCount
|
||||||
|
}
|
||||||
@@ -0,0 +1,660 @@
|
|||||||
|
package viewmodel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
yaml "github.com/zrepl/yaml-config"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/client/status/viewmodel/stringbuilder"
|
||||||
|
"github.com/zrepl/zrepl/daemon"
|
||||||
|
"github.com/zrepl/zrepl/daemon/job"
|
||||||
|
"github.com/zrepl/zrepl/daemon/pruner"
|
||||||
|
"github.com/zrepl/zrepl/daemon/snapper"
|
||||||
|
"github.com/zrepl/zrepl/replication/report"
|
||||||
|
)
|
||||||
|
|
||||||
|
type M struct {
|
||||||
|
jobs map[string]*Job
|
||||||
|
jobsList []*Job
|
||||||
|
selectedJob *Job
|
||||||
|
dateString string
|
||||||
|
bottomBarStatus string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Job struct {
|
||||||
|
// long-lived
|
||||||
|
name string
|
||||||
|
byteProgress *bytesProgressHistory
|
||||||
|
|
||||||
|
lastStatus *job.Status
|
||||||
|
fulldescription string
|
||||||
|
}
|
||||||
|
|
||||||
|
func New() *M {
|
||||||
|
return &M{
|
||||||
|
jobs: make(map[string]*Job),
|
||||||
|
jobsList: make([]*Job, 0),
|
||||||
|
selectedJob: nil,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FilterFunc func(string) bool
|
||||||
|
|
||||||
|
type Params struct {
|
||||||
|
Report map[string]*job.Status
|
||||||
|
ReportFetchError error
|
||||||
|
SelectedJob *Job
|
||||||
|
FSFilter FilterFunc `validate:"required"`
|
||||||
|
DetailViewWidth int `validate:"gte=1"`
|
||||||
|
DetailViewWrap bool
|
||||||
|
ShortKeybindingOverview string
|
||||||
|
}
|
||||||
|
|
||||||
|
var validate = validator.New()
|
||||||
|
|
||||||
|
func (m *M) Update(p Params) {
|
||||||
|
|
||||||
|
if err := validate.Struct(p); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if p.ReportFetchError != nil {
|
||||||
|
m.bottomBarStatus = fmt.Sprintf("[red::]status fetch: %s", p.ReportFetchError)
|
||||||
|
} else {
|
||||||
|
m.bottomBarStatus = p.ShortKeybindingOverview
|
||||||
|
for jobname, st := range p.Report {
|
||||||
|
// TODO handle job renames & deletions
|
||||||
|
j, ok := m.jobs[jobname]
|
||||||
|
if !ok {
|
||||||
|
j = &Job{
|
||||||
|
name: jobname,
|
||||||
|
byteProgress: &bytesProgressHistory{},
|
||||||
|
}
|
||||||
|
m.jobs[jobname] = j
|
||||||
|
m.jobsList = append(m.jobsList, j)
|
||||||
|
}
|
||||||
|
j.lastStatus = st
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter out internal jobs
|
||||||
|
var jobsList []*Job
|
||||||
|
for _, j := range m.jobsList {
|
||||||
|
if daemon.IsInternalJobName(j.name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
jobsList = append(jobsList, j)
|
||||||
|
}
|
||||||
|
m.jobsList = jobsList
|
||||||
|
|
||||||
|
// determinism!
|
||||||
|
sort.Slice(m.jobsList, func(i, j int) bool {
|
||||||
|
return strings.Compare(m.jobsList[i].name, m.jobsList[j].name) < 0
|
||||||
|
})
|
||||||
|
|
||||||
|
// try to not lose the selected job
|
||||||
|
m.selectedJob = nil
|
||||||
|
for _, j := range m.jobsList {
|
||||||
|
j.updateFullDescription(p)
|
||||||
|
if j == p.SelectedJob {
|
||||||
|
m.selectedJob = j
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
m.dateString = time.Now().Format(time.RFC3339)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *M) BottomBarStatus() string { return m.bottomBarStatus }
|
||||||
|
|
||||||
|
func (m *M) Jobs() []*Job { return m.jobsList }
|
||||||
|
|
||||||
|
// may be nil
|
||||||
|
func (m *M) SelectedJob() *Job { return m.selectedJob }
|
||||||
|
|
||||||
|
func (m *M) DateString() string { return m.dateString }
|
||||||
|
|
||||||
|
func (j *Job) updateFullDescription(p Params) {
|
||||||
|
width := p.DetailViewWidth
|
||||||
|
if !p.DetailViewWrap {
|
||||||
|
width = 10000000 // FIXME
|
||||||
|
}
|
||||||
|
b := stringbuilder.New(stringbuilder.Config{
|
||||||
|
IndentMultiplier: 3,
|
||||||
|
Width: width,
|
||||||
|
})
|
||||||
|
drawJob(b, j.name, j.lastStatus, j.byteProgress, p.FSFilter)
|
||||||
|
j.fulldescription = b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *Job) JobTreeTitle() string {
|
||||||
|
return j.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *Job) FullDescription() string {
|
||||||
|
return j.fulldescription
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *Job) Name() string {
|
||||||
|
return j.name
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawJob(t *stringbuilder.B, name string, v *job.Status, history *bytesProgressHistory, fsfilter FilterFunc) {
|
||||||
|
|
||||||
|
t.Printf("Job: %s\n", name)
|
||||||
|
t.Printf("Type: %s\n\n", v.Type)
|
||||||
|
|
||||||
|
if v.Type == job.TypePush || v.Type == job.TypePull {
|
||||||
|
activeStatus, ok := v.JobSpecific.(*job.ActiveSideStatus)
|
||||||
|
if !ok || activeStatus == nil {
|
||||||
|
t.Printf("ActiveSideStatus is null")
|
||||||
|
t.Newline()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Printf("Replication:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderReplicationReport(t, activeStatus.Replication, history, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
|
||||||
|
t.Printf("Pruning Sender:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderPrunerReport(t, activeStatus.PruningSender, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
|
||||||
|
t.Printf("Pruning Receiver:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderPrunerReport(t, activeStatus.PruningReceiver, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
|
||||||
|
if v.Type == job.TypePush {
|
||||||
|
t.Printf("Snapshotting:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderSnapperReport(t, activeStatus.Snapshotting, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if v.Type == job.TypeSnap {
|
||||||
|
snapStatus, ok := v.JobSpecific.(*job.SnapJobStatus)
|
||||||
|
if !ok || snapStatus == nil {
|
||||||
|
t.Printf("SnapJobStatus is null")
|
||||||
|
t.Newline()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Printf("Pruning snapshots:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderPrunerReport(t, snapStatus.Pruning, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
t.Printf("Snapshotting:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
renderSnapperReport(t, snapStatus.Snapshotting, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
} else if v.Type == job.TypeSource {
|
||||||
|
|
||||||
|
st := v.JobSpecific.(*job.PassiveStatus)
|
||||||
|
t.Printf("Snapshotting:\n")
|
||||||
|
t.AddIndent(1)
|
||||||
|
renderSnapperReport(t, st.Snapper, fsfilter)
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
|
||||||
|
} else {
|
||||||
|
t.Printf("No status representation for job type '%s', dumping as YAML", v.Type)
|
||||||
|
t.Newline()
|
||||||
|
asYaml, err := yaml.Marshal(v.JobSpecific)
|
||||||
|
if err != nil {
|
||||||
|
t.Printf("Error marshaling status to YAML: %s", err)
|
||||||
|
t.Newline()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Write(string(asYaml))
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printFilesystemStatus(t *stringbuilder.B, rep *report.FilesystemReport, maxFS int) {
|
||||||
|
|
||||||
|
expected, replicated, containsInvalidSizeEstimates := rep.BytesSum()
|
||||||
|
sizeEstimationImpreciseNotice := ""
|
||||||
|
if containsInvalidSizeEstimates {
|
||||||
|
sizeEstimationImpreciseNotice = " (some steps lack size estimation)"
|
||||||
|
}
|
||||||
|
if rep.CurrentStep < len(rep.Steps) && rep.Steps[rep.CurrentStep].Info.BytesExpected == 0 {
|
||||||
|
sizeEstimationImpreciseNotice = " (step lacks size estimation)"
|
||||||
|
}
|
||||||
|
|
||||||
|
userVisisbleCurrentStep, userVisibleTotalSteps := rep.CurrentStep, len(rep.Steps)
|
||||||
|
// `.CurrentStep` is == len(rep.Steps) if all steps are done.
|
||||||
|
// Until then, it's an index into .Steps that starts at 0.
|
||||||
|
// For the user, we want it to start at 1.
|
||||||
|
if rep.CurrentStep >= len(rep.Steps) {
|
||||||
|
// rep.CurrentStep is what we want to show.
|
||||||
|
// We check for >= and not == for robustness.
|
||||||
|
} else {
|
||||||
|
// We're not done yet, so, make step count start at 1
|
||||||
|
// (The `.State` is included in the output, indicating we're not done yet)
|
||||||
|
userVisisbleCurrentStep = rep.CurrentStep + 1
|
||||||
|
}
|
||||||
|
status := fmt.Sprintf("%s (step %d/%d, %s/%s)%s",
|
||||||
|
strings.ToUpper(string(rep.State)),
|
||||||
|
userVisisbleCurrentStep, userVisibleTotalSteps,
|
||||||
|
ByteCountBinaryUint(replicated), ByteCountBinaryUint(expected),
|
||||||
|
sizeEstimationImpreciseNotice,
|
||||||
|
)
|
||||||
|
|
||||||
|
activeIndicator := " "
|
||||||
|
if rep.BlockedOn == report.FsBlockedOnNothing &&
|
||||||
|
(rep.State == report.FilesystemPlanning || rep.State == report.FilesystemStepping) {
|
||||||
|
activeIndicator = "*"
|
||||||
|
}
|
||||||
|
t.AddIndent(1)
|
||||||
|
t.Printf("%s %s %s ",
|
||||||
|
activeIndicator,
|
||||||
|
stringbuilder.RightPad(rep.Info.Name, maxFS, " "),
|
||||||
|
status)
|
||||||
|
|
||||||
|
next := ""
|
||||||
|
if err := rep.Error(); err != nil {
|
||||||
|
next = err.Err
|
||||||
|
} else if rep.State != report.FilesystemDone {
|
||||||
|
if nextStep := rep.NextStep(); nextStep != nil {
|
||||||
|
if nextStep.IsIncremental() {
|
||||||
|
next = fmt.Sprintf("next: %s => %s", nextStep.Info.From, nextStep.Info.To)
|
||||||
|
} else {
|
||||||
|
next = fmt.Sprintf("next: full send %s", nextStep.Info.To)
|
||||||
|
}
|
||||||
|
attribs := []string{}
|
||||||
|
|
||||||
|
if nextStep.Info.Resumed {
|
||||||
|
attribs = append(attribs, "resumed")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(attribs) > 0 {
|
||||||
|
next += fmt.Sprintf(" (%s)", strings.Join(attribs, ", "))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
next = "" // individual FSes may still be in planning state
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
t.Printf("%s", next)
|
||||||
|
|
||||||
|
t.AddIndent(-1)
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderReplicationReport(t *stringbuilder.B, rep *report.Report, history *bytesProgressHistory, fsfilter FilterFunc) {
|
||||||
|
if rep == nil {
|
||||||
|
t.Printf("...\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if rep.WaitReconnectError != nil {
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("Connectivity: %s", rep.WaitReconnectError)
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
if !rep.WaitReconnectSince.IsZero() {
|
||||||
|
delta := time.Until(rep.WaitReconnectUntil).Round(time.Second)
|
||||||
|
if rep.WaitReconnectUntil.IsZero() || delta > 0 {
|
||||||
|
var until string
|
||||||
|
if rep.WaitReconnectUntil.IsZero() {
|
||||||
|
until = "waiting indefinitely"
|
||||||
|
} else {
|
||||||
|
until = fmt.Sprintf("hard fail in %s @ %s", delta, rep.WaitReconnectUntil)
|
||||||
|
}
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("Connectivity: reconnecting with exponential backoff (since %s) (%s)",
|
||||||
|
rep.WaitReconnectSince, until)
|
||||||
|
} else {
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("Connectivity: reconnects reached hard-fail timeout @ %s", rep.WaitReconnectUntil)
|
||||||
|
}
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO visualize more than the latest attempt by folding all attempts into one
|
||||||
|
if len(rep.Attempts) == 0 {
|
||||||
|
t.Printf("no attempts made yet")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
t.Printf("Attempt #%d", len(rep.Attempts))
|
||||||
|
if len(rep.Attempts) > 1 {
|
||||||
|
t.Printf(". Previous attempts failed with the following statuses:")
|
||||||
|
t.AddIndentAndNewline(1)
|
||||||
|
for i, a := range rep.Attempts[:len(rep.Attempts)-1] {
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("#%d: %s (failed at %s) (ran %s)\n", i+1, a.State, a.FinishAt, a.FinishAt.Sub(a.StartAt))
|
||||||
|
}
|
||||||
|
t.AddIndentAndNewline(-1)
|
||||||
|
} else {
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
latest := rep.Attempts[len(rep.Attempts)-1]
|
||||||
|
sort.Slice(latest.Filesystems, func(i, j int) bool {
|
||||||
|
return latest.Filesystems[i].Info.Name < latest.Filesystems[j].Info.Name
|
||||||
|
})
|
||||||
|
|
||||||
|
// apply filter
|
||||||
|
filtered := make([]*report.FilesystemReport, 0, len(latest.Filesystems))
|
||||||
|
for _, fs := range latest.Filesystems {
|
||||||
|
if !fsfilter(fs.Info.Name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
filtered = append(filtered, fs)
|
||||||
|
}
|
||||||
|
latest.Filesystems = filtered
|
||||||
|
|
||||||
|
t.Printf("Status: %s", latest.State)
|
||||||
|
t.Newline()
|
||||||
|
if !latest.FinishAt.IsZero() {
|
||||||
|
t.Printf("Last Run: %s (lasted %s)\n", latest.FinishAt.Round(time.Second), latest.FinishAt.Sub(latest.StartAt).Round(time.Second))
|
||||||
|
} else {
|
||||||
|
t.Printf("Started: %s (lasting %s)\n", latest.StartAt.Round(time.Second), time.Since(latest.StartAt).Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
|
if latest.State == report.AttemptPlanningError {
|
||||||
|
t.Printf("Problem: ")
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("%s", latest.PlanError)
|
||||||
|
t.Newline()
|
||||||
|
} else if latest.State == report.AttemptFanOutError {
|
||||||
|
t.Printf("Problem: one or more of the filesystems encountered errors")
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
if latest.State != report.AttemptPlanning && latest.State != report.AttemptPlanningError {
|
||||||
|
// Draw global progress bar
|
||||||
|
// Progress: [---------------]
|
||||||
|
expected, replicated, containsInvalidSizeEstimates := latest.BytesSum()
|
||||||
|
rate, changeCount := history.Update(replicated)
|
||||||
|
eta := time.Duration(0)
|
||||||
|
if rate > 0 {
|
||||||
|
eta = time.Duration((float64(expected)-float64(replicated))/float64(rate)) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
if !latest.State.IsTerminal() {
|
||||||
|
t.Write("Progress: ")
|
||||||
|
t.DrawBar(50, replicated, expected, changeCount)
|
||||||
|
t.Write(fmt.Sprintf(" %s / %s @ %s/s", ByteCountBinaryUint(replicated), ByteCountBinaryUint(expected), ByteCountBinary(rate)))
|
||||||
|
if eta != 0 {
|
||||||
|
t.Write(fmt.Sprintf(" (%s remaining)", humanizeDuration(eta)))
|
||||||
|
}
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
if containsInvalidSizeEstimates {
|
||||||
|
t.Write("NOTE: not all steps could be size-estimated, total estimate is likely imprecise!")
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(latest.Filesystems) == 0 {
|
||||||
|
t.Write("NOTE: no filesystems were considered for replication!")
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
var maxFSLen int
|
||||||
|
for _, fs := range latest.Filesystems {
|
||||||
|
if len(fs.Info.Name) > maxFSLen {
|
||||||
|
maxFSLen = len(fs.Info.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, fs := range latest.Filesystems {
|
||||||
|
printFilesystemStatus(t, fs, maxFSLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func humanizeDuration(duration time.Duration) string {
|
||||||
|
days := int64(duration.Hours() / 24)
|
||||||
|
hours := int64(math.Mod(duration.Hours(), 24))
|
||||||
|
minutes := int64(math.Mod(duration.Minutes(), 60))
|
||||||
|
seconds := int64(math.Mod(duration.Seconds(), 60))
|
||||||
|
|
||||||
|
var parts []string
|
||||||
|
|
||||||
|
force := false
|
||||||
|
chunks := []int64{days, hours, minutes, seconds}
|
||||||
|
for i, chunk := range chunks {
|
||||||
|
if force || chunk > 0 {
|
||||||
|
padding := 0
|
||||||
|
if force {
|
||||||
|
padding = 2
|
||||||
|
}
|
||||||
|
parts = append(parts, fmt.Sprintf("%*d%c", padding, chunk, "dhms"[i]))
|
||||||
|
force = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(parts, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderPrunerReport(t *stringbuilder.B, r *pruner.Report, fsfilter FilterFunc) {
|
||||||
|
if r == nil {
|
||||||
|
t.Printf("...\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state, err := pruner.StateString(r.State)
|
||||||
|
if err != nil {
|
||||||
|
t.Printf("Status: %q (parse error: %q)\n", r.State, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Printf("Status: %s", state)
|
||||||
|
t.Newline()
|
||||||
|
|
||||||
|
if r.Error != "" {
|
||||||
|
t.Printf("Error: %s\n", r.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type commonFS struct {
|
||||||
|
*pruner.FSReport
|
||||||
|
completed bool
|
||||||
|
}
|
||||||
|
all := make([]commonFS, 0, len(r.Pending)+len(r.Completed))
|
||||||
|
for i := range r.Pending {
|
||||||
|
all = append(all, commonFS{&r.Pending[i], false})
|
||||||
|
}
|
||||||
|
for i := range r.Completed {
|
||||||
|
all = append(all, commonFS{&r.Completed[i], true})
|
||||||
|
}
|
||||||
|
|
||||||
|
// filter all
|
||||||
|
filtered := make([]commonFS, 0, len(all))
|
||||||
|
for _, fs := range all {
|
||||||
|
if fsfilter(fs.FSReport.Filesystem) {
|
||||||
|
filtered = append(filtered, fs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
all = filtered
|
||||||
|
|
||||||
|
switch state {
|
||||||
|
case pruner.Plan:
|
||||||
|
fallthrough
|
||||||
|
case pruner.PlanErr:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(all) == 0 {
|
||||||
|
t.Printf("nothing to do\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var totalDestroyCount, completedDestroyCount int
|
||||||
|
var maxFSname int
|
||||||
|
for _, fs := range all {
|
||||||
|
totalDestroyCount += len(fs.DestroyList)
|
||||||
|
if fs.completed {
|
||||||
|
completedDestroyCount += len(fs.DestroyList)
|
||||||
|
}
|
||||||
|
if maxFSname < len(fs.Filesystem) {
|
||||||
|
maxFSname = len(fs.Filesystem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// global progress bar
|
||||||
|
if !state.IsTerminal() {
|
||||||
|
progress := int(math.Round(80 * float64(completedDestroyCount) / float64(totalDestroyCount)))
|
||||||
|
t.Write("Progress: ")
|
||||||
|
t.Write("[")
|
||||||
|
t.Write(stringbuilder.Times("=", progress))
|
||||||
|
t.Write(">")
|
||||||
|
t.Write(stringbuilder.Times("-", 80-progress))
|
||||||
|
t.Write("]")
|
||||||
|
t.Printf(" %d/%d snapshots", completedDestroyCount, totalDestroyCount)
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
sort.SliceStable(all, func(i, j int) bool {
|
||||||
|
return strings.Compare(all[i].Filesystem, all[j].Filesystem) == -1
|
||||||
|
})
|
||||||
|
|
||||||
|
// Draw a table-like representation of 'all'
|
||||||
|
for _, fs := range all {
|
||||||
|
t.Write(stringbuilder.RightPad(fs.Filesystem, maxFSname, " "))
|
||||||
|
t.Write(" ")
|
||||||
|
if !fs.SkipReason.NotSkipped() {
|
||||||
|
t.Printf("skipped: %s\n", fs.SkipReason)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fs.LastError != "" {
|
||||||
|
if strings.ContainsAny(fs.LastError, "\r\n") {
|
||||||
|
t.Printf("ERROR:")
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("%s\n", fs.LastError)
|
||||||
|
} else {
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline("ERROR: %s\n", fs.LastError)
|
||||||
|
}
|
||||||
|
t.Newline()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
pruneRuleActionStr := fmt.Sprintf("(destroy %d of %d snapshots)",
|
||||||
|
len(fs.DestroyList), len(fs.SnapshotList))
|
||||||
|
|
||||||
|
if fs.completed {
|
||||||
|
t.Printf("Completed %s\n", pruneRuleActionStr)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Write("Pending ") // whitespace is padding 10
|
||||||
|
if len(fs.DestroyList) == 1 {
|
||||||
|
t.Write(fs.DestroyList[0].Name)
|
||||||
|
} else {
|
||||||
|
t.Write(pruneRuleActionStr)
|
||||||
|
}
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderSnapperReport(t *stringbuilder.B, r *snapper.Report, fsfilter FilterFunc) {
|
||||||
|
if r == nil {
|
||||||
|
t.Printf("<no snapshotting report available>\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Printf("Type: %s\n", r.Type)
|
||||||
|
if r.Periodic != nil {
|
||||||
|
renderSnapperReportPeriodic(t, r.Periodic, fsfilter)
|
||||||
|
} else if r.Cron != nil {
|
||||||
|
renderSnapperReportCron(t, r.Cron, fsfilter)
|
||||||
|
} else {
|
||||||
|
t.Printf("<no details available>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderSnapperReportPeriodic(t *stringbuilder.B, r *snapper.PeriodicReport, fsfilter FilterFunc) {
|
||||||
|
t.Printf("Status: %s", r.State)
|
||||||
|
t.Newline()
|
||||||
|
|
||||||
|
if r.Error != "" {
|
||||||
|
t.Printf("Error: %s\n", r.Error)
|
||||||
|
}
|
||||||
|
if !r.SleepUntil.IsZero() {
|
||||||
|
t.Printf("Sleep until: %s\n", r.SleepUntil)
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSnapperPlanReportFilesystem(t, r.Progress, fsfilter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderSnapperReportCron(t *stringbuilder.B, r *snapper.CronReport, fsfilter FilterFunc) {
|
||||||
|
t.Printf("State: %s\n", r.State)
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
if r.WakeupTime.After(now) {
|
||||||
|
t.Printf("Sleep until: %s (%s remaining)\n", r.WakeupTime, r.WakeupTime.Sub(now).Round(time.Second))
|
||||||
|
} else {
|
||||||
|
t.Printf("Started: %s (lasting %s)\n", r.WakeupTime, now.Sub(r.WakeupTime).Round(time.Second))
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSnapperPlanReportFilesystem(t, r.Progress, fsfilter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func renderSnapperPlanReportFilesystem(t *stringbuilder.B, fss []*snapper.ReportFilesystem, fsfilter FilterFunc) {
|
||||||
|
sort.Slice(fss, func(i, j int) bool {
|
||||||
|
return strings.Compare(fss[i].Path, fss[j].Path) == -1
|
||||||
|
})
|
||||||
|
|
||||||
|
dur := func(d time.Duration) string {
|
||||||
|
return d.Round(100 * time.Millisecond).String()
|
||||||
|
}
|
||||||
|
|
||||||
|
type row struct {
|
||||||
|
path, state, duration, remainder, hookReport string
|
||||||
|
}
|
||||||
|
var widths struct {
|
||||||
|
path, state, duration int
|
||||||
|
}
|
||||||
|
rows := make([]*row, 0, len(fss))
|
||||||
|
for _, fs := range fss {
|
||||||
|
if !fsfilter(fs.Path) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
r := &row{
|
||||||
|
path: fs.Path,
|
||||||
|
state: fs.State.String(),
|
||||||
|
}
|
||||||
|
if fs.HooksHadError {
|
||||||
|
r.hookReport = fs.Hooks // FIXME render here, not in daemon
|
||||||
|
}
|
||||||
|
switch fs.State {
|
||||||
|
case snapper.SnapPending:
|
||||||
|
r.duration = "..."
|
||||||
|
r.remainder = ""
|
||||||
|
case snapper.SnapStarted:
|
||||||
|
r.duration = dur(time.Since(fs.StartAt))
|
||||||
|
r.remainder = fmt.Sprintf("snap name: %q", fs.SnapName)
|
||||||
|
case snapper.SnapDone:
|
||||||
|
fallthrough
|
||||||
|
case snapper.SnapError:
|
||||||
|
r.duration = dur(fs.DoneAt.Sub(fs.StartAt))
|
||||||
|
r.remainder = fmt.Sprintf("snap name: %q", fs.SnapName)
|
||||||
|
}
|
||||||
|
rows = append(rows, r)
|
||||||
|
if len(r.path) > widths.path {
|
||||||
|
widths.path = len(r.path)
|
||||||
|
}
|
||||||
|
if len(r.state) > widths.state {
|
||||||
|
widths.state = len(r.state)
|
||||||
|
}
|
||||||
|
if len(r.duration) > widths.duration {
|
||||||
|
widths.duration = len(r.duration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, r := range rows {
|
||||||
|
path := stringbuilder.RightPad(r.path, widths.path, " ")
|
||||||
|
state := stringbuilder.RightPad(r.state, widths.state, " ")
|
||||||
|
duration := stringbuilder.RightPad(r.duration, widths.duration, " ")
|
||||||
|
t.Printf("%s %s %s", path, state, duration)
|
||||||
|
t.PrintfDrawIndentedAndWrappedIfMultiline(" %s", r.remainder)
|
||||||
|
if r.hookReport != "" {
|
||||||
|
t.AddIndent(1)
|
||||||
|
t.Newline()
|
||||||
|
t.Printf("%s", r.hookReport)
|
||||||
|
t.AddIndent(-1)
|
||||||
|
}
|
||||||
|
t.Newline()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package stringbuilder
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
)
|
||||||
|
|
||||||
|
type B struct {
|
||||||
|
// const
|
||||||
|
indentMultiplier int
|
||||||
|
|
||||||
|
// mut
|
||||||
|
sb *strings.Builder
|
||||||
|
indent int
|
||||||
|
width int
|
||||||
|
x, y int
|
||||||
|
}
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
IndentMultiplier int `validate:"gte=1"`
|
||||||
|
Width int `validate:"gte=1"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var validate = validator.New()
|
||||||
|
|
||||||
|
func New(config Config) *B {
|
||||||
|
|
||||||
|
if err := validate.Struct(config); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &B{sb: &strings.Builder{}, width: config.Width, indentMultiplier: config.IndentMultiplier}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *B) String() string { return b.sb.String() }
|
||||||
|
|
||||||
|
func (w *B) Newline() {
|
||||||
|
w.Write("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *B) PrintfDrawIndentedAndWrappedIfMultiline(format string, args ...interface{}) {
|
||||||
|
whole := fmt.Sprintf(format, args...)
|
||||||
|
if strings.ContainsAny(whole, "\n\r") {
|
||||||
|
w.AddIndent(1)
|
||||||
|
defer w.AddIndent(-1)
|
||||||
|
}
|
||||||
|
w.Write(whole)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *B) Printf(format string, args ...interface{}) {
|
||||||
|
whole := fmt.Sprintf(format, args...)
|
||||||
|
w.Write(whole)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *B) AddIndent(delta int) {
|
||||||
|
t.indent += delta * t.indentMultiplier
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *B) AddIndentAndNewline(delta int) {
|
||||||
|
t.indent += delta * t.indentMultiplier
|
||||||
|
t.Write("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *B) Write(s string) {
|
||||||
|
for _, c := range s {
|
||||||
|
if c == '\n' {
|
||||||
|
fmt.Fprint(w.sb, "\n")
|
||||||
|
w.x = 0
|
||||||
|
fmt.Fprint(w.sb, Times(" ", w.indent-w.x))
|
||||||
|
w.x = w.indent
|
||||||
|
w.y++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w.x >= w.width {
|
||||||
|
fmt.Fprint(w.sb, "\n")
|
||||||
|
w.x = 0
|
||||||
|
fmt.Fprint(w.sb, Times(" ", w.indent-w.x))
|
||||||
|
w.x = w.indent
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w.sb, "%c", c)
|
||||||
|
w.x++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func Times(str string, n int) (out string) {
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
out += str
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func RightPad(str string, length int, pad string) string {
|
||||||
|
if len(str) > length {
|
||||||
|
return str[:length]
|
||||||
|
}
|
||||||
|
return str + strings.Repeat(pad, length-len(str))
|
||||||
|
}
|
||||||
|
|
||||||
|
// changeCount = 0 indicates stall / no progress
|
||||||
|
func (w *B) DrawBar(length int, bytes, totalBytes uint64, changeCount int) {
|
||||||
|
const arrowPositions = `>\|/`
|
||||||
|
var completedLength int
|
||||||
|
if totalBytes > 0 {
|
||||||
|
completedLength = int(uint64(length) * bytes / totalBytes)
|
||||||
|
if completedLength > length {
|
||||||
|
completedLength = length
|
||||||
|
}
|
||||||
|
} else if totalBytes == bytes {
|
||||||
|
completedLength = length
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Write("[")
|
||||||
|
w.Write(Times("=", completedLength))
|
||||||
|
w.Write(string(arrowPositions[changeCount%len(arrowPositions)]))
|
||||||
|
w.Write(Times("-", length-completedLength))
|
||||||
|
w.Write("]")
|
||||||
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/zrepl/zrepl/cli"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
"github.com/problame/go-netssh"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"github.com/problame/go-netssh"
|
|
||||||
"github.com/zrepl/zrepl/config"
|
|
||||||
"log"
|
"log"
|
||||||
"path"
|
"path"
|
||||||
)
|
)
|
||||||
@@ -15,7 +17,7 @@ import (
|
|||||||
var StdinserverCmd = &cli.Subcommand{
|
var StdinserverCmd = &cli.Subcommand{
|
||||||
Use: "stdinserver CLIENT_IDENTITY",
|
Use: "stdinserver CLIENT_IDENTITY",
|
||||||
Short: "stdinserver transport mode (started from authorized_keys file as forced command)",
|
Short: "stdinserver transport mode (started from authorized_keys file as forced command)",
|
||||||
Run: func(subcommand *cli.Subcommand, args []string) error {
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
return runStdinserver(subcommand.Config(), args)
|
return runStdinserver(subcommand.Config(), args)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|||||||
+61
-17
@@ -1,30 +1,35 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
"github.com/zrepl/zrepl/cli"
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/filters"
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
"github.com/zrepl/zrepl/zfs"
|
"github.com/zrepl/zrepl/zfs"
|
||||||
)
|
)
|
||||||
|
|
||||||
var TestCmd = &cli.Subcommand {
|
var TestCmd = &cli.Subcommand{
|
||||||
Use: "test",
|
Use: "test",
|
||||||
SetupSubcommands: func() []*cli.Subcommand {
|
SetupSubcommands: func() []*cli.Subcommand {
|
||||||
return []*cli.Subcommand{testFilter, testPlaceholder}
|
return []*cli.Subcommand{testFilter, testPlaceholder, testDecodeResumeToken}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
var testFilterArgs struct {
|
var testFilterArgs struct {
|
||||||
job string
|
job string
|
||||||
all bool
|
all bool
|
||||||
input string
|
input string
|
||||||
}
|
}
|
||||||
|
|
||||||
var testFilter = &cli.Subcommand{
|
var testFilter = &cli.Subcommand{
|
||||||
Use: "filesystems --job JOB [--all | --input INPUT]",
|
Use: "filesystems --job JOB [--all | --input INPUT]",
|
||||||
Short: "test filesystems filter specified in push or source job",
|
Short: "test filesystems filter specified in push or source job",
|
||||||
SetupFlags: func(f *pflag.FlagSet) {
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
f.StringVar(&testFilterArgs.job, "job", "", "the name of the push or source job")
|
f.StringVar(&testFilterArgs.job, "job", "", "the name of the push or source job")
|
||||||
@@ -34,7 +39,7 @@ var testFilter = &cli.Subcommand{
|
|||||||
Run: runTestFilterCmd,
|
Run: runTestFilterCmd,
|
||||||
}
|
}
|
||||||
|
|
||||||
func runTestFilterCmd(subcommand *cli.Subcommand, args []string) error {
|
func runTestFilterCmd(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
|
||||||
if testFilterArgs.job == "" {
|
if testFilterArgs.job == "" {
|
||||||
return fmt.Errorf("must specify --job flag")
|
return fmt.Errorf("must specify --job flag")
|
||||||
@@ -51,8 +56,12 @@ func runTestFilterCmd(subcommand *cli.Subcommand, args []string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
switch j := job.Ret.(type) {
|
switch j := job.Ret.(type) {
|
||||||
case *config.SourceJob: confFilter = j.Filesystems
|
case *config.SourceJob:
|
||||||
case *config.PushJob: confFilter = j.Filesystems
|
confFilter = j.Filesystems
|
||||||
|
case *config.PushJob:
|
||||||
|
confFilter = j.Filesystems
|
||||||
|
case *config.SnapJob:
|
||||||
|
confFilter = j.Filesystems
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("job type %T does not have filesystems filter", j)
|
return fmt.Errorf("job type %T does not have filesystems filter", j)
|
||||||
}
|
}
|
||||||
@@ -66,7 +75,7 @@ func runTestFilterCmd(subcommand *cli.Subcommand, args []string) error {
|
|||||||
if testFilterArgs.input != "" {
|
if testFilterArgs.input != "" {
|
||||||
fsnames = []string{testFilterArgs.input}
|
fsnames = []string{testFilterArgs.input}
|
||||||
} else {
|
} else {
|
||||||
out, err := zfs.ZFSList([]string{"name"})
|
out, err := zfs.ZFSList(ctx, []string{"name"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("could not list ZFS filesystems: %s", err)
|
return fmt.Errorf("could not list ZFS filesystems: %s", err)
|
||||||
}
|
}
|
||||||
@@ -109,10 +118,8 @@ func runTestFilterCmd(subcommand *cli.Subcommand, args []string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var testPlaceholderArgs struct {
|
var testPlaceholderArgs struct {
|
||||||
action string
|
ds string
|
||||||
ds string
|
all bool
|
||||||
plv string
|
|
||||||
all bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var testPlaceholder = &cli.Subcommand{
|
var testPlaceholder = &cli.Subcommand{
|
||||||
@@ -129,13 +136,15 @@ var testPlaceholder = &cli.Subcommand{
|
|||||||
Run: runTestPlaceholder,
|
Run: runTestPlaceholder,
|
||||||
}
|
}
|
||||||
|
|
||||||
func runTestPlaceholder(subcommand *cli.Subcommand, args []string) error {
|
func runTestPlaceholder(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
|
||||||
var checkDPs []*zfs.DatasetPath
|
var checkDPs []*zfs.DatasetPath
|
||||||
|
var datasetWasExplicitArgument bool
|
||||||
|
|
||||||
// all actions first
|
// all actions first
|
||||||
if testPlaceholderArgs.all {
|
if testPlaceholderArgs.all {
|
||||||
out, err := zfs.ZFSList([]string{"name"})
|
datasetWasExplicitArgument = false
|
||||||
|
out, err := zfs.ZFSList(ctx, []string{"name"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "could not list ZFS filesystems")
|
return errors.Wrap(err, "could not list ZFS filesystems")
|
||||||
}
|
}
|
||||||
@@ -147,6 +156,7 @@ func runTestPlaceholder(subcommand *cli.Subcommand, args []string) error {
|
|||||||
checkDPs = append(checkDPs, dp)
|
checkDPs = append(checkDPs, dp)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
datasetWasExplicitArgument = true
|
||||||
dp, err := zfs.NewDatasetPath(testPlaceholderArgs.ds)
|
dp, err := zfs.NewDatasetPath(testPlaceholderArgs.ds)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -159,12 +169,17 @@ func runTestPlaceholder(subcommand *cli.Subcommand, args []string) error {
|
|||||||
|
|
||||||
fmt.Printf("IS_PLACEHOLDER\tDATASET\tzrepl:placeholder\n")
|
fmt.Printf("IS_PLACEHOLDER\tDATASET\tzrepl:placeholder\n")
|
||||||
for _, dp := range checkDPs {
|
for _, dp := range checkDPs {
|
||||||
ph, err := zfs.ZFSGetFilesystemPlaceholderState(dp)
|
ph, err := zfs.ZFSGetFilesystemPlaceholderState(ctx, dp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "cannot get placeholder state")
|
return errors.Wrap(err, "cannot get placeholder state")
|
||||||
}
|
}
|
||||||
if !ph.FSExists {
|
if !ph.FSExists {
|
||||||
panic("placeholder state inconsistent: filesystem " + ph.FS + " must exist in this context")
|
if datasetWasExplicitArgument {
|
||||||
|
return errors.Errorf("filesystem %q does not exist", ph.FS)
|
||||||
|
} else {
|
||||||
|
// got deleted between ZFSList and ZFSGetFilesystemPlaceholderState
|
||||||
|
continue
|
||||||
|
}
|
||||||
}
|
}
|
||||||
is := "yes"
|
is := "yes"
|
||||||
if !ph.IsPlaceholder {
|
if !ph.IsPlaceholder {
|
||||||
@@ -174,3 +189,32 @@ func runTestPlaceholder(subcommand *cli.Subcommand, args []string) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var testDecodeResumeTokenArgs struct {
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
var testDecodeResumeToken = &cli.Subcommand{
|
||||||
|
Use: "decoderesumetoken --token TOKEN",
|
||||||
|
Short: "decode resume token",
|
||||||
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
|
f.StringVar(&testDecodeResumeTokenArgs.token, "token", "", "the resume token obtained from the receive_resume_token property")
|
||||||
|
},
|
||||||
|
Run: runTestDecodeResumeTokenCmd,
|
||||||
|
}
|
||||||
|
|
||||||
|
func runTestDecodeResumeTokenCmd(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
|
if testDecodeResumeTokenArgs.token == "" {
|
||||||
|
return fmt.Errorf("token argument must be specified")
|
||||||
|
}
|
||||||
|
token, err := zfs.ParseResumeToken(ctx, testDecodeResumeTokenArgs.token)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
if err := enc.Encode(&token); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
+9
-6
@@ -1,29 +1,32 @@
|
|||||||
package client
|
package client
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
"github.com/spf13/pflag"
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/cli"
|
"github.com/zrepl/zrepl/cli"
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon"
|
"github.com/zrepl/zrepl/daemon"
|
||||||
"github.com/zrepl/zrepl/version"
|
"github.com/zrepl/zrepl/version"
|
||||||
"os"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var versionArgs struct {
|
var versionArgs struct {
|
||||||
Show string
|
Show string
|
||||||
Config *config.Config
|
Config *config.Config
|
||||||
ConfigErr error
|
ConfigErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
var VersionCmd = &cli.Subcommand{
|
var VersionCmd = &cli.Subcommand{
|
||||||
Use: "version",
|
Use: "version",
|
||||||
Short: "print version of zrepl binary and running daemon",
|
Short: "print version of zrepl binary and running daemon",
|
||||||
NoRequireConfig: true,
|
NoRequireConfig: true,
|
||||||
SetupFlags: func(f *pflag.FlagSet) {
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
f.StringVar(&versionArgs.Show, "show", "", "version info to show (client|daemon)")
|
f.StringVar(&versionArgs.Show, "show", "", "version info to show (client|daemon)")
|
||||||
},
|
},
|
||||||
Run: func(subcommand *cli.Subcommand, args []string) error {
|
Run: func(ctx context.Context, subcommand *cli.Subcommand, args []string) error {
|
||||||
versionArgs.Config = subcommand.Config()
|
versionArgs.Config = subcommand.Config()
|
||||||
versionArgs.ConfigErr = subcommand.ConfigParsingError()
|
versionArgs.ConfigErr = subcommand.ConfigParsingError()
|
||||||
return runVersionCmd()
|
return runVersionCmd()
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ZFSAbstractionsCmd = &cli.Subcommand{
|
||||||
|
Use: "zfs-abstraction",
|
||||||
|
Short: "manage abstractions that zrepl builds on top of ZFS",
|
||||||
|
SetupSubcommands: func() []*cli.Subcommand {
|
||||||
|
return []*cli.Subcommand{
|
||||||
|
zabsCmdList,
|
||||||
|
zabsCmdReleaseAll,
|
||||||
|
zabsCmdReleaseStale,
|
||||||
|
zabsCmdCreate,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// a common set of CLI flags that map to the fields of an
|
||||||
|
// endpoint.ListZFSHoldsAndBookmarksQuery
|
||||||
|
type zabsFilterFlags struct {
|
||||||
|
Filesystems FilesystemsFilterFlag
|
||||||
|
Job JobIDFlag
|
||||||
|
Types AbstractionTypesFlag
|
||||||
|
Concurrency int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// produce a query from the CLI flags
|
||||||
|
func (f zabsFilterFlags) Query() (endpoint.ListZFSHoldsAndBookmarksQuery, error) {
|
||||||
|
q := endpoint.ListZFSHoldsAndBookmarksQuery{
|
||||||
|
FS: f.Filesystems.FlagValue(),
|
||||||
|
What: f.Types.FlagValue(),
|
||||||
|
JobID: f.Job.FlagValue(),
|
||||||
|
Concurrency: f.Concurrency,
|
||||||
|
}
|
||||||
|
return q, q.Validate()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *zabsFilterFlags) registerZabsFilterFlags(s *pflag.FlagSet, verb string) {
|
||||||
|
// Note: the default value is defined in the .FlagValue methods
|
||||||
|
s.Var(&f.Filesystems, "fs", fmt.Sprintf("only %s holds on the specified filesystem [default: all filesystems] [comma-separated list of <dataset-pattern>:<ok|!> pairs]", verb))
|
||||||
|
s.Var(&f.Job, "job", fmt.Sprintf("only %s holds created by the specified job [default: any job]", verb))
|
||||||
|
|
||||||
|
variants := make([]string, 0, len(endpoint.AbstractionTypesAll))
|
||||||
|
for v := range endpoint.AbstractionTypesAll {
|
||||||
|
variants = append(variants, string(v))
|
||||||
|
}
|
||||||
|
sort.Strings(variants)
|
||||||
|
variantsJoined := strings.Join(variants, "|")
|
||||||
|
s.Var(&f.Types, "type", fmt.Sprintf("only %s holds of the specified type [default: all] [comma-separated list of %s]", verb, variantsJoined))
|
||||||
|
|
||||||
|
s.Int64VarP(&f.Concurrency, "concurrency", "p", 1, "number of concurrently queried filesystems")
|
||||||
|
}
|
||||||
|
|
||||||
|
type JobIDFlag struct{ J *endpoint.JobID }
|
||||||
|
|
||||||
|
func (f *JobIDFlag) Set(s string) error {
|
||||||
|
if len(s) == 0 {
|
||||||
|
*f = JobIDFlag{J: nil}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
jobID, err := endpoint.MakeJobID(s)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*f = JobIDFlag{J: &jobID}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (f JobIDFlag) Type() string { return "job-ID" }
|
||||||
|
func (f JobIDFlag) String() string { return fmt.Sprint(f.J) }
|
||||||
|
func (f JobIDFlag) FlagValue() *endpoint.JobID { return f.J }
|
||||||
|
|
||||||
|
type AbstractionTypesFlag map[endpoint.AbstractionType]bool
|
||||||
|
|
||||||
|
func (f *AbstractionTypesFlag) Set(s string) error {
|
||||||
|
ats, err := endpoint.AbstractionTypeSetFromStrings(strings.Split(s, ","))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*f = AbstractionTypesFlag(ats)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (f AbstractionTypesFlag) Type() string { return "abstraction-type" }
|
||||||
|
func (f AbstractionTypesFlag) String() string {
|
||||||
|
return endpoint.AbstractionTypeSet(f).String()
|
||||||
|
}
|
||||||
|
func (f AbstractionTypesFlag) FlagValue() map[endpoint.AbstractionType]bool {
|
||||||
|
if len(f) > 0 {
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
return endpoint.AbstractionTypesAll
|
||||||
|
}
|
||||||
|
|
||||||
|
type FilesystemsFilterFlag struct {
|
||||||
|
F endpoint.ListZFSHoldsAndBookmarksQueryFilesystemFilter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (flag *FilesystemsFilterFlag) Set(s string) error {
|
||||||
|
mappings := strings.Split(s, ",")
|
||||||
|
if len(mappings) == 1 && !strings.Contains(mappings[0], ":") {
|
||||||
|
flag.F = endpoint.ListZFSHoldsAndBookmarksQueryFilesystemFilter{
|
||||||
|
FS: &mappings[0],
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f := filters.NewDatasetMapFilter(len(mappings), true)
|
||||||
|
for _, m := range mappings {
|
||||||
|
thisMappingErr := fmt.Errorf("expecting comma-separated list of <dataset-pattern>:<ok|!> pairs, got %q", m)
|
||||||
|
lhsrhs := strings.SplitN(m, ":", 2)
|
||||||
|
if len(lhsrhs) != 2 {
|
||||||
|
return thisMappingErr
|
||||||
|
}
|
||||||
|
err := f.Add(lhsrhs[0], lhsrhs[1])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %s", thisMappingErr, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flag.F = endpoint.ListZFSHoldsAndBookmarksQueryFilesystemFilter{
|
||||||
|
Filter: f,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
func (flag FilesystemsFilterFlag) Type() string { return "filesystem filter spec" }
|
||||||
|
func (flag FilesystemsFilterFlag) String() string {
|
||||||
|
return fmt.Sprintf("%v", flag.F)
|
||||||
|
}
|
||||||
|
func (flag FilesystemsFilterFlag) FlagValue() endpoint.ListZFSHoldsAndBookmarksQueryFilesystemFilter {
|
||||||
|
var z FilesystemsFilterFlag
|
||||||
|
if flag == z {
|
||||||
|
return endpoint.ListZFSHoldsAndBookmarksQueryFilesystemFilter{Filter: zfs.NoFilter()}
|
||||||
|
}
|
||||||
|
return flag.F
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import "github.com/zrepl/zrepl/cli"
|
||||||
|
|
||||||
|
var zabsCmdCreate = &cli.Subcommand{
|
||||||
|
Use: "create",
|
||||||
|
NoRequireConfig: true,
|
||||||
|
Short: `create zrepl ZFS abstractions (mostly useful for debugging & development, users should not need to use this command)`,
|
||||||
|
SetupSubcommands: func() []*cli.Subcommand {
|
||||||
|
return []*cli.Subcommand{
|
||||||
|
zabsCmdCreateStepHold,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
var zabsCreateStepHoldFlags struct {
|
||||||
|
target string
|
||||||
|
jobid JobIDFlag
|
||||||
|
}
|
||||||
|
|
||||||
|
var zabsCmdCreateStepHold = &cli.Subcommand{
|
||||||
|
Use: "step",
|
||||||
|
Run: doZabsCreateStep,
|
||||||
|
NoRequireConfig: true,
|
||||||
|
Short: `create a step hold or bookmark`,
|
||||||
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
|
f.StringVarP(&zabsCreateStepHoldFlags.target, "target", "t", "", "snapshot to be held / bookmark to be held")
|
||||||
|
f.VarP(&zabsCreateStepHoldFlags.jobid, "jobid", "j", "jobid for which the hold is installed")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func doZabsCreateStep(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
|
if len(args) > 0 {
|
||||||
|
return errors.New("subcommand takes no arguments")
|
||||||
|
}
|
||||||
|
|
||||||
|
f := &zabsCreateStepHoldFlags
|
||||||
|
|
||||||
|
fs, _, _, err := zfs.DecomposeVersionString(f.target)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "%q invalid target", f.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.jobid.FlagValue() == nil {
|
||||||
|
return errors.Errorf("jobid must be set")
|
||||||
|
}
|
||||||
|
|
||||||
|
v, err := zfs.ZFSGetFilesystemVersion(ctx, f.target)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "get info about target %q", f.target)
|
||||||
|
}
|
||||||
|
|
||||||
|
step, err := endpoint.HoldStep(ctx, fs, v, *f.jobid.FlagValue())
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "create step hold")
|
||||||
|
}
|
||||||
|
fmt.Println(step.String())
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/fatih/color"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/util/chainlock"
|
||||||
|
)
|
||||||
|
|
||||||
|
var zabsListFlags struct {
|
||||||
|
Filter zabsFilterFlags
|
||||||
|
Json bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var zabsCmdList = &cli.Subcommand{
|
||||||
|
Use: "list",
|
||||||
|
Short: `list zrepl ZFS abstractions`,
|
||||||
|
Run: doZabsList,
|
||||||
|
NoRequireConfig: true,
|
||||||
|
SetupFlags: func(f *pflag.FlagSet) {
|
||||||
|
zabsListFlags.Filter.registerZabsFilterFlags(f, "list")
|
||||||
|
f.BoolVar(&zabsListFlags.Json, "json", false, "emit JSON")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
func doZabsList(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if len(args) > 0 {
|
||||||
|
return errors.New("this subcommand takes no positional arguments")
|
||||||
|
}
|
||||||
|
|
||||||
|
q, err := zabsListFlags.Filter.Query()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "invalid filter specification on command line")
|
||||||
|
}
|
||||||
|
|
||||||
|
abstractions, errors, drainDone, err := endpoint.ListAbstractionsStreamed(ctx, q)
|
||||||
|
if err != nil {
|
||||||
|
return err // context clear by invocation of command
|
||||||
|
}
|
||||||
|
defer drainDone()
|
||||||
|
|
||||||
|
var line chainlock.L
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
defer wg.Wait()
|
||||||
|
|
||||||
|
// print results
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
for a := range abstractions {
|
||||||
|
func() {
|
||||||
|
defer line.Lock().Unlock()
|
||||||
|
if zabsListFlags.Json {
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
if err := enc.Encode(a); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
} else {
|
||||||
|
fmt.Println(a)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// print errors to stderr
|
||||||
|
errorColor := color.New(color.FgRed)
|
||||||
|
var errorsSlice []endpoint.ListAbstractionsError
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for err := range errors {
|
||||||
|
func() {
|
||||||
|
defer line.Lock().Unlock()
|
||||||
|
errorsSlice = append(errorsSlice, err)
|
||||||
|
errorColor.Fprintf(os.Stderr, "%s\n", err)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
wg.Wait()
|
||||||
|
if len(errorsSlice) > 0 {
|
||||||
|
errorColor.Add(color.Bold).Fprintf(os.Stderr, "there were errors in listing the abstractions")
|
||||||
|
return fmt.Errorf("")
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/fatih/color"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/spf13/pflag"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/cli"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
)
|
||||||
|
|
||||||
|
// shared between release-all and release-step
|
||||||
|
var zabsReleaseFlags struct {
|
||||||
|
Filter zabsFilterFlags
|
||||||
|
Json bool
|
||||||
|
DryRun bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerZabsReleaseFlags(s *pflag.FlagSet) {
|
||||||
|
zabsReleaseFlags.Filter.registerZabsFilterFlags(s, "release")
|
||||||
|
s.BoolVar(&zabsReleaseFlags.Json, "json", false, "emit json instead of pretty-printed")
|
||||||
|
s.BoolVar(&zabsReleaseFlags.DryRun, "dry-run", false, "do a dry-run")
|
||||||
|
}
|
||||||
|
|
||||||
|
var zabsCmdReleaseAll = &cli.Subcommand{
|
||||||
|
Use: "release-all",
|
||||||
|
Run: doZabsReleaseAll,
|
||||||
|
NoRequireConfig: true,
|
||||||
|
Short: `(DANGEROUS) release ALL zrepl ZFS abstractions (mostly useful for uninstalling zrepl completely or for "de-zrepl-ing" a filesystem)`,
|
||||||
|
SetupFlags: registerZabsReleaseFlags,
|
||||||
|
}
|
||||||
|
|
||||||
|
var zabsCmdReleaseStale = &cli.Subcommand{
|
||||||
|
Use: "release-stale",
|
||||||
|
Run: doZabsReleaseStale,
|
||||||
|
NoRequireConfig: true,
|
||||||
|
Short: `release stale zrepl ZFS abstractions (useful if zrepl has a bug and does not do it by itself)`,
|
||||||
|
SetupFlags: registerZabsReleaseFlags,
|
||||||
|
}
|
||||||
|
|
||||||
|
func doZabsReleaseAll(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if len(args) > 0 {
|
||||||
|
return errors.New("this subcommand takes no positional arguments")
|
||||||
|
}
|
||||||
|
|
||||||
|
q, err := zabsReleaseFlags.Filter.Query()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "invalid filter specification on command line")
|
||||||
|
}
|
||||||
|
|
||||||
|
abstractions, listErrors, err := endpoint.ListAbstractions(ctx, q)
|
||||||
|
if err != nil {
|
||||||
|
return err // context clear by invocation of command
|
||||||
|
}
|
||||||
|
if len(listErrors) > 0 {
|
||||||
|
color.New(color.FgRed).Fprintf(os.Stderr, "there were errors in listing the abstractions:\n%s\n", listErrors)
|
||||||
|
// proceed anyways with rest of abstractions
|
||||||
|
}
|
||||||
|
|
||||||
|
return doZabsRelease_Common(ctx, abstractions)
|
||||||
|
}
|
||||||
|
|
||||||
|
func doZabsReleaseStale(ctx context.Context, sc *cli.Subcommand, args []string) error {
|
||||||
|
|
||||||
|
var err error
|
||||||
|
|
||||||
|
if len(args) > 0 {
|
||||||
|
return errors.New("this subcommand takes no positional arguments")
|
||||||
|
}
|
||||||
|
|
||||||
|
q, err := zabsReleaseFlags.Filter.Query()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "invalid filter specification on command line")
|
||||||
|
}
|
||||||
|
|
||||||
|
stalenessInfo, err := endpoint.ListStale(ctx, q)
|
||||||
|
if err != nil {
|
||||||
|
return err // context clear by invocation of command
|
||||||
|
}
|
||||||
|
|
||||||
|
return doZabsRelease_Common(ctx, stalenessInfo.Stale)
|
||||||
|
}
|
||||||
|
|
||||||
|
func doZabsRelease_Common(ctx context.Context, destroy []endpoint.Abstraction) error {
|
||||||
|
|
||||||
|
if zabsReleaseFlags.DryRun {
|
||||||
|
if zabsReleaseFlags.Json {
|
||||||
|
m, err := json.MarshalIndent(destroy, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stdout.Write(m); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
} else {
|
||||||
|
for _, a := range destroy {
|
||||||
|
fmt.Printf("would destroy %s\n", a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
outcome := endpoint.BatchDestroy(ctx, destroy)
|
||||||
|
hadErr := false
|
||||||
|
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
enc.SetIndent("", " ")
|
||||||
|
colorErr := color.New(color.FgRed)
|
||||||
|
printfSuccess := color.New(color.FgGreen).FprintfFunc()
|
||||||
|
printfSection := color.New(color.Bold).FprintfFunc()
|
||||||
|
|
||||||
|
for res := range outcome {
|
||||||
|
hadErr = hadErr || res.DestroyErr != nil
|
||||||
|
if zabsReleaseFlags.Json {
|
||||||
|
err := enc.Encode(res)
|
||||||
|
if err != nil {
|
||||||
|
colorErr.Fprintf(os.Stderr, "cannot marshal there were errors in destroying the abstractions")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
printfSection(os.Stdout, "destroy %s ...", res.Abstraction)
|
||||||
|
if res.DestroyErr != nil {
|
||||||
|
colorErr.Fprintf(os.Stdout, " failed:\n%s\n", res.DestroyErr)
|
||||||
|
} else {
|
||||||
|
printfSuccess(os.Stdout, " OK\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hadErr {
|
||||||
|
colorErr.Add(color.Bold).Fprintf(os.Stderr, "there were errors in destroying the abstractions")
|
||||||
|
return fmt.Errorf("")
|
||||||
|
} else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
+274
-128
@@ -2,15 +2,25 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/pkg/errors"
|
|
||||||
"github.com/zrepl/yaml-config"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log/syslog"
|
"log/syslog"
|
||||||
"os"
|
"os"
|
||||||
"reflect"
|
"reflect"
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/robfig/cron/v3"
|
||||||
|
"github.com/zrepl/yaml-config"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/util/datasizeunit"
|
||||||
|
zfsprop "github.com/zrepl/zrepl/zfs/property"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ParseFlags uint
|
||||||
|
|
||||||
|
const (
|
||||||
|
ParseFlagsNone ParseFlags = 0
|
||||||
|
ParseFlagsNoCertCheck ParseFlags = 1 << iota
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@@ -34,11 +44,16 @@ type JobEnum struct {
|
|||||||
func (j JobEnum) Name() string {
|
func (j JobEnum) Name() string {
|
||||||
var name string
|
var name string
|
||||||
switch v := j.Ret.(type) {
|
switch v := j.Ret.(type) {
|
||||||
case *SnapJob: name = v.Name
|
case *SnapJob:
|
||||||
case *PushJob: name = v.Name
|
name = v.Name
|
||||||
case *SinkJob: name = v.Name
|
case *PushJob:
|
||||||
case *PullJob: name = v.Name
|
name = v.Name
|
||||||
case *SourceJob: name = v.Name
|
case *SinkJob:
|
||||||
|
name = v.Name
|
||||||
|
case *PullJob:
|
||||||
|
name = v.Name
|
||||||
|
case *SourceJob:
|
||||||
|
name = v.Name
|
||||||
default:
|
default:
|
||||||
panic(fmt.Sprintf("unknown job type %T", v))
|
panic(fmt.Sprintf("unknown job type %T", v))
|
||||||
}
|
}
|
||||||
@@ -46,41 +61,110 @@ func (j JobEnum) Name() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ActiveJob struct {
|
type ActiveJob struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Name string `yaml:"name"`
|
Name string `yaml:"name"`
|
||||||
Connect ConnectEnum `yaml:"connect"`
|
Connect ConnectEnum `yaml:"connect"`
|
||||||
Pruning PruningSenderReceiver `yaml:"pruning"`
|
Pruning PruningSenderReceiver `yaml:"pruning"`
|
||||||
Debug JobDebugSettings `yaml:"debug,optional"`
|
Replication *Replication `yaml:"replication,optional,fromdefaults"`
|
||||||
|
ConflictResolution *ConflictResolution `yaml:"conflict_resolution,optional,fromdefaults"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ConflictResolution struct {
|
||||||
|
InitialReplication string `yaml:"initial_replication,optional,default=most_recent"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PassiveJob struct {
|
type PassiveJob struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Name string `yaml:"name"`
|
Name string `yaml:"name"`
|
||||||
Serve ServeEnum `yaml:"serve"`
|
Serve ServeEnum `yaml:"serve"`
|
||||||
Debug JobDebugSettings `yaml:"debug,optional"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type SnapJob struct {
|
type SnapJob struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Name string `yaml:"name"`
|
Name string `yaml:"name"`
|
||||||
Pruning PruningLocal `yaml:"pruning"`
|
Pruning PruningLocal `yaml:"pruning"`
|
||||||
Debug JobDebugSettings `yaml:"debug,optional"`
|
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
||||||
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
||||||
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
}
|
||||||
|
|
||||||
|
type SendOptions struct {
|
||||||
|
Encrypted bool `yaml:"encrypted,optional,default=false"`
|
||||||
|
Raw bool `yaml:"raw,optional,default=false"`
|
||||||
|
SendProperties bool `yaml:"send_properties,optional,default=false"`
|
||||||
|
BackupProperties bool `yaml:"backup_properties,optional,default=false"`
|
||||||
|
LargeBlocks bool `yaml:"large_blocks,optional,default=false"`
|
||||||
|
Compressed bool `yaml:"compressed,optional,default=false"`
|
||||||
|
EmbeddedData bool `yaml:"embedded_data,optional,default=false"`
|
||||||
|
Saved bool `yaml:"saved,optional,default=false"`
|
||||||
|
|
||||||
|
BandwidthLimit *BandwidthLimit `yaml:"bandwidth_limit,optional,fromdefaults"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RecvOptions struct {
|
||||||
|
// Note: we cannot enforce encrypted recv as the ZFS cli doesn't provide a mechanism for it
|
||||||
|
// Encrypted bool `yaml:"may_encrypted"`
|
||||||
|
// Future:
|
||||||
|
// Reencrypt bool `yaml:"reencrypt"`
|
||||||
|
|
||||||
|
Properties *PropertyRecvOptions `yaml:"properties,fromdefaults"`
|
||||||
|
|
||||||
|
BandwidthLimit *BandwidthLimit `yaml:"bandwidth_limit,optional,fromdefaults"`
|
||||||
|
|
||||||
|
Placeholder *PlaceholderRecvOptions `yaml:"placeholder,fromdefaults"`
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ yaml.Unmarshaler = &datasizeunit.Bits{}
|
||||||
|
|
||||||
|
type BandwidthLimit struct {
|
||||||
|
Max datasizeunit.Bits `yaml:"max,default=-1 B"`
|
||||||
|
BucketCapacity datasizeunit.Bits `yaml:"bucket_capacity,default=128 KiB"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Replication struct {
|
||||||
|
Protection *ReplicationOptionsProtection `yaml:"protection,optional,fromdefaults"`
|
||||||
|
Concurrency *ReplicationOptionsConcurrency `yaml:"concurrency,optional,fromdefaults"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplicationOptionsProtection struct {
|
||||||
|
Initial string `yaml:"initial,optional,default=guarantee_resumability"`
|
||||||
|
Incremental string `yaml:"incremental,optional,default=guarantee_resumability"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReplicationOptionsConcurrency struct {
|
||||||
|
Steps int `yaml:"steps,optional,default=1"`
|
||||||
|
SizeEstimates int `yaml:"size_estimates,optional,default=4"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PropertyRecvOptions struct {
|
||||||
|
Inherit []zfsprop.Property `yaml:"inherit,optional"`
|
||||||
|
Override map[zfsprop.Property]string `yaml:"override,optional"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlaceholderRecvOptions struct {
|
||||||
|
Encryption string `yaml:"encryption,default=unspecified"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PushJob struct {
|
type PushJob struct {
|
||||||
ActiveJob `yaml:",inline"`
|
ActiveJob `yaml:",inline"`
|
||||||
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
||||||
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
||||||
|
Send *SendOptions `yaml:"send,fromdefaults,optional"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (j *PushJob) GetFilesystems() FilesystemsFilter { return j.Filesystems }
|
||||||
|
func (j *PushJob) GetSendOptions() *SendOptions { return j.Send }
|
||||||
|
|
||||||
type PullJob struct {
|
type PullJob struct {
|
||||||
ActiveJob `yaml:",inline"`
|
ActiveJob `yaml:",inline"`
|
||||||
RootFS string `yaml:"root_fs"`
|
RootFS string `yaml:"root_fs"`
|
||||||
Interval PositiveDurationOrManual `yaml:"interval"`
|
Interval PositiveDurationOrManual `yaml:"interval"`
|
||||||
|
Recv *RecvOptions `yaml:"recv,fromdefaults,optional"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (j *PullJob) GetRootFS() string { return j.RootFS }
|
||||||
|
func (j *PullJob) GetAppendClientIdentity() bool { return false }
|
||||||
|
func (j *PullJob) GetRecvOptions() *RecvOptions { return j.Recv }
|
||||||
|
|
||||||
type PositiveDurationOrManual struct {
|
type PositiveDurationOrManual struct {
|
||||||
Interval time.Duration
|
Interval time.Duration
|
||||||
Manual bool
|
Manual bool
|
||||||
@@ -101,28 +185,34 @@ func (i *PositiveDurationOrManual) UnmarshalYAML(u func(interface{}, bool) error
|
|||||||
return fmt.Errorf("value must not be empty")
|
return fmt.Errorf("value must not be empty")
|
||||||
default:
|
default:
|
||||||
i.Manual = false
|
i.Manual = false
|
||||||
i.Interval, err = time.ParseDuration(s)
|
i.Interval, err = parsePositiveDuration(s)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if i.Interval <= 0 {
|
|
||||||
return fmt.Errorf("value must be a positive duration, got %q", s)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type SinkJob struct {
|
type SinkJob struct {
|
||||||
PassiveJob `yaml:",inline"`
|
PassiveJob `yaml:",inline"`
|
||||||
RootFS string `yaml:"root_fs"`
|
RootFS string `yaml:"root_fs"`
|
||||||
|
Recv *RecvOptions `yaml:"recv,optional,fromdefaults"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (j *SinkJob) GetRootFS() string { return j.RootFS }
|
||||||
|
func (j *SinkJob) GetAppendClientIdentity() bool { return true }
|
||||||
|
func (j *SinkJob) GetRecvOptions() *RecvOptions { return j.Recv }
|
||||||
|
|
||||||
type SourceJob struct {
|
type SourceJob struct {
|
||||||
PassiveJob `yaml:",inline"`
|
PassiveJob `yaml:",inline"`
|
||||||
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
Snapshotting SnapshottingEnum `yaml:"snapshotting"`
|
||||||
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
||||||
|
Send *SendOptions `yaml:"send,optional,fromdefaults"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (j *SourceJob) GetFilesystems() FilesystemsFilter { return j.Filesystems }
|
||||||
|
func (j *SourceJob) GetSendOptions() *SendOptions { return j.Send }
|
||||||
|
|
||||||
type FilesystemsFilter map[string]bool
|
type FilesystemsFilter map[string]bool
|
||||||
|
|
||||||
type SnapshottingEnum struct {
|
type SnapshottingEnum struct {
|
||||||
@@ -130,9 +220,44 @@ type SnapshottingEnum struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SnapshottingPeriodic struct {
|
type SnapshottingPeriodic struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Prefix string `yaml:"prefix"`
|
Prefix string `yaml:"prefix"`
|
||||||
Interval time.Duration `yaml:"interval,positive"`
|
Interval *PositiveDuration `yaml:"interval"`
|
||||||
|
Hooks HookList `yaml:"hooks,optional"`
|
||||||
|
TimestampFormat string `yaml:"timestamp_format,optional,default=dense"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CronSpec struct {
|
||||||
|
Schedule cron.Schedule
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ yaml.Unmarshaler = &CronSpec{}
|
||||||
|
|
||||||
|
func (s *CronSpec) UnmarshalYAML(unmarshal func(v interface{}, not_strict bool) error) error {
|
||||||
|
var specString string
|
||||||
|
if err := unmarshal(&specString, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use standard cron format.
|
||||||
|
// Disable the various "descriptors" (@daily, etc)
|
||||||
|
// They are just aliases to "top of hour", "midnight", etc.
|
||||||
|
parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.SecondOptional)
|
||||||
|
|
||||||
|
sched, err := parser.Parse(specString)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "cron syntax invalid")
|
||||||
|
}
|
||||||
|
s.Schedule = sched
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type SnapshottingCron struct {
|
||||||
|
Type string `yaml:"type"`
|
||||||
|
Prefix string `yaml:"prefix"`
|
||||||
|
Cron CronSpec `yaml:"cron"`
|
||||||
|
Hooks HookList `yaml:"hooks,optional"`
|
||||||
|
TimestampFormat string `yaml:"timestamp_format,optional,default=dense"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SnapshottingManual struct {
|
type SnapshottingManual struct {
|
||||||
@@ -191,18 +316,18 @@ type ConnectEnum struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ConnectCommon struct {
|
type ConnectCommon struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TCPConnect struct {
|
type TCPConnect struct {
|
||||||
ConnectCommon `yaml:",inline"`
|
ConnectCommon `yaml:",inline"`
|
||||||
Address string `yaml:"address"`
|
Address string `yaml:"address,hostport"`
|
||||||
DialTimeout time.Duration `yaml:"dial_timeout,zeropositive,default=10s"`
|
DialTimeout time.Duration `yaml:"dial_timeout,zeropositive,default=10s"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TLSConnect struct {
|
type TLSConnect struct {
|
||||||
ConnectCommon `yaml:",inline"`
|
ConnectCommon `yaml:",inline"`
|
||||||
Address string `yaml:"address"`
|
Address string `yaml:"address,hostport"`
|
||||||
Ca string `yaml:"ca"`
|
Ca string `yaml:"ca"`
|
||||||
Cert string `yaml:"cert"`
|
Cert string `yaml:"cert"`
|
||||||
Key string `yaml:"key"`
|
Key string `yaml:"key"`
|
||||||
@@ -223,9 +348,10 @@ type SSHStdinserverConnect struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type LocalConnect struct {
|
type LocalConnect struct {
|
||||||
ConnectCommon `yaml:",inline"`
|
ConnectCommon `yaml:",inline"`
|
||||||
ListenerName string `yaml:"listener_name"`
|
ListenerName string `yaml:"listener_name"`
|
||||||
ClientIdentity string `yaml:"client_identity"`
|
ClientIdentity string `yaml:"client_identity"`
|
||||||
|
DialTimeout time.Duration `yaml:"dial_timeout,zeropositive,default=2s"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ServeEnum struct {
|
type ServeEnum struct {
|
||||||
@@ -233,18 +359,20 @@ type ServeEnum struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type ServeCommon struct {
|
type ServeCommon struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TCPServe struct {
|
type TCPServe struct {
|
||||||
ServeCommon `yaml:",inline"`
|
ServeCommon `yaml:",inline"`
|
||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen,hostport"`
|
||||||
Clients map[string]string `yaml:"clients"`
|
ListenFreeBind bool `yaml:"listen_freebind,default=false"`
|
||||||
|
Clients map[string]string `yaml:"clients"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TLSServe struct {
|
type TLSServe struct {
|
||||||
ServeCommon `yaml:",inline"`
|
ServeCommon `yaml:",inline"`
|
||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen,hostport"`
|
||||||
|
ListenFreeBind bool `yaml:"listen_freebind,default=false"`
|
||||||
Ca string `yaml:"ca"`
|
Ca string `yaml:"ca"`
|
||||||
Cert string `yaml:"cert"`
|
Cert string `yaml:"cert"`
|
||||||
Key string `yaml:"key"`
|
Key string `yaml:"key"`
|
||||||
@@ -253,12 +381,12 @@ type TLSServe struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type StdinserverServer struct {
|
type StdinserverServer struct {
|
||||||
ServeCommon `yaml:",inline"`
|
ServeCommon `yaml:",inline"`
|
||||||
ClientIdentities []string `yaml:"client_identities"`
|
ClientIdentities []string `yaml:"client_identities"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type LocalServe struct {
|
type LocalServe struct {
|
||||||
ServeCommon `yaml:",inline"`
|
ServeCommon `yaml:",inline"`
|
||||||
ListenerName string `yaml:"listener_name"`
|
ListenerName string `yaml:"listener_name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,18 +395,19 @@ type PruningEnum struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PruneKeepNotReplicated struct {
|
type PruneKeepNotReplicated struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
KeepSnapshotAtCursor bool `yaml:"keep_snapshot_at_cursor,optional,default=true"`
|
KeepSnapshotAtCursor bool `yaml:"keep_snapshot_at_cursor,optional,default=true"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PruneKeepLastN struct {
|
type PruneKeepLastN struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Count int `yaml:"count"`
|
Count int `yaml:"count"`
|
||||||
|
Regex string `yaml:"regex,optional"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PruneKeepRegex struct { // FIXME rename to KeepRegex
|
type PruneKeepRegex struct { // FIXME rename to KeepRegex
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Regex string `yaml:"regex"`
|
Regex string `yaml:"regex"`
|
||||||
Negate bool `yaml:"negate,optional,default=false"`
|
Negate bool `yaml:"negate,optional,default=false"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -301,12 +430,12 @@ type StdoutLoggingOutlet struct {
|
|||||||
type SyslogLoggingOutlet struct {
|
type SyslogLoggingOutlet struct {
|
||||||
LoggingOutletCommon `yaml:",inline"`
|
LoggingOutletCommon `yaml:",inline"`
|
||||||
Facility *SyslogFacility `yaml:"facility,optional,fromdefaults"`
|
Facility *SyslogFacility `yaml:"facility,optional,fromdefaults"`
|
||||||
RetryInterval time.Duration `yaml:"retry_interval,positive,default=10s"`
|
RetryInterval time.Duration `yaml:"retry_interval,positive,default=10s"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type TCPLoggingOutlet struct {
|
type TCPLoggingOutlet struct {
|
||||||
LoggingOutletCommon `yaml:",inline"`
|
LoggingOutletCommon `yaml:",inline"`
|
||||||
Address string `yaml:"address"`
|
Address string `yaml:"address,hostport"`
|
||||||
Net string `yaml:"net,default=tcp"`
|
Net string `yaml:"net,default=tcp"`
|
||||||
RetryInterval time.Duration `yaml:"retry_interval,positive,default=10s"`
|
RetryInterval time.Duration `yaml:"retry_interval,positive,default=10s"`
|
||||||
TLS *TCPLoggingOutletTLS `yaml:"tls,optional"`
|
TLS *TCPLoggingOutletTLS `yaml:"tls,optional"`
|
||||||
@@ -323,8 +452,9 @@ type MonitoringEnum struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PrometheusMonitoring struct {
|
type PrometheusMonitoring struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Listen string `yaml:"listen"`
|
Listen string `yaml:"listen,hostport"`
|
||||||
|
ListenFreeBind bool `yaml:"listen_freebind,default=false"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SyslogFacility syslog.Priority
|
type SyslogFacility syslog.Priority
|
||||||
@@ -347,12 +477,36 @@ type GlobalStdinServer struct {
|
|||||||
SockDir string `yaml:"sockdir,default=/var/run/zrepl/stdinserver"`
|
SockDir string `yaml:"sockdir,default=/var/run/zrepl/stdinserver"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type JobDebugSettings struct {
|
type HookList []HookEnum
|
||||||
Conn *struct {
|
|
||||||
ReadDump string `yaml:"read_dump"`
|
type HookEnum struct {
|
||||||
WriteDump string `yaml:"write_dump"`
|
Ret interface{}
|
||||||
} `yaml:"conn,optional"`
|
}
|
||||||
RPCLog bool `yaml:"rpc_log,optional,default=false"`
|
|
||||||
|
type HookCommand struct {
|
||||||
|
Path string `yaml:"path"`
|
||||||
|
Timeout time.Duration `yaml:"timeout,optional,positive,default=30s"`
|
||||||
|
Filesystems FilesystemsFilter `yaml:"filesystems,optional,default={'<': true}"`
|
||||||
|
HookSettingsCommon `yaml:",inline"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HookPostgresCheckpoint struct {
|
||||||
|
HookSettingsCommon `yaml:",inline"`
|
||||||
|
DSN string `yaml:"dsn"`
|
||||||
|
Timeout time.Duration `yaml:"timeout,optional,positive,default=30s"`
|
||||||
|
Filesystems FilesystemsFilter `yaml:"filesystems"` // required, user should not CHECKPOINT for every FS
|
||||||
|
}
|
||||||
|
|
||||||
|
type HookMySQLLockTables struct {
|
||||||
|
HookSettingsCommon `yaml:",inline"`
|
||||||
|
DSN string `yaml:"dsn"`
|
||||||
|
Timeout time.Duration `yaml:"timeout,optional,positive,default=30s"`
|
||||||
|
Filesystems FilesystemsFilter `yaml:"filesystems"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HookSettingsCommon struct {
|
||||||
|
Type string `yaml:"type"`
|
||||||
|
ErrIsFatal bool `yaml:"err_is_fatal,optional,default=false"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func enumUnmarshal(u func(interface{}, bool) error, types map[string]interface{}) (interface{}, error) {
|
func enumUnmarshal(u func(interface{}, bool) error, types map[string]interface{}) (interface{}, error) {
|
||||||
@@ -392,7 +546,7 @@ func (t *ConnectEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error)
|
|||||||
"tcp": &TCPConnect{},
|
"tcp": &TCPConnect{},
|
||||||
"tls": &TLSConnect{},
|
"tls": &TLSConnect{},
|
||||||
"ssh+stdinserver": &SSHStdinserverConnect{},
|
"ssh+stdinserver": &SSHStdinserverConnect{},
|
||||||
"local": &LocalConnect{},
|
"local": &LocalConnect{},
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -402,7 +556,7 @@ func (t *ServeEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
|||||||
"tcp": &TCPServe{},
|
"tcp": &TCPServe{},
|
||||||
"tls": &TLSServe{},
|
"tls": &TLSServe{},
|
||||||
"stdinserver": &StdinserverServer{},
|
"stdinserver": &StdinserverServer{},
|
||||||
"local" : &LocalServe{},
|
"local": &LocalServe{},
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -420,7 +574,8 @@ func (t *PruningEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error)
|
|||||||
func (t *SnapshottingEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
func (t *SnapshottingEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
||||||
t.Ret, err = enumUnmarshal(u, map[string]interface{}{
|
t.Ret, err = enumUnmarshal(u, map[string]interface{}{
|
||||||
"periodic": &SnapshottingPeriodic{},
|
"periodic": &SnapshottingPeriodic{},
|
||||||
"manual": &SnapshottingManual{},
|
"manual": &SnapshottingManual{},
|
||||||
|
"cron": &SnapshottingCron{},
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -448,31 +603,60 @@ func (t *SyslogFacility) UnmarshalYAML(u func(interface{}, bool) error) (err err
|
|||||||
}
|
}
|
||||||
var level syslog.Priority
|
var level syslog.Priority
|
||||||
switch s {
|
switch s {
|
||||||
case "kern": level = syslog.LOG_KERN
|
case "kern":
|
||||||
case "user": level = syslog.LOG_USER
|
level = syslog.LOG_KERN
|
||||||
case "mail": level = syslog.LOG_MAIL
|
case "user":
|
||||||
case "daemon": level = syslog.LOG_DAEMON
|
level = syslog.LOG_USER
|
||||||
case "auth": level = syslog.LOG_AUTH
|
case "mail":
|
||||||
case "syslog": level = syslog.LOG_SYSLOG
|
level = syslog.LOG_MAIL
|
||||||
case "lpr": level = syslog.LOG_LPR
|
case "daemon":
|
||||||
case "news": level = syslog.LOG_NEWS
|
level = syslog.LOG_DAEMON
|
||||||
case "uucp": level = syslog.LOG_UUCP
|
case "auth":
|
||||||
case "cron": level = syslog.LOG_CRON
|
level = syslog.LOG_AUTH
|
||||||
case "authpriv": level = syslog.LOG_AUTHPRIV
|
case "syslog":
|
||||||
case "ftp": level = syslog.LOG_FTP
|
level = syslog.LOG_SYSLOG
|
||||||
case "local0": level = syslog.LOG_LOCAL0
|
case "lpr":
|
||||||
case "local1": level = syslog.LOG_LOCAL1
|
level = syslog.LOG_LPR
|
||||||
case "local2": level = syslog.LOG_LOCAL2
|
case "news":
|
||||||
case "local3": level = syslog.LOG_LOCAL3
|
level = syslog.LOG_NEWS
|
||||||
case "local4": level = syslog.LOG_LOCAL4
|
case "uucp":
|
||||||
case "local5": level = syslog.LOG_LOCAL5
|
level = syslog.LOG_UUCP
|
||||||
case "local6": level = syslog.LOG_LOCAL6
|
case "cron":
|
||||||
case "local7": level = syslog.LOG_LOCAL7
|
level = syslog.LOG_CRON
|
||||||
|
case "authpriv":
|
||||||
|
level = syslog.LOG_AUTHPRIV
|
||||||
|
case "ftp":
|
||||||
|
level = syslog.LOG_FTP
|
||||||
|
case "local0":
|
||||||
|
level = syslog.LOG_LOCAL0
|
||||||
|
case "local1":
|
||||||
|
level = syslog.LOG_LOCAL1
|
||||||
|
case "local2":
|
||||||
|
level = syslog.LOG_LOCAL2
|
||||||
|
case "local3":
|
||||||
|
level = syslog.LOG_LOCAL3
|
||||||
|
case "local4":
|
||||||
|
level = syslog.LOG_LOCAL4
|
||||||
|
case "local5":
|
||||||
|
level = syslog.LOG_LOCAL5
|
||||||
|
case "local6":
|
||||||
|
level = syslog.LOG_LOCAL6
|
||||||
|
case "local7":
|
||||||
|
level = syslog.LOG_LOCAL7
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("invalid syslog level: %q", s)
|
return fmt.Errorf("invalid syslog level: %q", s)
|
||||||
}
|
}
|
||||||
*t = SyslogFacility(level)
|
*t = SyslogFacility(level)
|
||||||
return nil
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *HookEnum) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
||||||
|
t.Ret, err = enumUnmarshal(u, map[string]interface{}{
|
||||||
|
"command": &HookCommand{},
|
||||||
|
"postgres-checkpoint": &HookPostgresCheckpoint{},
|
||||||
|
"mysql-lock-tables": &HookMySQLLockTables{},
|
||||||
|
})
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var ConfigFileDefaultLocations = []string{
|
var ConfigFileDefaultLocations = []string{
|
||||||
@@ -517,41 +701,3 @@ func ParseConfigBytes(bytes []byte) (*Config, error) {
|
|||||||
}
|
}
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var durationStringRegex *regexp.Regexp = regexp.MustCompile(`^\s*(\d+)\s*(s|m|h|d|w)\s*$`)
|
|
||||||
|
|
||||||
func parsePostitiveDuration(e string) (d time.Duration, err error) {
|
|
||||||
comps := durationStringRegex.FindStringSubmatch(e)
|
|
||||||
if len(comps) != 3 {
|
|
||||||
err = fmt.Errorf("does not match regex: %s %#v", e, comps)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
durationFactor, err := strconv.ParseInt(comps[1], 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
if durationFactor <= 0 {
|
|
||||||
return 0, errors.New("duration must be positive integer")
|
|
||||||
}
|
|
||||||
|
|
||||||
var durationUnit time.Duration
|
|
||||||
switch comps[2] {
|
|
||||||
case "s":
|
|
||||||
durationUnit = time.Second
|
|
||||||
case "m":
|
|
||||||
durationUnit = time.Minute
|
|
||||||
case "h":
|
|
||||||
durationUnit = time.Hour
|
|
||||||
case "d":
|
|
||||||
durationUnit = 24 * time.Hour
|
|
||||||
case "w":
|
|
||||||
durationUnit = 24 * 7 * time.Hour
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("contains unknown time unit '%s'", comps[2])
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
d = time.Duration(durationFactor) * durationUnit
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"github.com/zrepl/yaml-config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type A struct {
|
||||||
|
B *B `yaml:"b,optional,fromdefaults"`
|
||||||
|
A1 string `yaml:"a1,optional"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type B struct {
|
||||||
|
C *C `yaml:"c,optional,fromdefaults"`
|
||||||
|
D string `yaml:"d,default=ddd"`
|
||||||
|
E string `yaml:"e,optional"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type C struct {
|
||||||
|
Q string `yaml:"q,optional"`
|
||||||
|
R string `yaml:"r,default=r"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDepFromDefaults(t *testing.T) {
|
||||||
|
|
||||||
|
type testcase struct {
|
||||||
|
name string
|
||||||
|
yaml string
|
||||||
|
expect *A
|
||||||
|
}
|
||||||
|
|
||||||
|
tcs := []testcase{
|
||||||
|
{
|
||||||
|
name: "empty",
|
||||||
|
yaml: `{}`,
|
||||||
|
expect: &A{
|
||||||
|
B: &B{
|
||||||
|
C: &C{
|
||||||
|
R: "r",
|
||||||
|
},
|
||||||
|
D: "ddd",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a1 set",
|
||||||
|
yaml: `{"a1":"blah"}`,
|
||||||
|
expect: &A{
|
||||||
|
A1: "blah",
|
||||||
|
B: &B{
|
||||||
|
C: &C{
|
||||||
|
R: "r",
|
||||||
|
},
|
||||||
|
D: "ddd",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "D set",
|
||||||
|
yaml: `
|
||||||
|
b:
|
||||||
|
d: 4d
|
||||||
|
`,
|
||||||
|
expect: &A{
|
||||||
|
B: &B{
|
||||||
|
D: "4d",
|
||||||
|
C: &C{
|
||||||
|
R: "r",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for tci := range tcs {
|
||||||
|
t.Run(fmt.Sprintf("%d-%s", tci, tcs[tci].name), func(t *testing.T) {
|
||||||
|
tc := tcs[tci]
|
||||||
|
|
||||||
|
var a A
|
||||||
|
err := yaml.UnmarshalStrict([]byte(tc.yaml), &a)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
require.Equal(t, tc.expect, &a)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/kr/pretty"
|
||||||
|
"github.com/zrepl/yaml-config"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Duration struct{ d time.Duration }
|
||||||
|
|
||||||
|
func (d Duration) Duration() time.Duration { return d.d }
|
||||||
|
|
||||||
|
var _ yaml.Unmarshaler = &Duration{}
|
||||||
|
|
||||||
|
func (d *Duration) UnmarshalYAML(unmarshal func(v interface{}, not_strict bool) error) error {
|
||||||
|
var s string
|
||||||
|
err := unmarshal(&s, false)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
d.d, err = parseDuration(s)
|
||||||
|
if err != nil {
|
||||||
|
d.d = 0
|
||||||
|
return &yaml.TypeError{Errors: []string{fmt.Sprintf("cannot parse value %q: %s", s, err)}}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type PositiveDuration struct{ d Duration }
|
||||||
|
|
||||||
|
var _ yaml.Unmarshaler = &PositiveDuration{}
|
||||||
|
|
||||||
|
func (d PositiveDuration) Duration() time.Duration { return d.d.Duration() }
|
||||||
|
|
||||||
|
func (d *PositiveDuration) UnmarshalYAML(unmarshal func(v interface{}, not_strict bool) error) error {
|
||||||
|
err := d.d.UnmarshalYAML(unmarshal)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if d.d.Duration() <= 0 {
|
||||||
|
return fmt.Errorf("duration must be positive, got %s", d.d.Duration())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parsePositiveDuration(e string) (time.Duration, error) {
|
||||||
|
d, err := parseDuration(e)
|
||||||
|
if err != nil {
|
||||||
|
return d, err
|
||||||
|
}
|
||||||
|
if d <= 0 {
|
||||||
|
return 0, errors.New("duration must be positive integer")
|
||||||
|
}
|
||||||
|
return d, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var durationStringRegex *regexp.Regexp = regexp.MustCompile(`^\s*([\+-]?\d+)\s*(|s|m|h|d|w)\s*$`)
|
||||||
|
|
||||||
|
func parseDuration(e string) (d time.Duration, err error) {
|
||||||
|
comps := durationStringRegex.FindStringSubmatch(e)
|
||||||
|
if comps == nil {
|
||||||
|
err = fmt.Errorf("must match %s", durationStringRegex)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(comps) != 3 {
|
||||||
|
panic(pretty.Sprint(comps))
|
||||||
|
}
|
||||||
|
|
||||||
|
durationFactor, err := strconv.ParseInt(comps[1], 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var durationUnit time.Duration
|
||||||
|
switch comps[2] {
|
||||||
|
case "":
|
||||||
|
if durationFactor != 0 {
|
||||||
|
err = fmt.Errorf("missing time unit")
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
// It's the case where user specified '0'.
|
||||||
|
// We want to allow this, just like time.ParseDuration.
|
||||||
|
}
|
||||||
|
case "s":
|
||||||
|
durationUnit = time.Second
|
||||||
|
case "m":
|
||||||
|
durationUnit = time.Minute
|
||||||
|
case "h":
|
||||||
|
durationUnit = time.Hour
|
||||||
|
case "d":
|
||||||
|
durationUnit = 24 * time.Hour
|
||||||
|
case "w":
|
||||||
|
durationUnit = 24 * 7 * time.Hour
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("contains unknown time unit '%s'", comps[2])
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
d = time.Duration(durationFactor) * durationUnit
|
||||||
|
return
|
||||||
|
}
|
||||||
@@ -2,11 +2,12 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log/syslog"
|
||||||
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"github.com/zrepl/yaml-config"
|
"github.com/zrepl/yaml-config"
|
||||||
"log/syslog"
|
|
||||||
"testing"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func testValidGlobalSection(t *testing.T, s string) *Config {
|
func testValidGlobalSection(t *testing.T, s string) *Config {
|
||||||
@@ -20,11 +21,11 @@ jobs:
|
|||||||
clients: {
|
clients: {
|
||||||
"10.0.0.1":"foo"
|
"10.0.0.1":"foo"
|
||||||
}
|
}
|
||||||
root_fs: zoot/foo
|
root_fs: zroot/foo
|
||||||
`
|
`
|
||||||
_, err := ParseConfigBytes([]byte(jobdef))
|
_, err := ParseConfigBytes([]byte(jobdef))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
return testValidConfig(t, s + jobdef)
|
return testValidConfig(t, s+jobdef)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestOutletTypes(t *testing.T) {
|
func TestOutletTypes(t *testing.T) {
|
||||||
@@ -69,9 +70,9 @@ func TestPrometheusMonitoring(t *testing.T) {
|
|||||||
global:
|
global:
|
||||||
monitoring:
|
monitoring:
|
||||||
- type: prometheus
|
- type: prometheus
|
||||||
listen: ':9091'
|
listen: ':9811'
|
||||||
`)
|
`)
|
||||||
assert.Equal(t, ":9091", conf.Global.Monitoring[0].Ret.(*PrometheusMonitoring).Listen)
|
assert.Equal(t, ":9811", conf.Global.Monitoring[0].Ret.(*PrometheusMonitoring).Listen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSyslogLoggingOutletFacility(t *testing.T) {
|
func TestSyslogLoggingOutletFacility(t *testing.T) {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
package config
|
||||||
@@ -2,6 +2,7 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -36,4 +37,4 @@ jobs:
|
|||||||
- type: last_n
|
- type: last_n
|
||||||
count: 1
|
count: 1
|
||||||
`)
|
`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
zfsprop "github.com/zrepl/zrepl/zfs/property"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRecvOptions(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: foo
|
||||||
|
type: pull
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: foo
|
||||||
|
client_identity: bar
|
||||||
|
root_fs: "zreplplatformtest"
|
||||||
|
%s
|
||||||
|
interval: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_properties_empty := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_inherit_empty := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
inherit:
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_inherit := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
inherit:
|
||||||
|
- testprop
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_override_empty := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
override:
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_override := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
override:
|
||||||
|
testprop2: "test123"
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_override_and_inherit := `
|
||||||
|
recv:
|
||||||
|
properties:
|
||||||
|
inherit:
|
||||||
|
- testprop
|
||||||
|
override:
|
||||||
|
testprop2: "test123"
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_empty := `
|
||||||
|
recv: {}
|
||||||
|
`
|
||||||
|
|
||||||
|
recv_not_specified := `
|
||||||
|
`
|
||||||
|
|
||||||
|
fill := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
|
||||||
|
t.Run("recv_inherit_empty", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_inherit_empty))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_inherit", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_inherit))
|
||||||
|
inherit := c.Jobs[0].Ret.(*PullJob).Recv.Properties.Inherit
|
||||||
|
assert.NotEmpty(t, inherit)
|
||||||
|
assert.Contains(t, inherit, zfsprop.Property("testprop"))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_override_empty", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_override_empty))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_override", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_override))
|
||||||
|
override := c.Jobs[0].Ret.(*PullJob).Recv.Properties.Override
|
||||||
|
require.Len(t, override, 1)
|
||||||
|
require.Equal(t, "test123", override["testprop2"])
|
||||||
|
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_override_and_inherit", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_override_and_inherit))
|
||||||
|
inherit := c.Jobs[0].Ret.(*PullJob).Recv.Properties.Inherit
|
||||||
|
override := c.Jobs[0].Ret.(*PullJob).Recv.Properties.Override
|
||||||
|
assert.NotEmpty(t, inherit)
|
||||||
|
assert.Contains(t, inherit, zfsprop.Property("testprop"))
|
||||||
|
assert.NotEmpty(t, override)
|
||||||
|
assert.Equal(t, "test123", override["testprop2"])
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_properties_empty", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_properties_empty))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("recv_empty", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_empty))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("send_not_specified", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(recv_not_specified))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSendOptions(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: foo
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: foo
|
||||||
|
client_identity: bar
|
||||||
|
filesystems: {"<": true}
|
||||||
|
%s
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`
|
||||||
|
encrypted_false := `
|
||||||
|
send:
|
||||||
|
encrypted: false
|
||||||
|
`
|
||||||
|
|
||||||
|
encrypted_true := `
|
||||||
|
send:
|
||||||
|
encrypted: true
|
||||||
|
`
|
||||||
|
|
||||||
|
raw_true := `
|
||||||
|
send:
|
||||||
|
raw: true
|
||||||
|
|
||||||
|
`
|
||||||
|
|
||||||
|
raw_false := `
|
||||||
|
send:
|
||||||
|
raw: false
|
||||||
|
|
||||||
|
`
|
||||||
|
|
||||||
|
raw_and_encrypted := `
|
||||||
|
send:
|
||||||
|
encrypted: true
|
||||||
|
raw: true
|
||||||
|
`
|
||||||
|
|
||||||
|
properties_and_encrypted := `
|
||||||
|
send:
|
||||||
|
encrypted: true
|
||||||
|
send_properties: true
|
||||||
|
`
|
||||||
|
|
||||||
|
properties_true := `
|
||||||
|
send:
|
||||||
|
send_properties: true
|
||||||
|
`
|
||||||
|
|
||||||
|
properties_false := `
|
||||||
|
send:
|
||||||
|
send_properties: false
|
||||||
|
`
|
||||||
|
|
||||||
|
send_empty := `
|
||||||
|
send: {}
|
||||||
|
`
|
||||||
|
|
||||||
|
send_not_specified := `
|
||||||
|
`
|
||||||
|
|
||||||
|
fill := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
|
||||||
|
t.Run("encrypted_false", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(encrypted_false))
|
||||||
|
encrypted := c.Jobs[0].Ret.(*PushJob).Send.Encrypted
|
||||||
|
assert.Equal(t, false, encrypted)
|
||||||
|
})
|
||||||
|
t.Run("encrypted_true", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(encrypted_true))
|
||||||
|
encrypted := c.Jobs[0].Ret.(*PushJob).Send.Encrypted
|
||||||
|
assert.Equal(t, true, encrypted)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("send_empty", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(send_empty))
|
||||||
|
encrypted := c.Jobs[0].Ret.(*PushJob).Send.Encrypted
|
||||||
|
assert.Equal(t, false, encrypted)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("properties_and_encrypted", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(properties_and_encrypted))
|
||||||
|
encrypted := c.Jobs[0].Ret.(*PushJob).Send.Encrypted
|
||||||
|
properties := c.Jobs[0].Ret.(*PushJob).Send.SendProperties
|
||||||
|
assert.Equal(t, true, encrypted)
|
||||||
|
assert.Equal(t, true, properties)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("properties_false", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(properties_false))
|
||||||
|
properties := c.Jobs[0].Ret.(*PushJob).Send.SendProperties
|
||||||
|
assert.Equal(t, false, properties)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("properties_true", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(properties_true))
|
||||||
|
properties := c.Jobs[0].Ret.(*PushJob).Send.SendProperties
|
||||||
|
assert.Equal(t, true, properties)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("raw_true", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(raw_true))
|
||||||
|
raw := c.Jobs[0].Ret.(*PushJob).Send.Raw
|
||||||
|
assert.Equal(t, true, raw)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("raw_false", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(raw_false))
|
||||||
|
raw := c.Jobs[0].Ret.(*PushJob).Send.Raw
|
||||||
|
assert.Equal(t, false, raw)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("raw_and_encrypted", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(raw_and_encrypted))
|
||||||
|
raw := c.Jobs[0].Ret.(*PushJob).Send.Raw
|
||||||
|
encrypted := c.Jobs[0].Ret.(*PushJob).Send.Encrypted
|
||||||
|
assert.Equal(t, true, raw)
|
||||||
|
assert.Equal(t, true, encrypted)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("send_not_specified", func(t *testing.T) {
|
||||||
|
c := testValidConfig(t, fill(send_not_specified))
|
||||||
|
assert.NotNil(t, c)
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
@@ -2,9 +2,10 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSnapshotting(t *testing.T) {
|
func TestSnapshotting(t *testing.T) {
|
||||||
@@ -34,10 +35,48 @@ jobs:
|
|||||||
snapshotting:
|
snapshotting:
|
||||||
type: periodic
|
type: periodic
|
||||||
prefix: zrepl_
|
prefix: zrepl_
|
||||||
|
timestamp_format: dense
|
||||||
interval: 10m
|
interval: 10m
|
||||||
`
|
`
|
||||||
|
cron := `
|
||||||
|
snapshotting:
|
||||||
|
type: cron
|
||||||
|
prefix: zrepl_
|
||||||
|
timestamp_format: human
|
||||||
|
cron: "10 * * * *"
|
||||||
|
`
|
||||||
|
|
||||||
fillSnapshotting := func(s string) string {return fmt.Sprintf(tmpl, s)}
|
periodicDaily := `
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
prefix: zrepl_
|
||||||
|
interval: 1d
|
||||||
|
`
|
||||||
|
|
||||||
|
hooks := `
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
prefix: zrepl_
|
||||||
|
interval: 10m
|
||||||
|
hooks:
|
||||||
|
- type: command
|
||||||
|
path: /tmp/path/to/command
|
||||||
|
- type: command
|
||||||
|
path: /tmp/path/to/command
|
||||||
|
filesystems: { "zroot<": true, "<": false }
|
||||||
|
- type: postgres-checkpoint
|
||||||
|
dsn: "host=localhost port=5432 user=postgres sslmode=disable"
|
||||||
|
filesystems: {
|
||||||
|
"tank/postgres/data11": true
|
||||||
|
}
|
||||||
|
- type: mysql-lock-tables
|
||||||
|
dsn: "root@tcp(localhost)/"
|
||||||
|
filesystems: {
|
||||||
|
"tank/mysql": true
|
||||||
|
}
|
||||||
|
`
|
||||||
|
|
||||||
|
fillSnapshotting := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
var c *Config
|
var c *Config
|
||||||
|
|
||||||
t.Run("manual", func(t *testing.T) {
|
t.Run("manual", func(t *testing.T) {
|
||||||
@@ -50,8 +89,88 @@ jobs:
|
|||||||
c = testValidConfig(t, fillSnapshotting(periodic))
|
c = testValidConfig(t, fillSnapshotting(periodic))
|
||||||
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingPeriodic)
|
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingPeriodic)
|
||||||
assert.Equal(t, "periodic", snp.Type)
|
assert.Equal(t, "periodic", snp.Type)
|
||||||
assert.Equal(t, 10*time.Minute, snp.Interval)
|
assert.Equal(t, 10*time.Minute, snp.Interval.Duration())
|
||||||
assert.Equal(t, "zrepl_" , snp.Prefix)
|
assert.Equal(t, "zrepl_", snp.Prefix)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("periodicDaily", func(t *testing.T) {
|
||||||
|
c = testValidConfig(t, fillSnapshotting(periodicDaily))
|
||||||
|
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingPeriodic)
|
||||||
|
assert.Equal(t, "periodic", snp.Type)
|
||||||
|
assert.Equal(t, 24*time.Hour, snp.Interval.Duration())
|
||||||
|
assert.Equal(t, "zrepl_", snp.Prefix)
|
||||||
|
assert.Equal(t, "dense", snp.TimestampFormat)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("cron", func(t *testing.T) {
|
||||||
|
c = testValidConfig(t, fillSnapshotting(cron))
|
||||||
|
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingCron)
|
||||||
|
assert.Equal(t, "cron", snp.Type)
|
||||||
|
assert.Equal(t, "zrepl_", snp.Prefix)
|
||||||
|
assert.Equal(t, "human", snp.TimestampFormat)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("hooks", func(t *testing.T) {
|
||||||
|
c = testValidConfig(t, fillSnapshotting(hooks))
|
||||||
|
hs := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingPeriodic).Hooks
|
||||||
|
assert.Equal(t, hs[0].Ret.(*HookCommand).Filesystems["<"], true)
|
||||||
|
assert.Equal(t, hs[1].Ret.(*HookCommand).Filesystems["zroot<"], true)
|
||||||
|
assert.Equal(t, hs[2].Ret.(*HookPostgresCheckpoint).Filesystems["tank/postgres/data11"], true)
|
||||||
|
assert.Equal(t, hs[3].Ret.(*HookMySQLLockTables).Filesystems["tank/mysql"], true)
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSnapshottingTimestampDefaults(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: foo
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: foo
|
||||||
|
client_identity: bar
|
||||||
|
filesystems: {"<": true}
|
||||||
|
%s
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`
|
||||||
|
|
||||||
|
periodic := `
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
prefix: zrepl_
|
||||||
|
interval: 10m
|
||||||
|
`
|
||||||
|
cron := `
|
||||||
|
snapshotting:
|
||||||
|
type: cron
|
||||||
|
prefix: zrepl_
|
||||||
|
cron: "10 * * * *"
|
||||||
|
`
|
||||||
|
|
||||||
|
fillSnapshotting := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
var c *Config
|
||||||
|
|
||||||
|
t.Run("periodic", func(t *testing.T) {
|
||||||
|
c = testValidConfig(t, fillSnapshotting(periodic))
|
||||||
|
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingPeriodic)
|
||||||
|
assert.Equal(t, "periodic", snp.Type)
|
||||||
|
assert.Equal(t, 10*time.Minute, snp.Interval.Duration())
|
||||||
|
assert.Equal(t, "zrepl_", snp.Prefix)
|
||||||
|
assert.Equal(t, "dense", snp.TimestampFormat) // default was set correctly
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("cron", func(t *testing.T) {
|
||||||
|
c = testValidConfig(t, fillSnapshotting(cron))
|
||||||
|
snp := c.Jobs[0].Ret.(*PushJob).Snapshotting.Ret.(*SnapshottingCron)
|
||||||
|
assert.Equal(t, "cron", snp.Type)
|
||||||
|
assert.Equal(t, "zrepl_", snp.Prefix)
|
||||||
|
assert.Equal(t, "dense", snp.TimestampFormat) // default was set correctly
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|||||||
+75
-1
@@ -1,14 +1,19 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"fmt"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"text/template"
|
"text/template"
|
||||||
|
|
||||||
"github.com/kr/pretty"
|
"github.com/kr/pretty"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
|
"github.com/zrepl/yaml-config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestSampleConfigsAreParsedWithoutErrors(t *testing.T) {
|
func TestSampleConfigsAreParsedWithoutErrors(t *testing.T) {
|
||||||
@@ -38,7 +43,9 @@ func TestSampleConfigsAreParsedWithoutErrors(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// template must be a template/text template with a single '{{ . }}' as placehodler for val
|
// template must be a template/text template with a single '{{ . }}' as placeholder for val
|
||||||
|
//
|
||||||
|
//nolint:deadcode,unused
|
||||||
func testValidConfigTemplate(t *testing.T, tmpl string, val string) *Config {
|
func testValidConfigTemplate(t *testing.T, tmpl string, val string) *Config {
|
||||||
tmp, err := template.New("master").Parse(tmpl)
|
tmp, err := template.New("master").Parse(tmpl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -64,3 +71,70 @@ func testConfig(t *testing.T, input string) (*Config, error) {
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
return ParseConfigBytes([]byte(input))
|
return ParseConfigBytes([]byte(input))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func trimSpaceEachLineAndPad(s, pad string) string {
|
||||||
|
var out strings.Builder
|
||||||
|
scan := bufio.NewScanner(strings.NewReader(s))
|
||||||
|
for scan.Scan() {
|
||||||
|
fmt.Fprintf(&out, "%s%s\n", pad, bytes.TrimSpace(scan.Bytes()))
|
||||||
|
}
|
||||||
|
return out.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTrimSpaceEachLineAndPad(t *testing.T) {
|
||||||
|
foo := `
|
||||||
|
foo
|
||||||
|
bar baz
|
||||||
|
`
|
||||||
|
assert.Equal(t, " \n foo\n bar baz\n \n", trimSpaceEachLineAndPad(foo, " "))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCronSpec(t *testing.T) {
|
||||||
|
|
||||||
|
expectAccept := []string{
|
||||||
|
`"* * * * *"`,
|
||||||
|
`"0-10 * * * *"`,
|
||||||
|
`"* 0-5,8,12 * * *"`,
|
||||||
|
}
|
||||||
|
|
||||||
|
expectFail := []string{
|
||||||
|
`* * * *`,
|
||||||
|
``,
|
||||||
|
`23`,
|
||||||
|
`"@reboot"`,
|
||||||
|
`"@every 1h30m"`,
|
||||||
|
`"@daily"`,
|
||||||
|
`* * * * * *`,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, input := range expectAccept {
|
||||||
|
t.Run(input, func(t *testing.T) {
|
||||||
|
s := fmt.Sprintf("spec: %s\n", input)
|
||||||
|
var v struct {
|
||||||
|
Spec CronSpec
|
||||||
|
}
|
||||||
|
v.Spec.Schedule = nil
|
||||||
|
t.Logf("input:\n%s", s)
|
||||||
|
err := yaml.UnmarshalStrict([]byte(s), &v)
|
||||||
|
t.Logf("error: %T %s", err, err)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, v.Spec.Schedule)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, input := range expectFail {
|
||||||
|
t.Run(input, func(t *testing.T) {
|
||||||
|
s := fmt.Sprintf("spec: %s\n", input)
|
||||||
|
var v struct {
|
||||||
|
Spec CronSpec
|
||||||
|
}
|
||||||
|
v.Spec.Schedule = nil
|
||||||
|
t.Logf("input: %q", s)
|
||||||
|
err := yaml.UnmarshalStrict([]byte(s), &v)
|
||||||
|
t.Logf("error: %T %s", err, err)
|
||||||
|
require.Error(t, err)
|
||||||
|
require.Nil(t, v.Spec.Schedule)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTransportConnect(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: foo
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
%s
|
||||||
|
filesystems: {"<": true}
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`
|
||||||
|
|
||||||
|
mconf := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
|
||||||
|
type test struct {
|
||||||
|
Name string
|
||||||
|
ExpectError bool
|
||||||
|
Connect string
|
||||||
|
}
|
||||||
|
|
||||||
|
testTable := []test{
|
||||||
|
{
|
||||||
|
Name: "tcp_with_address_and_port",
|
||||||
|
ExpectError: false,
|
||||||
|
Connect: `
|
||||||
|
type: tcp
|
||||||
|
address: 10.0.0.23:42
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "tls_with_host_and_port",
|
||||||
|
ExpectError: false,
|
||||||
|
Connect: `
|
||||||
|
type: tls
|
||||||
|
address: "server1.foo.bar:8888"
|
||||||
|
ca: /etc/zrepl/ca.crt
|
||||||
|
cert: /etc/zrepl/backupserver.fullchain
|
||||||
|
key: /etc/zrepl/backupserver.key
|
||||||
|
server_cn: "server1"
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "tcp_without_port",
|
||||||
|
ExpectError: true,
|
||||||
|
Connect: `
|
||||||
|
type: tcp
|
||||||
|
address: 10.0.0.23
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "tls_without_port",
|
||||||
|
ExpectError: true,
|
||||||
|
Connect: `
|
||||||
|
type: tls
|
||||||
|
address: 10.0.0.23
|
||||||
|
ca: /etc/zrepl/ca.crt
|
||||||
|
cert: /etc/zrepl/backupserver.fullchain
|
||||||
|
key: /etc/zrepl/backupserver.key
|
||||||
|
server_cn: "server1"
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range testTable {
|
||||||
|
t.Run(tc.Name, func(t *testing.T) {
|
||||||
|
require.NotEmpty(t, tc.Connect)
|
||||||
|
connect := trimSpaceEachLineAndPad(tc.Connect, " ")
|
||||||
|
conf := mconf(connect)
|
||||||
|
config, err := testConfig(t, conf)
|
||||||
|
if tc.ExpectError && err == nil {
|
||||||
|
t.Errorf("expected test failure, but got valid config %v", config)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !tc.ExpectError && err != nil {
|
||||||
|
t.Errorf("not expecint test failure but got error: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Logf("error=%v", err)
|
||||||
|
t.Logf("config=%v", config)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+6
-10
@@ -11,9 +11,9 @@ import (
|
|||||||
type RetentionIntervalList []RetentionInterval
|
type RetentionIntervalList []RetentionInterval
|
||||||
|
|
||||||
type PruneGrid struct {
|
type PruneGrid struct {
|
||||||
Type string `yaml:"type"`
|
Type string `yaml:"type"`
|
||||||
Grid RetentionIntervalList `yaml:"grid"`
|
Grid RetentionIntervalList `yaml:"grid"`
|
||||||
Regex string `yaml:"regex"`
|
Regex string `yaml:"regex"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type RetentionInterval struct {
|
type RetentionInterval struct {
|
||||||
@@ -31,17 +31,13 @@ func (i *RetentionInterval) KeepCount() int {
|
|||||||
|
|
||||||
const RetentionGridKeepCountAll int = -1
|
const RetentionGridKeepCountAll int = -1
|
||||||
|
|
||||||
type RetentionGrid struct {
|
|
||||||
intervals []RetentionInterval
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t *RetentionIntervalList) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
func (t *RetentionIntervalList) UnmarshalYAML(u func(interface{}, bool) error) (err error) {
|
||||||
var in string
|
var in string
|
||||||
if err := u(&in, true); err != nil {
|
if err := u(&in, true); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
intervals, err := parseRetentionGridIntervalsString(in)
|
intervals, err := ParseRetentionIntervalSpec(in)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -68,7 +64,7 @@ func parseRetentionGridIntervalString(e string) (intervals []RetentionInterval,
|
|||||||
return nil, fmt.Errorf("contains factor <= 0")
|
return nil, fmt.Errorf("contains factor <= 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
duration, err := parsePostitiveDuration(comps[2])
|
duration, err := parsePositiveDuration(comps[2])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -106,7 +102,7 @@ func parseRetentionGridIntervalString(e string) (intervals []RetentionInterval,
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseRetentionGridIntervalsString(s string) (intervals []RetentionInterval, err error) {
|
func ParseRetentionIntervalSpec(s string) (intervals []RetentionInterval, err error) {
|
||||||
|
|
||||||
ges := strings.Split(s, "|")
|
ges := strings.Split(s, "|")
|
||||||
intervals = make([]RetentionInterval, 0, 7*len(ges))
|
intervals = make([]RetentionInterval, 0, 7*len(ges))
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
|
||||||
|
jobs:
|
||||||
|
- type: sink
|
||||||
|
name: "limited_sink"
|
||||||
|
root_fs: "fs0"
|
||||||
|
recv:
|
||||||
|
bandwidth_limit:
|
||||||
|
max: 12345 B
|
||||||
|
serve:
|
||||||
|
type: local
|
||||||
|
listener_name: localsink
|
||||||
|
|
||||||
|
- type: push
|
||||||
|
name: "limited_push"
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: localsink
|
||||||
|
client_identity: local_backup
|
||||||
|
filesystems: {
|
||||||
|
"root<": true,
|
||||||
|
}
|
||||||
|
send:
|
||||||
|
bandwidth_limit:
|
||||||
|
max: 54321 B
|
||||||
|
bucket_capacity: 1024 B
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 1
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 1
|
||||||
|
|
||||||
|
- type: sink
|
||||||
|
name: "nolimit_sink"
|
||||||
|
root_fs: "fs1"
|
||||||
|
serve:
|
||||||
|
type: local
|
||||||
|
listener_name: localsink
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
[ "$ZREPL_DRYRUN" = "true" ] && DRYRUN="echo DRYRUN: "
|
||||||
|
|
||||||
|
pre_snapshot() {
|
||||||
|
$DRYRUN date
|
||||||
|
}
|
||||||
|
|
||||||
|
post_snapshot() {
|
||||||
|
$DRYRUN date
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$ZREPL_HOOKTYPE" in
|
||||||
|
pre_snapshot|post_snapshot)
|
||||||
|
"$ZREPL_HOOKTYPE"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
printf 'Unrecognized hook type: %s\n' "$ZREPL_HOOKTYPE"
|
||||||
|
exit 255
|
||||||
|
;;
|
||||||
|
esac
|
||||||
@@ -9,7 +9,7 @@ jobs:
|
|||||||
port: 22
|
port: 22
|
||||||
identity_file: /etc/zrepl/ssh/identity
|
identity_file: /etc/zrepl/ssh/identity
|
||||||
options: # optional, default [], `-o` arguments passed to ssh
|
options: # optional, default [], `-o` arguments passed to ssh
|
||||||
- "Compression=on"
|
- "Compression=yes"
|
||||||
root_fs: "pool2/backup_servers"
|
root_fs: "pool2/backup_servers"
|
||||||
interval: 10m
|
interval: 10m
|
||||||
pruning:
|
pruning:
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ jobs:
|
|||||||
address: "backup-server.foo.bar:8888"
|
address: "backup-server.foo.bar:8888"
|
||||||
snapshotting:
|
snapshotting:
|
||||||
type: manual
|
type: manual
|
||||||
|
send:
|
||||||
|
encrypted: false
|
||||||
pruning:
|
pruning:
|
||||||
keep_sender:
|
keep_sender:
|
||||||
- type: not_replicated
|
- type: not_replicated
|
||||||
|
|||||||
@@ -0,0 +1,88 @@
|
|||||||
|
# This config serves as an example for a local zrepl installation that
|
||||||
|
# backups the entire zpool `system` to `backuppool/zrepl/sink`
|
||||||
|
#
|
||||||
|
# The requirements covered by this setup are described in the zrepl documentation's
|
||||||
|
# quick start section which inlines this example.
|
||||||
|
#
|
||||||
|
# CUSTOMIZATIONS YOU WILL LIKELY WANT TO APPLY:
|
||||||
|
# - adjust the name of the production pool `system` in the `filesystems` filter of jobs `snapjob` and `push_to_drive`
|
||||||
|
# - adjust the name of the backup pool `backuppool` in the `backuppool_sink` job
|
||||||
|
# - adjust the occurences of `myhostname` to the name of the system you are backing up (cannot be easily changed once you start replicating)
|
||||||
|
# - make sure the `zrepl_` prefix is not being used by any other zfs tools you might have installed (it likely isn't)
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
# this job takes care of snapshot creation + pruning
|
||||||
|
- name: snapjob
|
||||||
|
type: snap
|
||||||
|
filesystems: {
|
||||||
|
"system<": true,
|
||||||
|
}
|
||||||
|
# create snapshots with prefix `zrepl_` every 15 minutes
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
interval: 15m
|
||||||
|
prefix: zrepl_
|
||||||
|
pruning:
|
||||||
|
keep:
|
||||||
|
# fade-out scheme for snapshots starting with `zrepl_`
|
||||||
|
# - keep all created in the last hour
|
||||||
|
# - then destroy snapshots such that we keep 24 each 1 hour apart
|
||||||
|
# - then destroy snapshots such that we keep 14 each 1 day apart
|
||||||
|
# - then destroy all older snapshots
|
||||||
|
- type: grid
|
||||||
|
grid: 1x1h(keep=all) | 24x1h | 14x1d
|
||||||
|
regex: "^zrepl_.*"
|
||||||
|
# keep all snapshots that don't have the `zrepl_` prefix
|
||||||
|
- type: regex
|
||||||
|
negate: true
|
||||||
|
regex: "^zrepl_.*"
|
||||||
|
|
||||||
|
# This job pushes to the local sink defined in job `backuppool_sink`.
|
||||||
|
# We trigger replication manually from the command line / udev rules using
|
||||||
|
# `zrepl signal wakeup push_to_drive`
|
||||||
|
- type: push
|
||||||
|
name: push_to_drive
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: backuppool_sink
|
||||||
|
client_identity: myhostname
|
||||||
|
filesystems: {
|
||||||
|
"system<": true
|
||||||
|
}
|
||||||
|
send:
|
||||||
|
encrypted: true
|
||||||
|
replication:
|
||||||
|
protection:
|
||||||
|
initial: guarantee_resumability
|
||||||
|
# Downgrade protection to guarantee_incremental which uses zfs bookmarks instead of zfs holds.
|
||||||
|
# Thus, when we yank out the backup drive during replication
|
||||||
|
# - we might not be able to resume the interrupted replication step because the partially received `to` snapshot of a `from`->`to` step may be pruned any time
|
||||||
|
# - but in exchange we get back the disk space allocated by `to` when we prune it
|
||||||
|
# - and because we still have the bookmarks created by `guarantee_incremental`, we can still do incremental replication of `from`->`to2` in the future
|
||||||
|
incremental: guarantee_incremental
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
# no-op prune rule on sender (keep all snapshots), job `snapshot` takes care of this
|
||||||
|
keep_sender:
|
||||||
|
- type: regex
|
||||||
|
regex: ".*"
|
||||||
|
# retain
|
||||||
|
keep_receiver:
|
||||||
|
# longer retention on the backup drive, we have more space there
|
||||||
|
- type: grid
|
||||||
|
grid: 1x1h(keep=all) | 24x1h | 360x1d
|
||||||
|
regex: "^zrepl_.*"
|
||||||
|
# retain all non-zrepl snapshots on the backup drive
|
||||||
|
- type: regex
|
||||||
|
negate: true
|
||||||
|
regex: "^zrepl_.*"
|
||||||
|
|
||||||
|
# This job receives from job `push_to_drive` into `backuppool/zrepl/sink/myhostname`
|
||||||
|
- type: sink
|
||||||
|
name: backuppool_sink
|
||||||
|
root_fs: "backuppool/zrepl/sink"
|
||||||
|
serve:
|
||||||
|
type: local
|
||||||
|
listener_name: backuppool_sink
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
jobs:
|
||||||
|
- name: sink
|
||||||
|
type: sink
|
||||||
|
serve:
|
||||||
|
type: tls
|
||||||
|
listen: ":8888"
|
||||||
|
ca: "/etc/zrepl/prod.crt"
|
||||||
|
cert: "/etc/zrepl/backups.crt"
|
||||||
|
key: "/etc/zrepl/backups.key"
|
||||||
|
client_cns:
|
||||||
|
- "prod"
|
||||||
|
root_fs: "storage/zrepl/sink"
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
jobs:
|
||||||
|
- name: prod_to_backups
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
type: tls
|
||||||
|
address: "backups.example.com:8888"
|
||||||
|
ca: /etc/zrepl/backups.crt
|
||||||
|
cert: /etc/zrepl/prod.crt
|
||||||
|
key: /etc/zrepl/prod.key
|
||||||
|
server_cn: "backups"
|
||||||
|
filesystems: {
|
||||||
|
"zroot<": true,
|
||||||
|
"zroot/var/tmp<": false,
|
||||||
|
"zroot/usr/home/paranoid": false
|
||||||
|
}
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
prefix: zrepl_
|
||||||
|
interval: 10m
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: not_replicated
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: grid
|
||||||
|
grid: 1x1h(keep=all) | 24x1h | 30x1d | 6x30d
|
||||||
|
regex: "^zrepl_"
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
jobs:
|
||||||
|
# Separate job for snapshots and pruning
|
||||||
|
- name: snapshots
|
||||||
|
type: snap
|
||||||
|
filesystems:
|
||||||
|
'tank<': true # all filesystems
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
prefix: zrepl_
|
||||||
|
interval: 10m
|
||||||
|
pruning:
|
||||||
|
keep:
|
||||||
|
# Keep non-zrepl snapshots
|
||||||
|
- type: regex
|
||||||
|
negate: true
|
||||||
|
regex: '^zrepl_'
|
||||||
|
# Time-based snapshot retention
|
||||||
|
- type: grid
|
||||||
|
grid: 1x1h(keep=all) | 24x1h | 30x1d | 12x30d
|
||||||
|
regex: '^zrepl_'
|
||||||
|
|
||||||
|
# Source job for target B
|
||||||
|
- name: target_b
|
||||||
|
type: source
|
||||||
|
serve:
|
||||||
|
type: tls
|
||||||
|
listen: :8888
|
||||||
|
ca: /etc/zrepl/b.example.com.crt
|
||||||
|
cert: /etc/zrepl/a.example.com.crt
|
||||||
|
key: /etc/zrepl/a.example.com.key
|
||||||
|
client_cns:
|
||||||
|
- b.example.com
|
||||||
|
filesystems:
|
||||||
|
'tank<': true # all filesystems
|
||||||
|
# Snapshots are handled by the separate snap job
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
|
||||||
|
# Source job for target C
|
||||||
|
- name: target_c
|
||||||
|
type: source
|
||||||
|
serve:
|
||||||
|
type: tls
|
||||||
|
listen: :8889
|
||||||
|
ca: /etc/zrepl/c.example.com.crt
|
||||||
|
cert: /etc/zrepl/a.example.com.crt
|
||||||
|
key: /etc/zrepl/a.example.com.key
|
||||||
|
client_cns:
|
||||||
|
- c.example.com
|
||||||
|
filesystems:
|
||||||
|
'tank<': true # all filesystems
|
||||||
|
# Snapshots are handled by the separate snap job
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
|
||||||
|
# Source jobs for remaining targets. Each one should listen on a different port
|
||||||
|
# and reference the correct certificate and client CN.
|
||||||
|
# - name: target_c
|
||||||
|
# ...
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
jobs:
|
||||||
|
# Pull from source server A
|
||||||
|
- name: source_a
|
||||||
|
type: pull
|
||||||
|
connect:
|
||||||
|
type: tls
|
||||||
|
# Use the correct port for this specific client (eg. B is 8888, C is 8889, etc.)
|
||||||
|
address: a.example.com:8888
|
||||||
|
ca: /etc/zrepl/a.example.com.crt
|
||||||
|
# Use the correct key pair for this specific client
|
||||||
|
cert: /etc/zrepl/b.example.com.crt
|
||||||
|
key: /etc/zrepl/b.example.com.key
|
||||||
|
server_cn: a.example.com
|
||||||
|
root_fs: pool0/backup
|
||||||
|
interval: 10m
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
# Source does the pruning in its snap job
|
||||||
|
- type: regex
|
||||||
|
regex: '.*'
|
||||||
|
# Receiver-side pruning can be configured as desired on each target server
|
||||||
|
keep_receiver:
|
||||||
|
# Keep non-zrepl snapshots
|
||||||
|
- type: regex
|
||||||
|
negate: true
|
||||||
|
regex: '^zrepl_'
|
||||||
|
# Time-based snapshot retention
|
||||||
|
- type: grid
|
||||||
|
grid: 1x1h(keep=all) | 24x1h | 30x1d | 12x30d
|
||||||
|
regex: '^zrepl_'
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
jobs:
|
||||||
|
- name: snapjob
|
||||||
|
type: snap
|
||||||
|
filesystems: {
|
||||||
|
"tank<": true,
|
||||||
|
}
|
||||||
|
snapshotting:
|
||||||
|
type: cron
|
||||||
|
prefix: zrepl_snapjob_
|
||||||
|
cron: "*/5 * * * *"
|
||||||
|
pruning:
|
||||||
|
keep:
|
||||||
|
- type: last_n
|
||||||
|
count: 60
|
||||||
@@ -5,7 +5,11 @@ jobs:
|
|||||||
type: tcp
|
type: tcp
|
||||||
listen: "0.0.0.0:8888"
|
listen: "0.0.0.0:8888"
|
||||||
clients: {
|
clients: {
|
||||||
"192.168.122.123" : "client1"
|
"192.168.122.123" : "mysql01",
|
||||||
|
"192.168.122.42" : "mx01",
|
||||||
|
"2001:0db8:85a3::8a2e:0370:7334": "gateway",
|
||||||
|
"10.23.42.0/24": "cluster-*",
|
||||||
|
"fde4:8dba:82e1::/64": "san-*",
|
||||||
}
|
}
|
||||||
filesystems: {
|
filesystems: {
|
||||||
"<": true,
|
"<": true,
|
||||||
|
|||||||
+74
-26
@@ -8,15 +8,20 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/daemon/job"
|
"github.com/zrepl/zrepl/daemon/job"
|
||||||
"github.com/zrepl/zrepl/daemon/nethelpers"
|
"github.com/zrepl/zrepl/daemon/nethelpers"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
|
"github.com/zrepl/zrepl/util/envconst"
|
||||||
"github.com/zrepl/zrepl/version"
|
"github.com/zrepl/zrepl/version"
|
||||||
"github.com/zrepl/zrepl/zfs"
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
"github.com/zrepl/zrepl/zfs/zfscmd"
|
||||||
)
|
)
|
||||||
|
|
||||||
type controlJob struct {
|
type controlJob struct {
|
||||||
@@ -42,25 +47,27 @@ func (j *controlJob) Status() *job.Status { return &job.Status{Type: job.TypeInt
|
|||||||
|
|
||||||
func (j *controlJob) OwnedDatasetSubtreeRoot() (p *zfs.DatasetPath, ok bool) { return nil, false }
|
func (j *controlJob) OwnedDatasetSubtreeRoot() (p *zfs.DatasetPath, ok bool) { return nil, false }
|
||||||
|
|
||||||
|
func (j *controlJob) SenderConfig() *endpoint.SenderConfig { return nil }
|
||||||
|
|
||||||
var promControl struct {
|
var promControl struct {
|
||||||
requestBegin *prometheus.CounterVec
|
requestBegin *prometheus.CounterVec
|
||||||
requestFinished *prometheus.HistogramVec
|
requestFinished *prometheus.HistogramVec
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *controlJob) RegisterMetrics(registerer prometheus.Registerer) {
|
func (j *controlJob) RegisterMetrics(registerer prometheus.Registerer) {
|
||||||
promControl.requestBegin = prometheus.NewCounterVec(prometheus.CounterOpts{
|
promControl.requestBegin = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
Namespace: "zrepl",
|
Namespace: "zrepl",
|
||||||
Subsystem: "control",
|
Subsystem: "control",
|
||||||
Name: "request_begin",
|
Name: "request_begin",
|
||||||
Help: "number of request we started to handle",
|
Help: "number of request we started to handle",
|
||||||
}, []string{"endpoint"})
|
}, []string{"endpoint"})
|
||||||
|
|
||||||
promControl.requestFinished = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
promControl.requestFinished = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||||
Namespace: "zrepl",
|
Namespace: "zrepl",
|
||||||
Subsystem: "control",
|
Subsystem: "control",
|
||||||
Name: "request_finished",
|
Name: "request_finished",
|
||||||
Help: "time it took a request to finih",
|
Help: "time it took a request to finish",
|
||||||
Buckets: []float64{1e-6, 10e-6, 100e-6, 500e-6, 1e-3,10e-3, 100e-3, 200e-3,400e-3,800e-3, 1, 10, 20},
|
Buckets: []float64{1e-6, 10e-6, 100e-6, 500e-6, 1e-3, 10e-3, 100e-3, 200e-3, 400e-3, 800e-3, 1, 10, 20},
|
||||||
}, []string{"endpoint"})
|
}, []string{"endpoint"})
|
||||||
registerer.MustRegister(promControl.requestBegin)
|
registerer.MustRegister(promControl.requestBegin)
|
||||||
registerer.MustRegister(promControl.requestFinished)
|
registerer.MustRegister(promControl.requestFinished)
|
||||||
@@ -85,10 +92,16 @@ func (j *controlJob) Run(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pprofServer := NewPProfServer(ctx)
|
pprofServer := NewPProfServer(ctx)
|
||||||
|
if listen := envconst.String("ZREPL_DAEMON_AUTOSTART_PPROF_SERVER", ""); listen != "" {
|
||||||
|
pprofServer.Control(PprofServerControlMsg{
|
||||||
|
Run: true,
|
||||||
|
HttpListenAddress: listen,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.Handle(ControlJobEndpointPProf,
|
mux.Handle(ControlJobEndpointPProf,
|
||||||
requestLogger{log: log, handler: jsonRequestResponder{func(decoder jsonDecoder) (interface{}, error) {
|
requestLogger{log: log, handler: jsonRequestResponder{log, func(decoder jsonDecoder) (interface{}, error) {
|
||||||
var msg PprofServerControlMsg
|
var msg PprofServerControlMsg
|
||||||
err := decoder(&msg)
|
err := decoder(&msg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -99,22 +112,31 @@ func (j *controlJob) Run(ctx context.Context) {
|
|||||||
}}})
|
}}})
|
||||||
|
|
||||||
mux.Handle(ControlJobEndpointVersion,
|
mux.Handle(ControlJobEndpointVersion,
|
||||||
requestLogger{log: log, handler: jsonResponder{func() (interface{}, error) {
|
requestLogger{log: log, handler: jsonResponder{log, func() (interface{}, error) {
|
||||||
return version.NewZreplVersionInformation(), nil
|
return version.NewZreplVersionInformation(), nil
|
||||||
}}})
|
}}})
|
||||||
|
|
||||||
mux.Handle(ControlJobEndpointStatus,
|
mux.Handle(ControlJobEndpointStatus,
|
||||||
// don't log requests to status endpoint, too spammy
|
// don't log requests to status endpoint, too spammy
|
||||||
jsonResponder{func() (interface{}, error) {
|
jsonResponder{log, func() (interface{}, error) {
|
||||||
s := j.jobs.status()
|
jobs := j.jobs.status()
|
||||||
|
globalZFS := zfscmd.GetReport()
|
||||||
|
envconstReport := envconst.GetReport()
|
||||||
|
s := Status{
|
||||||
|
Jobs: jobs,
|
||||||
|
Global: GlobalStatus{
|
||||||
|
ZFSCmds: globalZFS,
|
||||||
|
Envconst: envconstReport,
|
||||||
|
OsEnviron: os.Environ(),
|
||||||
|
}}
|
||||||
return s, nil
|
return s, nil
|
||||||
}})
|
}})
|
||||||
|
|
||||||
mux.Handle(ControlJobEndpointSignal,
|
mux.Handle(ControlJobEndpointSignal,
|
||||||
requestLogger{log: log, handler: jsonRequestResponder{func(decoder jsonDecoder) (interface{}, error) {
|
requestLogger{log: log, handler: jsonRequestResponder{log, func(decoder jsonDecoder) (interface{}, error) {
|
||||||
type reqT struct {
|
type reqT struct {
|
||||||
Name string
|
Name string
|
||||||
Op string
|
Op string
|
||||||
}
|
}
|
||||||
var req reqT
|
var req reqT
|
||||||
if decoder(&req) != nil {
|
if decoder(&req) != nil {
|
||||||
@@ -136,8 +158,8 @@ func (j *controlJob) Run(ctx context.Context) {
|
|||||||
server := http.Server{
|
server := http.Server{
|
||||||
Handler: mux,
|
Handler: mux,
|
||||||
// control socket is local, 1s timeout should be more than sufficient, even on a loaded system
|
// control socket is local, 1s timeout should be more than sufficient, even on a loaded system
|
||||||
WriteTimeout: 1*time.Second,
|
WriteTimeout: envconst.Duration("ZREPL_DAEMON_CONTROL_SERVER_WRITE_TIMEOUT", 1*time.Second),
|
||||||
ReadTimeout: 1*time.Second,
|
ReadTimeout: envconst.Duration("ZREPL_DAEMON_CONTROL_SERVER_READ_TIMEOUT", 1*time.Second),
|
||||||
}
|
}
|
||||||
|
|
||||||
outer:
|
outer:
|
||||||
@@ -152,7 +174,10 @@ outer:
|
|||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.WithError(ctx.Err()).Info("context done")
|
log.WithError(ctx.Err()).Info("context done")
|
||||||
server.Shutdown(context.Background())
|
err := server.Shutdown(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
log.WithError(err).Error("cannot shutdown server")
|
||||||
|
}
|
||||||
break outer
|
break outer
|
||||||
case err = <-served:
|
case err = <-served:
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -166,33 +191,50 @@ outer:
|
|||||||
}
|
}
|
||||||
|
|
||||||
type jsonResponder struct {
|
type jsonResponder struct {
|
||||||
|
log Logger
|
||||||
producer func() (interface{}, error)
|
producer func() (interface{}, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j jsonResponder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (j jsonResponder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
logIoErr := func(err error) {
|
||||||
|
if err != nil {
|
||||||
|
j.log.WithError(err).Error("control handler io error")
|
||||||
|
}
|
||||||
|
}
|
||||||
res, err := j.producer()
|
res, err := j.producer()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
j.log.WithError(err).Error("control handler error")
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
io.WriteString(w, err.Error())
|
_, err = io.WriteString(w, err.Error())
|
||||||
|
logIoErr(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
err = json.NewEncoder(&buf).Encode(res)
|
err = json.NewEncoder(&buf).Encode(res)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
j.log.WithError(err).Error("control handler json marshal error")
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
io.WriteString(w, err.Error())
|
_, err = io.WriteString(w, err.Error())
|
||||||
} else {
|
} else {
|
||||||
io.Copy(w, &buf)
|
_, err = io.Copy(w, &buf)
|
||||||
}
|
}
|
||||||
|
logIoErr(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
type jsonDecoder = func(interface{}) error
|
type jsonDecoder = func(interface{}) error
|
||||||
|
|
||||||
type jsonRequestResponder struct {
|
type jsonRequestResponder struct {
|
||||||
|
log Logger
|
||||||
producer func(decoder jsonDecoder) (interface{}, error)
|
producer func(decoder jsonDecoder) (interface{}, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j jsonRequestResponder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (j jsonRequestResponder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
logIoErr := func(err error) {
|
||||||
|
if err != nil {
|
||||||
|
j.log.WithError(err).Error("control handler io error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var decodeError error
|
var decodeError error
|
||||||
decoder := func(i interface{}) error {
|
decoder := func(i interface{}) error {
|
||||||
err := json.NewDecoder(r.Body).Decode(&i)
|
err := json.NewDecoder(r.Body).Decode(&i)
|
||||||
@@ -204,22 +246,28 @@ func (j jsonRequestResponder) ServeHTTP(w http.ResponseWriter, r *http.Request)
|
|||||||
//If we had a decode error ignore output of producer and return error
|
//If we had a decode error ignore output of producer and return error
|
||||||
if decodeError != nil {
|
if decodeError != nil {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
io.WriteString(w, decodeError.Error())
|
_, err := io.WriteString(w, decodeError.Error())
|
||||||
|
logIoErr(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if producerErr != nil {
|
if producerErr != nil {
|
||||||
|
j.log.WithError(producerErr).Error("control handler error")
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
io.WriteString(w, producerErr.Error())
|
_, err := io.WriteString(w, producerErr.Error())
|
||||||
|
logIoErr(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
encodeErr := json.NewEncoder(&buf).Encode(res)
|
encodeErr := json.NewEncoder(&buf).Encode(res)
|
||||||
if encodeErr != nil {
|
if encodeErr != nil {
|
||||||
|
j.log.WithError(producerErr).Error("control handler json marshal error")
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
io.WriteString(w, encodeErr.Error())
|
_, err := io.WriteString(w, encodeErr.Error())
|
||||||
|
logIoErr(err)
|
||||||
} else {
|
} else {
|
||||||
io.Copy(w, &buf)
|
_, err := io.Copy(w, &buf)
|
||||||
|
logIoErr(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+61
-26
@@ -3,8 +3,21 @@ package daemon
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/util/envconst"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/job"
|
"github.com/zrepl/zrepl/daemon/job"
|
||||||
"github.com/zrepl/zrepl/daemon/job/reset"
|
"github.com/zrepl/zrepl/daemon/job/reset"
|
||||||
@@ -12,17 +25,11 @@ import (
|
|||||||
"github.com/zrepl/zrepl/daemon/logging"
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
"github.com/zrepl/zrepl/version"
|
"github.com/zrepl/zrepl/version"
|
||||||
"os"
|
"github.com/zrepl/zrepl/zfs/zfscmd"
|
||||||
"os/signal"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func Run(conf *config.Config) error {
|
func Run(ctx context.Context, conf *config.Config) error {
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
|
|
||||||
defer cancel()
|
defer cancel()
|
||||||
sigChan := make(chan os.Signal, 1)
|
sigChan := make(chan os.Signal, 1)
|
||||||
@@ -32,12 +39,19 @@ func Run(conf *config.Config) error {
|
|||||||
cancel()
|
cancel()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
// The math/rand package is used presently for generating trace IDs, we
|
||||||
|
// seed it with the current time and pid so that the IDs are mostly
|
||||||
|
// unique.
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
rand.Seed(int64(os.Getpid()))
|
||||||
|
|
||||||
outlets, err := logging.OutletsFromConfig(*conf.Global.Logging)
|
outlets, err := logging.OutletsFromConfig(*conf.Global.Logging)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "cannot build logging from config")
|
return errors.Wrap(err, "cannot build logging from config")
|
||||||
}
|
}
|
||||||
|
outlets.Add(newPrometheusLogOutlet(), logger.Debug)
|
||||||
|
|
||||||
confJobs, err := job.JobsFromConfig(conf)
|
confJobs, err := job.JobsFromConfig(conf, config.ParseFlagsNone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrap(err, "cannot build jobs from config")
|
return errors.Wrap(err, "cannot build jobs from config")
|
||||||
}
|
}
|
||||||
@@ -45,14 +59,23 @@ func Run(conf *config.Config) error {
|
|||||||
log := logger.NewLogger(outlets, 1*time.Second)
|
log := logger.NewLogger(outlets, 1*time.Second)
|
||||||
log.Info(version.NewZreplVersionInformation().String())
|
log.Info(version.NewZreplVersionInformation().String())
|
||||||
|
|
||||||
|
ctx = logging.WithLoggers(ctx, logging.SubsystemLoggersWithUniversalLogger(log))
|
||||||
|
trace.RegisterCallback(trace.Callback{
|
||||||
|
OnBegin: func(ctx context.Context) { logging.GetLogger(ctx, logging.SubsysTraceData).Debug("begin span") },
|
||||||
|
OnEnd: func(ctx context.Context, spanInfo trace.SpanInfo) {
|
||||||
|
logging.
|
||||||
|
GetLogger(ctx, logging.SubsysTraceData).
|
||||||
|
WithField("duration_s", spanInfo.EndedAt().Sub(spanInfo.StartedAt()).Seconds()).
|
||||||
|
Debug("finished span " + spanInfo.TaskAndSpanStack(trace.SpanStackKindAnnotation))
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
for _, job := range confJobs {
|
for _, job := range confJobs {
|
||||||
if IsInternalJobName(job.Name()) {
|
if IsInternalJobName(job.Name()) {
|
||||||
panic(fmt.Sprintf("internal job name used for config job '%s'", job.Name())) //FIXME
|
panic(fmt.Sprintf("internal job name used for config job '%s'", job.Name())) //FIXME
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx = job.WithLogger(ctx, log)
|
|
||||||
|
|
||||||
jobs := newJobs()
|
jobs := newJobs()
|
||||||
|
|
||||||
// start control socket
|
// start control socket
|
||||||
@@ -74,11 +97,16 @@ func Run(conf *config.Config) error {
|
|||||||
return errors.Errorf("unknown monitoring job #%d (type %T)", i, v)
|
return errors.Errorf("unknown monitoring job #%d (type %T)", i, v)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.Wrapf(err,"cannot build monitorin gjob #%d", i)
|
return errors.Wrapf(err, "cannot build monitoring job #%d", i)
|
||||||
}
|
}
|
||||||
jobs.start(ctx, job, true)
|
jobs.start(ctx, job, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// register global (=non job-local) metrics
|
||||||
|
version.PrometheusRegister(prometheus.DefaultRegisterer)
|
||||||
|
zfscmd.RegisterMetrics(prometheus.DefaultRegisterer)
|
||||||
|
trace.RegisterMetrics(prometheus.DefaultRegisterer)
|
||||||
|
endpoint.RegisterMetrics(prometheus.DefaultRegisterer)
|
||||||
|
|
||||||
log.Info("starting daemon")
|
log.Info("starting daemon")
|
||||||
|
|
||||||
@@ -93,6 +121,8 @@ func Run(conf *config.Config) error {
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
log.WithError(ctx.Err()).Info("context finished")
|
log.WithError(ctx.Err()).Info("context finished")
|
||||||
}
|
}
|
||||||
|
log.Info("waiting for jobs to finish")
|
||||||
|
<-jobs.wait()
|
||||||
log.Info("daemon exiting")
|
log.Info("daemon exiting")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -103,7 +133,7 @@ type jobs struct {
|
|||||||
// m protects all fields below it
|
// m protects all fields below it
|
||||||
m sync.RWMutex
|
m sync.RWMutex
|
||||||
wakeups map[string]wakeup.Func // by Job.Name
|
wakeups map[string]wakeup.Func // by Job.Name
|
||||||
resets map[string]reset.Func // by Job.Name
|
resets map[string]reset.Func // by Job.Name
|
||||||
jobs map[string]job.Job
|
jobs map[string]job.Job
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,20 +145,26 @@ func newJobs() *jobs {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
|
||||||
logJobField string = "job"
|
|
||||||
logTaskField string = "task"
|
|
||||||
logSubsysField string = "subsystem"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (s *jobs) wait() <-chan struct{} {
|
func (s *jobs) wait() <-chan struct{} {
|
||||||
ch := make(chan struct{})
|
ch := make(chan struct{})
|
||||||
go func() {
|
go func() {
|
||||||
s.wg.Wait()
|
s.wg.Wait()
|
||||||
|
close(ch)
|
||||||
}()
|
}()
|
||||||
return ch
|
return ch
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Status struct {
|
||||||
|
Jobs map[string]*job.Status
|
||||||
|
Global GlobalStatus
|
||||||
|
}
|
||||||
|
|
||||||
|
type GlobalStatus struct {
|
||||||
|
ZFSCmds *zfscmd.Report
|
||||||
|
Envconst *envconst.Report
|
||||||
|
OsEnviron []string
|
||||||
|
}
|
||||||
|
|
||||||
func (s *jobs) status() map[string]*job.Status {
|
func (s *jobs) status() map[string]*job.Status {
|
||||||
s.m.RLock()
|
s.m.RLock()
|
||||||
defer s.m.RUnlock()
|
defer s.m.RUnlock()
|
||||||
@@ -190,9 +226,8 @@ func (s *jobs) start(ctx context.Context, j job.Job, internal bool) {
|
|||||||
s.m.Lock()
|
s.m.Lock()
|
||||||
defer s.m.Unlock()
|
defer s.m.Unlock()
|
||||||
|
|
||||||
jobLog := job.GetLogger(ctx).
|
ctx = logging.WithInjectedField(ctx, logging.JobField, j.Name())
|
||||||
WithField(logJobField, j.Name()).
|
|
||||||
WithOutlet(newPrometheusLogOutlet(j.Name()), logger.Debug)
|
|
||||||
jobName := j.Name()
|
jobName := j.Name()
|
||||||
if !internal && IsInternalJobName(jobName) {
|
if !internal && IsInternalJobName(jobName) {
|
||||||
panic(fmt.Sprintf("internal job name used for non-internal job %s", jobName))
|
panic(fmt.Sprintf("internal job name used for non-internal job %s", jobName))
|
||||||
@@ -207,7 +242,7 @@ func (s *jobs) start(ctx context.Context, j job.Job, internal bool) {
|
|||||||
j.RegisterMetrics(prometheus.DefaultRegisterer)
|
j.RegisterMetrics(prometheus.DefaultRegisterer)
|
||||||
|
|
||||||
s.jobs[jobName] = j
|
s.jobs[jobName] = j
|
||||||
ctx = job.WithLogger(ctx, jobLog)
|
ctx = zfscmd.WithJobID(ctx, j.Name())
|
||||||
ctx, wakeup := wakeup.Context(ctx)
|
ctx, wakeup := wakeup.Context(ctx)
|
||||||
ctx, resetFunc := reset.Context(ctx)
|
ctx, resetFunc := reset.Context(ctx)
|
||||||
s.wakeups[jobName] = wakeup
|
s.wakeups[jobName] = wakeup
|
||||||
@@ -216,8 +251,8 @@ func (s *jobs) start(ctx context.Context, j job.Job, internal bool) {
|
|||||||
s.wg.Add(1)
|
s.wg.Add(1)
|
||||||
go func() {
|
go func() {
|
||||||
defer s.wg.Done()
|
defer s.wg.Done()
|
||||||
jobLog.Info("starting job")
|
job.GetLogger(ctx).Info("starting job")
|
||||||
defer jobLog.Info("job exited")
|
defer job.GetLogger(ctx).Info("job exited")
|
||||||
j.Run(ctx)
|
j.Run(ctx)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,12 @@ package filters
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/endpoint"
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
"github.com/zrepl/zrepl/zfs"
|
"github.com/zrepl/zrepl/zfs"
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type DatasetMapFilter struct {
|
type DatasetMapFilter struct {
|
||||||
@@ -158,8 +160,16 @@ func (m DatasetMapFilter) Filter(p *zfs.DatasetPath) (pass bool, err error) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m DatasetMapFilter) UserSpecifiedDatasets() (datasets zfs.UserSpecifiedDatasetsSet) {
|
||||||
|
datasets = make(zfs.UserSpecifiedDatasetsSet)
|
||||||
|
for i := range m.entries {
|
||||||
|
datasets[m.entries[i].path.ToString()] = true
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Construct a new filter-only DatasetMapFilter from a mapping
|
// Construct a new filter-only DatasetMapFilter from a mapping
|
||||||
// The new filter allows excactly those paths that were not forbidden by the mapping.
|
// The new filter allows exactly those paths that were not forbidden by the mapping.
|
||||||
func (m DatasetMapFilter) InvertedFilter() (inv *DatasetMapFilter, err error) {
|
func (m DatasetMapFilter) InvertedFilter() (inv *DatasetMapFilter, err error) {
|
||||||
|
|
||||||
if m.filterMode {
|
if m.filterMode {
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package filters
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDatasetMapFilter(t *testing.T) {
|
||||||
|
|
||||||
|
type testCase struct {
|
||||||
|
name string
|
||||||
|
filter map[string]string
|
||||||
|
checkPass map[string]bool // each entry is checked to match the filter's `pass` return value
|
||||||
|
}
|
||||||
|
|
||||||
|
tcs := []testCase{
|
||||||
|
{
|
||||||
|
"default_no_match",
|
||||||
|
map[string]string{},
|
||||||
|
map[string]bool{
|
||||||
|
"": false,
|
||||||
|
"foo": false,
|
||||||
|
"zroot": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"more_specific_path_has_precedence",
|
||||||
|
map[string]string{
|
||||||
|
"tank<": "ok",
|
||||||
|
"tank/tmp<": "!",
|
||||||
|
"tank/home/x<": "!",
|
||||||
|
"tank/home/x/1": "ok",
|
||||||
|
},
|
||||||
|
map[string]bool{
|
||||||
|
"zroot": false,
|
||||||
|
"tank": true,
|
||||||
|
"tank/tmp": false,
|
||||||
|
"tank/tmp/foo": false,
|
||||||
|
"tank/home/x": false,
|
||||||
|
"tank/home/y": true,
|
||||||
|
"tank/home/x/1": true,
|
||||||
|
"tank/home/x/2": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"precedence_of_specific_over_subtree_wildcard_on_same_path",
|
||||||
|
map[string]string{
|
||||||
|
"tank/home/bob": "ok",
|
||||||
|
"tank/home/bob<": "!",
|
||||||
|
},
|
||||||
|
map[string]bool{
|
||||||
|
"tank/home/bob": true,
|
||||||
|
"tank/home/bob/downloads": false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for tc := range tcs {
|
||||||
|
t.Run(tcs[tc].name, func(t *testing.T) {
|
||||||
|
c := tcs[tc]
|
||||||
|
f := NewDatasetMapFilter(len(c.filter), true)
|
||||||
|
for p, a := range c.filter {
|
||||||
|
err := f.Add(p, a)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("incorrect filter spec: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p, checkPass := range c.checkPass {
|
||||||
|
zp, err := zfs.NewDatasetPath(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("incorrect path spec: %s", err)
|
||||||
|
}
|
||||||
|
pass, err := f.Filter(zp)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unexpected filter error: %s", err)
|
||||||
|
}
|
||||||
|
ok := pass == checkPass
|
||||||
|
failstr := "OK"
|
||||||
|
if !ok {
|
||||||
|
failstr = "FAIL"
|
||||||
|
t.Fail()
|
||||||
|
}
|
||||||
|
t.Logf("%-40q %5v (exp=%v act=%v)", p, failstr, checkPass, pass)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package filters
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/zrepl/zrepl/zfs"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
type AnyFSVFilter struct{}
|
|
||||||
|
|
||||||
func NewAnyFSVFilter() AnyFSVFilter {
|
|
||||||
return AnyFSVFilter{}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ zfs.FilesystemVersionFilter = AnyFSVFilter{}
|
|
||||||
|
|
||||||
func (AnyFSVFilter) Filter(t zfs.VersionType, name string) (accept bool, err error) {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
type PrefixFilter struct {
|
|
||||||
prefix string
|
|
||||||
fstype zfs.VersionType
|
|
||||||
fstypeSet bool // optionals anyone?
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ zfs.FilesystemVersionFilter = &PrefixFilter{}
|
|
||||||
|
|
||||||
func NewPrefixFilter(prefix string) *PrefixFilter {
|
|
||||||
return &PrefixFilter{prefix: prefix}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTypedPrefixFilter(prefix string, versionType zfs.VersionType) *PrefixFilter {
|
|
||||||
return &PrefixFilter{prefix, versionType, true}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *PrefixFilter) Filter(t zfs.VersionType, name string) (accept bool, err error) {
|
|
||||||
fstypeMatches := (!f.fstypeSet || t == f.fstype)
|
|
||||||
prefixMatches := strings.HasPrefix(name, f.prefix)
|
|
||||||
return fstypeMatches && prefixMatches, nil
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// Code generated by "stringer -type=Edge"; DO NOT EDIT.
|
||||||
|
|
||||||
|
package hooks
|
||||||
|
|
||||||
|
import "strconv"
|
||||||
|
|
||||||
|
func _() {
|
||||||
|
// An "invalid array index" compiler error signifies that the constant values have changed.
|
||||||
|
// Re-run the stringer command to generate them again.
|
||||||
|
var x [1]struct{}
|
||||||
|
_ = x[Pre-1]
|
||||||
|
_ = x[Callback-2]
|
||||||
|
_ = x[Post-4]
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
_Edge_name_0 = "PreCallback"
|
||||||
|
_Edge_name_1 = "Post"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
_Edge_index_0 = [...]uint8{0, 3, 11}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (i Edge) String() string {
|
||||||
|
switch {
|
||||||
|
case 1 <= i && i <= 2:
|
||||||
|
i -= 1
|
||||||
|
return _Edge_name_0[_Edge_index_0[i]:_Edge_index_0[i+1]]
|
||||||
|
case i == 4:
|
||||||
|
return _Edge_name_1
|
||||||
|
default:
|
||||||
|
return "Edge(" + strconv.FormatInt(int64(i), 10) + ")"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type List []Hook
|
||||||
|
|
||||||
|
func HookFromConfig(in config.HookEnum) (Hook, error) {
|
||||||
|
switch v := in.Ret.(type) {
|
||||||
|
case *config.HookCommand:
|
||||||
|
return NewCommandHook(v)
|
||||||
|
case *config.HookPostgresCheckpoint:
|
||||||
|
return PgChkptHookFromConfig(v)
|
||||||
|
case *config.HookMySQLLockTables:
|
||||||
|
return MyLockTablesFromConfig(v)
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown hook type %T", v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ListFromConfig(in *config.HookList) (r *List, err error) {
|
||||||
|
hl := make(List, len(*in))
|
||||||
|
|
||||||
|
for i, h := range *in {
|
||||||
|
hl[i], err = HookFromConfig(h)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create hook #%d: %s", i+1, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &hl, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l List) CopyFilteredForFilesystem(fs *zfs.DatasetPath) (ret List, err error) {
|
||||||
|
ret = make(List, 0, len(l))
|
||||||
|
|
||||||
|
for _, h := range l {
|
||||||
|
var passFilesystem bool
|
||||||
|
if passFilesystem, err = h.Filesystems().Filter(fs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if passFilesystem {
|
||||||
|
ret = append(ret, h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ret, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// Package hooks implements pre- and post snapshot hooks.
|
||||||
|
//
|
||||||
|
// Plan is a generic executor for ExpectStepReports before and after an activity specified in a callback.
|
||||||
|
// It provides a reporting facility that can be polled while the plan is executing to gather progress information.
|
||||||
|
//
|
||||||
|
// This package also provides all supported hook type implementations and abstractions around them.
|
||||||
|
//
|
||||||
|
// # Use For Other Kinds Of ExpectStepReports
|
||||||
|
//
|
||||||
|
// This package REQUIRES REFACTORING before it can be used for other activities than snapshots, e.g. pre- and post-replication:
|
||||||
|
//
|
||||||
|
// The Hook interface requires a hook to provide a Filesystems() filter, which doesn't make sense for
|
||||||
|
// all kinds of activities.
|
||||||
|
//
|
||||||
|
// The hook implementations should move out of this package.
|
||||||
|
// However, there is a lot of tight coupling which to untangle isn't worth it ATM.
|
||||||
|
//
|
||||||
|
// # How This Package Is Used By Package Snapper
|
||||||
|
//
|
||||||
|
// Deserialize a config.List using ListFromConfig().
|
||||||
|
// Then it MUST filter the list to only contain hooks for a particular filesystem using
|
||||||
|
// hooksList.CopyFilteredForFilesystem(fs).
|
||||||
|
//
|
||||||
|
// Then create a CallbackHook using NewCallbackHookForFilesystem().
|
||||||
|
//
|
||||||
|
// Pass all of the above to NewPlan() which provides a Report() and Run() method:
|
||||||
|
//
|
||||||
|
// Plan.Run(ctx context.Context,dryRun bool) executes the plan and take a context as argument that should contain a logger added using hooks.WithLogger()).
|
||||||
|
// The value of dryRun is passed through to the hooks' Run() method.
|
||||||
|
// Command hooks make it available in the environment variable ZREPL_DRYRUN.
|
||||||
|
//
|
||||||
|
// Plan.Report() can be called while Plan.Run() is executing to give an overview of plan execution progress (future use in "zrepl status").
|
||||||
|
package hooks
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Re-export type here so that
|
||||||
|
// every file in package hooks doesn't
|
||||||
|
// have to import github.com/zrepl/zrepl/zfs
|
||||||
|
type Filter zfs.DatasetFilter
|
||||||
|
|
||||||
|
type Hook interface {
|
||||||
|
Filesystems() Filter
|
||||||
|
|
||||||
|
// If true and the Pre edge invocation of Run fails, Post edge will not run and other Pre edges will not run.
|
||||||
|
ErrIsFatal() bool
|
||||||
|
|
||||||
|
// Run is invoked by HookPlan for a Pre edge.
|
||||||
|
// If HookReport.HadError() == false, the Post edge will be invoked, too.
|
||||||
|
Run(ctx context.Context, edge Edge, phase Phase, dryRun bool, extra Env, state map[interface{}]interface{}) HookReport
|
||||||
|
|
||||||
|
String() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Phase string
|
||||||
|
|
||||||
|
const (
|
||||||
|
PhaseSnapshot = Phase("snapshot")
|
||||||
|
PhaseTesting = Phase("testing")
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p Phase) String() string {
|
||||||
|
return string(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:generate stringer -type=Edge
|
||||||
|
type Edge uint
|
||||||
|
|
||||||
|
const (
|
||||||
|
Pre = Edge(1 << iota)
|
||||||
|
Callback
|
||||||
|
Post
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e Edge) StringForPhase(phase Phase) string {
|
||||||
|
return fmt.Sprintf("%s_%s", e.String(), phase.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
//go:generate enumer -type=StepStatus -trimprefix=Step
|
||||||
|
type StepStatus int
|
||||||
|
|
||||||
|
const (
|
||||||
|
StepPending StepStatus = 1 << iota
|
||||||
|
StepExec
|
||||||
|
StepOk
|
||||||
|
StepErr
|
||||||
|
StepSkippedDueToFatalErr
|
||||||
|
StepSkippedDueToPreErr
|
||||||
|
)
|
||||||
|
|
||||||
|
type HookReport interface {
|
||||||
|
String() string
|
||||||
|
HadError() bool
|
||||||
|
Error() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Step struct {
|
||||||
|
Hook Hook
|
||||||
|
Edge Edge
|
||||||
|
Status StepStatus
|
||||||
|
Begin, End time.Time
|
||||||
|
// Report may be nil
|
||||||
|
// FIXME cannot serialize this for client status, but contains interesting info (like what error happened)
|
||||||
|
Report HookReport
|
||||||
|
state map[interface{}]interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s Step) String() (out string) {
|
||||||
|
fatal := "~"
|
||||||
|
if s.Hook.ErrIsFatal() && s.Edge == Pre {
|
||||||
|
fatal = "!"
|
||||||
|
}
|
||||||
|
runTime := "..."
|
||||||
|
if s.Status != StepPending {
|
||||||
|
t := s.End.Sub(s.Begin)
|
||||||
|
runTime = t.Round(time.Millisecond).String()
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("[%s] [%5s] %s [%s] %s", s.Status, runTime, fatal, s.Edge, s.Hook)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Plan struct {
|
||||||
|
mtx sync.RWMutex
|
||||||
|
|
||||||
|
steps []*Step
|
||||||
|
pre []*Step // protected by mtx
|
||||||
|
cb *Step
|
||||||
|
post []*Step // not reversed, i.e. entry at index i corresponds to pre-edge in pre[i]
|
||||||
|
|
||||||
|
phase Phase
|
||||||
|
env Env
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPlan(hooks *List, phase Phase, cb *CallbackHook, extra Env) (*Plan, error) {
|
||||||
|
|
||||||
|
var pre, post []*Step
|
||||||
|
// TODO sanity check unique name of hook?
|
||||||
|
for _, hook := range *hooks {
|
||||||
|
state := make(map[interface{}]interface{})
|
||||||
|
preE := &Step{
|
||||||
|
Hook: hook,
|
||||||
|
Edge: Pre,
|
||||||
|
Status: StepPending,
|
||||||
|
state: state,
|
||||||
|
}
|
||||||
|
pre = append(pre, preE)
|
||||||
|
postE := &Step{
|
||||||
|
Hook: hook,
|
||||||
|
Edge: Post,
|
||||||
|
Status: StepPending,
|
||||||
|
state: state,
|
||||||
|
}
|
||||||
|
post = append(post, postE)
|
||||||
|
}
|
||||||
|
|
||||||
|
cbE := &Step{
|
||||||
|
Hook: cb,
|
||||||
|
Edge: Callback,
|
||||||
|
Status: StepPending,
|
||||||
|
}
|
||||||
|
|
||||||
|
steps := make([]*Step, 0, len(pre)+len(post)+1)
|
||||||
|
steps = append(steps, pre...)
|
||||||
|
steps = append(steps, cbE)
|
||||||
|
for i := len(post) - 1; i >= 0; i-- {
|
||||||
|
steps = append(steps, post[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
plan := &Plan{
|
||||||
|
phase: phase,
|
||||||
|
env: extra,
|
||||||
|
steps: steps,
|
||||||
|
pre: pre,
|
||||||
|
post: post,
|
||||||
|
cb: cbE,
|
||||||
|
}
|
||||||
|
|
||||||
|
return plan, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type PlanReport []Step
|
||||||
|
|
||||||
|
func (p *Plan) Report() PlanReport {
|
||||||
|
p.mtx.RLock()
|
||||||
|
defer p.mtx.RUnlock()
|
||||||
|
rep := make([]Step, len(p.steps))
|
||||||
|
for i := range rep {
|
||||||
|
rep[i] = *p.steps[i]
|
||||||
|
}
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r PlanReport) HadError() bool {
|
||||||
|
for _, e := range r {
|
||||||
|
if e.Status == StepErr {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r PlanReport) HadFatalError() bool {
|
||||||
|
for _, e := range r {
|
||||||
|
if e.Status == StepSkippedDueToFatalErr {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r PlanReport) String() string {
|
||||||
|
stepStrings := make([]string, len(r))
|
||||||
|
for i, e := range r {
|
||||||
|
stepStrings[i] = fmt.Sprintf("%02d %s", i+1, e)
|
||||||
|
}
|
||||||
|
return strings.Join(stepStrings, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plan) Run(ctx context.Context, dryRun bool) {
|
||||||
|
p.mtx.RLock()
|
||||||
|
defer p.mtx.RUnlock()
|
||||||
|
w := func(f func()) {
|
||||||
|
p.mtx.RUnlock()
|
||||||
|
defer p.mtx.RLock()
|
||||||
|
p.mtx.Lock()
|
||||||
|
defer p.mtx.Unlock()
|
||||||
|
f()
|
||||||
|
}
|
||||||
|
runHook := func(s *Step, ctx context.Context, edge Edge) HookReport {
|
||||||
|
w(func() { s.Status = StepExec })
|
||||||
|
begin := time.Now()
|
||||||
|
r := s.Hook.Run(ctx, edge, p.phase, dryRun, p.env, s.state)
|
||||||
|
end := time.Now()
|
||||||
|
w(func() {
|
||||||
|
s.Report = r
|
||||||
|
s.Status = StepOk
|
||||||
|
if r.HadError() {
|
||||||
|
s.Status = StepErr
|
||||||
|
}
|
||||||
|
s.Begin, s.End = begin, end
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
l := getLogger(ctx)
|
||||||
|
|
||||||
|
// it's a stack, execute until we reach the end of the list (last item in)
|
||||||
|
// or fail inbetween
|
||||||
|
l.Info("run pre-edges in configuration order")
|
||||||
|
next := 0
|
||||||
|
for ; next < len(p.pre); next++ {
|
||||||
|
e := p.pre[next]
|
||||||
|
l := l.WithField("hook", e.Hook)
|
||||||
|
r := runHook(e, ctx, Pre)
|
||||||
|
if r.HadError() {
|
||||||
|
l.WithError(r).Error("hook invocation failed for pre-edge")
|
||||||
|
if e.Hook.ErrIsFatal() {
|
||||||
|
l.Error("the hook run was aborted due to a fatal error in this hook")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hadFatalErr := next != len(p.pre)
|
||||||
|
if hadFatalErr {
|
||||||
|
l.Error("fatal error in a pre-snapshot hook invocation")
|
||||||
|
l.Error("no snapshot will be taken")
|
||||||
|
l.Error("only running post-edges for successful pre-edges")
|
||||||
|
w(func() {
|
||||||
|
p.post[next].Status = StepSkippedDueToFatalErr
|
||||||
|
for i := next + 1; i < len(p.pre); i++ {
|
||||||
|
p.pre[i].Status = StepSkippedDueToFatalErr
|
||||||
|
p.post[i].Status = StepSkippedDueToFatalErr
|
||||||
|
}
|
||||||
|
p.cb.Status = StepSkippedDueToFatalErr
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l.Info("running callback")
|
||||||
|
cbR := runHook(p.cb, ctx, Callback)
|
||||||
|
if cbR.HadError() {
|
||||||
|
l.WithError(cbR).Error("callback failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
l.Info("run post-edges for successful pre-edges in reverse configuration order")
|
||||||
|
|
||||||
|
// the constructor produces pre and post entries
|
||||||
|
// post is NOT reversed
|
||||||
|
next-- // now at index of last executed pre-edge
|
||||||
|
for ; next >= 0; next-- {
|
||||||
|
e := p.post[next]
|
||||||
|
l := l.WithField("hook", e.Hook)
|
||||||
|
|
||||||
|
if p.pre[next].Status != StepOk {
|
||||||
|
if p.pre[next].Status != StepErr {
|
||||||
|
panic(fmt.Sprintf("expecting a pre-edge hook report to be either Ok or Err, got %s", p.pre[next].Status))
|
||||||
|
}
|
||||||
|
l.Info("skip post-edge because pre-edge failed")
|
||||||
|
w(func() {
|
||||||
|
e.Status = StepSkippedDueToPreErr
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
report := runHook(e, ctx, Post)
|
||||||
|
|
||||||
|
if report.HadError() {
|
||||||
|
l.WithError(report).Error("hook invocation failed for post-edge")
|
||||||
|
l.Error("subsequent post-edges run regardless of this post-edge failure")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrIsFatal is only relevant for Pre
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
|
"github.com/zrepl/zrepl/logger"
|
||||||
|
"github.com/zrepl/zrepl/util/envconst"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Logger = logger.Logger
|
||||||
|
|
||||||
|
func GetLogger(ctx context.Context) Logger { return getLogger(ctx) }
|
||||||
|
|
||||||
|
func getLogger(ctx context.Context) Logger {
|
||||||
|
return logging.GetLogger(ctx, logging.SubsysHooks)
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_HOOK_LOG_SIZE_DEFAULT int = 1 << 20
|
||||||
|
|
||||||
|
type logWriter struct {
|
||||||
|
/*
|
||||||
|
Mutex prevents:
|
||||||
|
concurrent writes to buf, scanner in Write([]byte)
|
||||||
|
data race on scanner vs Write([]byte)
|
||||||
|
and concurrent write to buf (call to buf.Reset())
|
||||||
|
in Close()
|
||||||
|
|
||||||
|
(Also, Close() should generally block until any Write() call completes.)
|
||||||
|
*/
|
||||||
|
mtx *sync.Mutex
|
||||||
|
buf bytes.Buffer
|
||||||
|
scanner *bufio.Scanner
|
||||||
|
logger Logger
|
||||||
|
level logger.Level
|
||||||
|
field string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLogWriter(mtx *sync.Mutex, logger Logger, level logger.Level, field string) *logWriter {
|
||||||
|
w := new(logWriter)
|
||||||
|
w.mtx = mtx
|
||||||
|
w.scanner = bufio.NewScanner(&w.buf)
|
||||||
|
w.logger = logger
|
||||||
|
w.level = level
|
||||||
|
w.field = field
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logWriter) log(line string) {
|
||||||
|
w.logger.WithField(w.field, line).Log(w.level, "hook output")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logWriter) logUnreadBytes() error {
|
||||||
|
for w.scanner.Scan() {
|
||||||
|
w.log(w.scanner.Text())
|
||||||
|
}
|
||||||
|
if w.buf.Cap() > envconst.Int("ZREPL_MAX_HOOK_LOG_SIZE", MAX_HOOK_LOG_SIZE_DEFAULT) {
|
||||||
|
w.buf.Reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logWriter) Write(in []byte) (int, error) {
|
||||||
|
w.mtx.Lock()
|
||||||
|
defer w.mtx.Unlock()
|
||||||
|
|
||||||
|
n, bufErr := w.buf.Write(in)
|
||||||
|
if bufErr != nil {
|
||||||
|
return n, bufErr
|
||||||
|
}
|
||||||
|
|
||||||
|
err := w.logUnreadBytes()
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
// Always reset the scanner for the next Write
|
||||||
|
w.scanner = bufio.NewScanner(&w.buf)
|
||||||
|
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *logWriter) Close() (err error) {
|
||||||
|
w.mtx.Lock()
|
||||||
|
defer w.mtx.Unlock()
|
||||||
|
|
||||||
|
return w.logUnreadBytes()
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HookJobCallback func(ctx context.Context) error
|
||||||
|
|
||||||
|
type CallbackHook struct {
|
||||||
|
cb HookJobCallback
|
||||||
|
filter Filter
|
||||||
|
displayString string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCallbackHookForFilesystem(displayString string, fs *zfs.DatasetPath, cb HookJobCallback) *CallbackHook {
|
||||||
|
filter, _ := filters.DatasetMapFilterFromConfig(map[string]bool{fs.ToString(): true})
|
||||||
|
return NewCallbackHook(displayString, cb, filter)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCallbackHook(displayString string, cb HookJobCallback, filter Filter) *CallbackHook {
|
||||||
|
return &CallbackHook{
|
||||||
|
cb: cb,
|
||||||
|
filter: filter,
|
||||||
|
displayString: displayString,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CallbackHook) Filesystems() Filter {
|
||||||
|
return h.filter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CallbackHook) ErrIsFatal() bool {
|
||||||
|
return false // callback is by definition
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CallbackHook) String() string {
|
||||||
|
return h.displayString
|
||||||
|
}
|
||||||
|
|
||||||
|
type CallbackHookReport struct {
|
||||||
|
Name string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CallbackHookReport) String() string {
|
||||||
|
if r.HadError() {
|
||||||
|
return r.Error()
|
||||||
|
}
|
||||||
|
return r.Name
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CallbackHookReport) HadError() bool { return r.Err != nil }
|
||||||
|
|
||||||
|
func (r *CallbackHookReport) Error() string {
|
||||||
|
return fmt.Sprintf("%s error: %s", r.Name, r.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CallbackHook) Run(ctx context.Context, edge Edge, phase Phase, dryRun bool, extra Env, state map[interface{}]interface{}) HookReport {
|
||||||
|
err := h.cb(ctx)
|
||||||
|
return &CallbackHookReport{h.displayString, err}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/logger"
|
||||||
|
"github.com/zrepl/zrepl/util/circlog"
|
||||||
|
"github.com/zrepl/zrepl/util/envconst"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HookEnvVar string
|
||||||
|
|
||||||
|
const (
|
||||||
|
EnvType HookEnvVar = "ZREPL_HOOKTYPE"
|
||||||
|
EnvDryRun HookEnvVar = "ZREPL_DRYRUN"
|
||||||
|
EnvFS HookEnvVar = "ZREPL_FS"
|
||||||
|
EnvSnapshot HookEnvVar = "ZREPL_SNAPNAME"
|
||||||
|
EnvTimeout HookEnvVar = "ZREPL_TIMEOUT"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Env map[HookEnvVar]string
|
||||||
|
|
||||||
|
func NewHookEnv(edge Edge, phase Phase, dryRun bool, timeout time.Duration, extra Env) Env {
|
||||||
|
r := Env{
|
||||||
|
EnvTimeout: fmt.Sprintf("%.f", math.Floor(timeout.Seconds())),
|
||||||
|
}
|
||||||
|
|
||||||
|
edgeString := edge.StringForPhase(phase)
|
||||||
|
r[EnvType] = strings.ToLower(edgeString)
|
||||||
|
|
||||||
|
var dryRunString string
|
||||||
|
if dryRun {
|
||||||
|
dryRunString = "true"
|
||||||
|
} else {
|
||||||
|
dryRunString = ""
|
||||||
|
}
|
||||||
|
r[EnvDryRun] = dryRunString
|
||||||
|
|
||||||
|
for k, v := range extra {
|
||||||
|
r[k] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandHook struct {
|
||||||
|
edge Edge
|
||||||
|
filter Filter
|
||||||
|
errIsFatal bool
|
||||||
|
command string
|
||||||
|
timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type CommandHookReport struct {
|
||||||
|
Command string
|
||||||
|
Args []string // currently always empty
|
||||||
|
Env Env
|
||||||
|
Err error
|
||||||
|
CapturedStdoutStderrCombined []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CommandHookReport) String() string {
|
||||||
|
// Reproduces a POSIX shell-compatible command line
|
||||||
|
var cmdLine strings.Builder
|
||||||
|
sep := ""
|
||||||
|
|
||||||
|
// Make sure environment variables are always
|
||||||
|
// printed in the same order
|
||||||
|
var hookEnvKeys []HookEnvVar
|
||||||
|
for k := range r.Env {
|
||||||
|
hookEnvKeys = append(hookEnvKeys, k)
|
||||||
|
}
|
||||||
|
sort.Slice(hookEnvKeys, func(i, j int) bool { return string(hookEnvKeys[i]) < string(hookEnvKeys[j]) })
|
||||||
|
|
||||||
|
for _, k := range hookEnvKeys {
|
||||||
|
cmdLine.WriteString(fmt.Sprintf("%s%s='%s'", sep, k, r.Env[k]))
|
||||||
|
sep = " "
|
||||||
|
}
|
||||||
|
|
||||||
|
cmdLine.WriteString(fmt.Sprintf("%s%s", sep, r.Command))
|
||||||
|
for _, a := range r.Args {
|
||||||
|
cmdLine.WriteString(fmt.Sprintf("%s'%s'", sep, a))
|
||||||
|
}
|
||||||
|
|
||||||
|
var msg string
|
||||||
|
if r.Err == nil {
|
||||||
|
msg = "command hook"
|
||||||
|
} else {
|
||||||
|
msg = fmt.Sprintf("command hook failed with %q", r.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s: \"%s\"", msg, cmdLine.String()) // no %q to make copy-pastable
|
||||||
|
}
|
||||||
|
func (r *CommandHookReport) Error() string {
|
||||||
|
if r.Err == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%s FAILED with error: %s", r.String(), r.Err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *CommandHookReport) HadError() bool {
|
||||||
|
return r.Err != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCommandHook(in *config.HookCommand) (r *CommandHook, err error) {
|
||||||
|
r = &CommandHook{
|
||||||
|
errIsFatal: in.ErrIsFatal,
|
||||||
|
command: in.Path,
|
||||||
|
timeout: in.Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
r.filter, err = filters.DatasetMapFilterFromConfig(in.Filesystems)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("cannot parse filesystem filter: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
r.edge = Pre | Post
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CommandHook) Filesystems() Filter {
|
||||||
|
return h.filter
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CommandHook) ErrIsFatal() bool {
|
||||||
|
return h.errIsFatal
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CommandHook) String() string {
|
||||||
|
return h.command
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *CommandHook) Run(ctx context.Context, edge Edge, phase Phase, dryRun bool, extra Env, state map[interface{}]interface{}) HookReport {
|
||||||
|
l := getLogger(ctx).WithField("command", h.command)
|
||||||
|
|
||||||
|
cmdCtx, cancel := context.WithTimeout(ctx, h.timeout)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
cmdExec := exec.CommandContext(cmdCtx, h.command)
|
||||||
|
|
||||||
|
hookEnv := NewHookEnv(edge, phase, dryRun, h.timeout, extra)
|
||||||
|
cmdEnv := os.Environ()
|
||||||
|
for k, v := range hookEnv {
|
||||||
|
cmdEnv = append(cmdEnv, fmt.Sprintf("%s=%s", k, v))
|
||||||
|
}
|
||||||
|
cmdExec.Env = cmdEnv
|
||||||
|
|
||||||
|
var scanMutex sync.Mutex
|
||||||
|
combinedOutput, err := circlog.NewCircularLog(envconst.Int("ZREPL_MAX_HOOK_LOG_SIZE", MAX_HOOK_LOG_SIZE_DEFAULT))
|
||||||
|
if err != nil {
|
||||||
|
return &CommandHookReport{Err: err}
|
||||||
|
}
|
||||||
|
logErrWriter := NewLogWriter(&scanMutex, l, logger.Warn, "stderr")
|
||||||
|
logOutWriter := NewLogWriter(&scanMutex, l, logger.Info, "stdout")
|
||||||
|
defer logErrWriter.Close()
|
||||||
|
defer logOutWriter.Close()
|
||||||
|
|
||||||
|
cmdExec.Stderr = io.MultiWriter(logErrWriter, combinedOutput)
|
||||||
|
cmdExec.Stdout = io.MultiWriter(logOutWriter, combinedOutput)
|
||||||
|
|
||||||
|
report := &CommandHookReport{
|
||||||
|
Command: h.command,
|
||||||
|
Env: hookEnv,
|
||||||
|
// no report.Args
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cmdExec.Start()
|
||||||
|
if err != nil {
|
||||||
|
report.Err = err
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
|
||||||
|
err = cmdExec.Wait()
|
||||||
|
combinedOutputBytes := combinedOutput.Bytes()
|
||||||
|
report.CapturedStdoutStderrCombined = make([]byte, len(combinedOutputBytes))
|
||||||
|
copy(report.CapturedStdoutStderrCombined, combinedOutputBytes)
|
||||||
|
if err != nil {
|
||||||
|
if cmdCtx.Err() == context.DeadlineExceeded {
|
||||||
|
report.Err = fmt.Errorf("timed out after %s: %s", h.timeout, err)
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
report.Err = err
|
||||||
|
return report
|
||||||
|
}
|
||||||
|
|
||||||
|
return report
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
sqldriver "database/sql/driver"
|
||||||
|
|
||||||
|
"github.com/go-sql-driver/mysql"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Hook to implement the following recommmendation from MySQL docs
|
||||||
|
// https://dev.mysql.com/doc/mysql-backup-excerpt/5.7/en/backup-methods.html
|
||||||
|
//
|
||||||
|
// Making Backups Using a File System Snapshot:
|
||||||
|
//
|
||||||
|
// If you are using a Veritas file system, you can make a backup like this:
|
||||||
|
//
|
||||||
|
// From a client program, execute FLUSH TABLES WITH READ LOCK.
|
||||||
|
// From another shell, execute mount vxfs snapshot.
|
||||||
|
// From the first client, execute UNLOCK TABLES.
|
||||||
|
// Copy files from the snapshot.
|
||||||
|
// Unmount the snapshot.
|
||||||
|
//
|
||||||
|
// Similar snapshot capabilities may be available in other file systems, such as LVM or ZFS.
|
||||||
|
//
|
||||||
|
|
||||||
|
type MySQLLockTables struct {
|
||||||
|
errIsFatal bool
|
||||||
|
connector sqldriver.Connector
|
||||||
|
filesystems Filter
|
||||||
|
}
|
||||||
|
|
||||||
|
type myLockTablesStateKey int
|
||||||
|
|
||||||
|
const (
|
||||||
|
myLockTablesConnection myLockTablesStateKey = 1 + iota
|
||||||
|
)
|
||||||
|
|
||||||
|
func MyLockTablesFromConfig(in *config.HookMySQLLockTables) (*MySQLLockTables, error) {
|
||||||
|
conf, err := mysql.ParseDSN(in.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "`dsn` invalid")
|
||||||
|
}
|
||||||
|
cn, err := mysql.NewConnector(conf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "`connect` invalid")
|
||||||
|
}
|
||||||
|
|
||||||
|
filesystems, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "`filesystems` invalid")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &MySQLLockTables{
|
||||||
|
in.ErrIsFatal,
|
||||||
|
cn,
|
||||||
|
filesystems,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MySQLLockTables) ErrIsFatal() bool { return h.errIsFatal }
|
||||||
|
func (h *MySQLLockTables) Filesystems() Filter { return h.filesystems }
|
||||||
|
func (h *MySQLLockTables) String() string { return "MySQL FLUSH TABLES WITH READ LOCK" }
|
||||||
|
|
||||||
|
type MyLockTablesReport struct {
|
||||||
|
What string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MyLockTablesReport) HadError() bool { return r.Err != nil }
|
||||||
|
func (r *MyLockTablesReport) Error() string { return r.String() }
|
||||||
|
func (r *MyLockTablesReport) String() string {
|
||||||
|
var s strings.Builder
|
||||||
|
s.WriteString(r.What)
|
||||||
|
if r.Err != nil {
|
||||||
|
fmt.Fprintf(&s, ": %s", r.Err)
|
||||||
|
}
|
||||||
|
return s.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MySQLLockTables) Run(ctx context.Context, edge Edge, phase Phase, dryRun bool, extra Env, state map[interface{}]interface{}) HookReport {
|
||||||
|
fs, ok := extra[EnvFS]
|
||||||
|
if !ok {
|
||||||
|
panic(extra)
|
||||||
|
}
|
||||||
|
dp, err := zfs.NewDatasetPath(fs)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
if pass, err := h.filesystems.Filter(dp); err != nil {
|
||||||
|
return &MyLockTablesReport{What: "filesystem filter", Err: err}
|
||||||
|
} else if !pass {
|
||||||
|
getLogger(ctx).Debug("filesystem does not match filter, skipping")
|
||||||
|
return &MyLockTablesReport{What: "filesystem filter skipped this filesystem", Err: nil}
|
||||||
|
}
|
||||||
|
|
||||||
|
switch edge {
|
||||||
|
case Pre:
|
||||||
|
err := h.doRunPre(ctx, dp, dryRun, state)
|
||||||
|
return &MyLockTablesReport{"FLUSH TABLES WITH READ LOCK", err}
|
||||||
|
case Post:
|
||||||
|
err := h.doRunPost(ctx, dp, dryRun, state)
|
||||||
|
return &MyLockTablesReport{"UNLOCK TABLES", err}
|
||||||
|
}
|
||||||
|
return &MyLockTablesReport{What: "skipped this edge", Err: nil}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MySQLLockTables) doRunPre(ctx context.Context, fs *zfs.DatasetPath, dry bool, state map[interface{}]interface{}) (err error) {
|
||||||
|
db := sql.OpenDB(h.connector)
|
||||||
|
defer func(err *error) {
|
||||||
|
if *err != nil {
|
||||||
|
db.Close()
|
||||||
|
}
|
||||||
|
}(&err)
|
||||||
|
|
||||||
|
getLogger(ctx).Debug("do FLUSH TABLES WITH READ LOCK")
|
||||||
|
_, err = db.ExecContext(ctx, "FLUSH TABLES WITH READ LOCK")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
state[myLockTablesConnection] = db
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MySQLLockTables) doRunPost(ctx context.Context, fs *zfs.DatasetPath, dry bool, state map[interface{}]interface{}) error {
|
||||||
|
|
||||||
|
db := state[myLockTablesConnection].(*sql.DB)
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
getLogger(ctx).Debug("do UNLOCK TABLES")
|
||||||
|
_, err := db.ExecContext(ctx, "UNLOCK TABLES")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/lib/pq"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PgChkptHook struct {
|
||||||
|
errIsFatal bool
|
||||||
|
connector *pq.Connector
|
||||||
|
filesystems Filter
|
||||||
|
}
|
||||||
|
|
||||||
|
func PgChkptHookFromConfig(in *config.HookPostgresCheckpoint) (*PgChkptHook, error) {
|
||||||
|
filesystems, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "`filesystems` invalid")
|
||||||
|
}
|
||||||
|
cn, err := pq.NewConnector(in.DSN)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "`dsn` invalid")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &PgChkptHook{
|
||||||
|
in.ErrIsFatal,
|
||||||
|
cn,
|
||||||
|
filesystems,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *PgChkptHook) ErrIsFatal() bool { return h.errIsFatal }
|
||||||
|
func (h *PgChkptHook) Filesystems() Filter { return h.filesystems }
|
||||||
|
func (h *PgChkptHook) String() string { return "postgres checkpoint" }
|
||||||
|
|
||||||
|
type PgChkptHookReport struct{ Err error }
|
||||||
|
|
||||||
|
func (r *PgChkptHookReport) HadError() bool { return r.Err != nil }
|
||||||
|
func (r *PgChkptHookReport) Error() string { return r.Err.Error() }
|
||||||
|
func (r *PgChkptHookReport) String() string {
|
||||||
|
if r.Err != nil {
|
||||||
|
return fmt.Sprintf("postgres CHECKPOINT failed: %s", r.Err)
|
||||||
|
} else {
|
||||||
|
return "postgres CHECKPOINT completed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *PgChkptHook) Run(ctx context.Context, edge Edge, phase Phase, dryRun bool, extra Env, state map[interface{}]interface{}) HookReport {
|
||||||
|
if edge != Pre {
|
||||||
|
return &PgChkptHookReport{nil}
|
||||||
|
}
|
||||||
|
fs, ok := extra[EnvFS]
|
||||||
|
if !ok {
|
||||||
|
panic(extra)
|
||||||
|
}
|
||||||
|
dp, err := zfs.NewDatasetPath(fs)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
err = h.doRunPre(ctx, dp, dryRun)
|
||||||
|
return &PgChkptHookReport{err}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *PgChkptHook) doRunPre(ctx context.Context, fs *zfs.DatasetPath, dry bool) error {
|
||||||
|
|
||||||
|
if pass, err := h.filesystems.Filter(fs); err != nil || !pass {
|
||||||
|
getLogger(ctx).Debug("filesystem does not match filter, skipping")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
db := sql.OpenDB(h.connector)
|
||||||
|
defer db.Close()
|
||||||
|
dl, ok := ctx.Deadline()
|
||||||
|
if ok {
|
||||||
|
timeout := uint64(math.Floor(time.Until(dl).Seconds() * 1000)) // TODO go1.13 milliseconds
|
||||||
|
getLogger(ctx).WithField("statement_timeout", timeout).Debug("setting statement timeout for CHECKPOINT")
|
||||||
|
_, err := db.ExecContext(ctx, "SET statement_timeout TO ?", timeout)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dry {
|
||||||
|
getLogger(ctx).Debug("dry-run - use ping instead of CHECKPOINT")
|
||||||
|
return db.PingContext(ctx)
|
||||||
|
}
|
||||||
|
getLogger(ctx).Info("execute CHECKPOINT command")
|
||||||
|
_, err := db.ExecContext(ctx, "CHECKPOINT")
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,489 @@
|
|||||||
|
package hooks_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"regexp"
|
||||||
|
"testing"
|
||||||
|
"text/template"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon/hooks"
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
|
"github.com/zrepl/zrepl/logger"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type comparisonAssertionFunc func(require.TestingT, interface{}, interface{}, ...interface{})
|
||||||
|
type valueAssertionFunc func(require.TestingT, interface{}, ...interface{})
|
||||||
|
|
||||||
|
type expectStep struct {
|
||||||
|
ExpectedEdge hooks.Edge
|
||||||
|
ExpectStatus hooks.StepStatus
|
||||||
|
OutputTest valueAssertionFunc
|
||||||
|
ErrorTest valueAssertionFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
type testCase struct {
|
||||||
|
Name string
|
||||||
|
Config []string
|
||||||
|
IsSlow bool
|
||||||
|
SuppressOutput bool
|
||||||
|
|
||||||
|
ExpectCallbackSkipped bool
|
||||||
|
ExpectHadFatalErr bool
|
||||||
|
ExpectHadError bool
|
||||||
|
ExpectStepReports []expectStep
|
||||||
|
}
|
||||||
|
|
||||||
|
func curryLeft(f comparisonAssertionFunc, expected interface{}) valueAssertionFunc {
|
||||||
|
return curry(f, expected, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func curryRight(f comparisonAssertionFunc, expected interface{}) valueAssertionFunc {
|
||||||
|
return curry(f, expected, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func curry(f comparisonAssertionFunc, expected interface{}, right bool) (ret valueAssertionFunc) {
|
||||||
|
ret = func(t require.TestingT, s interface{}, v ...interface{}) {
|
||||||
|
var x interface{}
|
||||||
|
var y interface{}
|
||||||
|
if right {
|
||||||
|
x = s
|
||||||
|
y = expected
|
||||||
|
} else {
|
||||||
|
x = expected
|
||||||
|
y = s
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(v) > 0 {
|
||||||
|
f(t, x, y, v)
|
||||||
|
} else {
|
||||||
|
f(t, x, y)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHooks(t *testing.T) {
|
||||||
|
ctx, end := trace.WithTaskFromStack(context.Background())
|
||||||
|
defer end()
|
||||||
|
|
||||||
|
testFSName := "testpool/testdataset"
|
||||||
|
testSnapshotName := "testsnap"
|
||||||
|
|
||||||
|
tmpl, err := template.New("TestHooks").Parse(`
|
||||||
|
jobs:
|
||||||
|
- name: TestHooks
|
||||||
|
type: snap
|
||||||
|
filesystems: {"<": true}
|
||||||
|
snapshotting:
|
||||||
|
type: periodic
|
||||||
|
interval: 1m
|
||||||
|
prefix: zrepl_snapjob_
|
||||||
|
hooks:
|
||||||
|
{{- template "List" . }}
|
||||||
|
pruning:
|
||||||
|
keep:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
regexpTest := func(s string) valueAssertionFunc {
|
||||||
|
return curryLeft(require.Regexp, regexp.MustCompile(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
containsTest := func(s string) valueAssertionFunc {
|
||||||
|
return curryRight(require.Contains, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
testTable := []testCase{
|
||||||
|
testCase{
|
||||||
|
Name: "no_hooks",
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
testCase{
|
||||||
|
Name: "timeout",
|
||||||
|
IsSlow: true,
|
||||||
|
ExpectHadError: true,
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-timeout.sh, timeout: 2s}`},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST pre_testing %s@%s ZREPL_TIMEOUT=2", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest(`timed out after 2(.\d+)?s`),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToPreErr,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
testCase{
|
||||||
|
Name: "check_env",
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-report-env.sh}`},
|
||||||
|
ExpectHadError: false,
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST post_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "nonfatal_pre_error_continues",
|
||||||
|
ExpectCallbackSkipped: false,
|
||||||
|
ExpectHadError: true,
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-error.sh}`},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST ERROR pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest("^command hook failed.*exit status 1$"),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToPreErr, // post-edge is not executed for failing pre-edge
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "pre_error_fatal_skips_subsequent_pre_edges_and_callback_and_its_post_edge_and_post_edges",
|
||||||
|
ExpectCallbackSkipped: true,
|
||||||
|
ExpectHadFatalErr: true,
|
||||||
|
ExpectHadError: true,
|
||||||
|
Config: []string{
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-error.sh, err_is_fatal: true}`,
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-report-env.sh}`,
|
||||||
|
},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST ERROR pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest("^command hook failed.*exit status 1$"),
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToFatalErr,
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepSkippedDueToFatalErr},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToFatalErr,
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToFatalErr,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "post_error_fails_are_ignored_even_if_fatal",
|
||||||
|
ExpectHadFatalErr: false, // only occurs during Post, so it's not a fatal error
|
||||||
|
ExpectHadError: true,
|
||||||
|
Config: []string{
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-post-error.sh, err_is_fatal: true}`,
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-report-env.sh}`,
|
||||||
|
},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
// No-action run of test-post-error.sh
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: require.Empty,
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
// Pre run of test-report-env.sh
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST post_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST ERROR post_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest("^command hook failed.*exit status 1$"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "cleanup_check_env",
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-report-env.sh}`},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST post_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "pre_error_cancels_post",
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-pre-error-post-ok.sh}`},
|
||||||
|
ExpectHadError: true,
|
||||||
|
ExpectHadFatalErr: false,
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST ERROR pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest("^command hook failed.*exit status 1$"),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToPreErr,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "pre_error_does_not_cancel_other_posts_but_itself",
|
||||||
|
Config: []string{
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-report-env.sh}`,
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-pre-error-post-ok.sh}`,
|
||||||
|
},
|
||||||
|
ExpectHadError: true,
|
||||||
|
ExpectHadFatalErr: false,
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepErr,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST ERROR pre_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
ErrorTest: regexpTest("^command hook failed.*exit status 1$"),
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepSkippedDueToPreErr,
|
||||||
|
},
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: containsTest(fmt.Sprintf("TEST post_testing %s@%s", testFSName, testSnapshotName)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
testCase{
|
||||||
|
Name: "exceed_buffer_limit",
|
||||||
|
SuppressOutput: true,
|
||||||
|
Config: []string{`{type: command, path: {{.WorkDir}}/test/test-large-stdout.sh}`},
|
||||||
|
ExpectHadError: false,
|
||||||
|
ExpectHadFatalErr: false,
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Pre,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: func(t require.TestingT, s interface{}, v ...interface{}) {
|
||||||
|
require.Len(t, s, 1<<20)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expectStep{ExpectedEdge: hooks.Callback, ExpectStatus: hooks.StepOk},
|
||||||
|
expectStep{
|
||||||
|
// No-action run of above hook
|
||||||
|
ExpectedEdge: hooks.Post,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
OutputTest: require.Empty,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
|
||||||
|
/*
|
||||||
|
Following not intended to test functionality of
|
||||||
|
filter package. Only to demonstrate that hook
|
||||||
|
filters are being applied. The following should
|
||||||
|
result in NO hooks running. If it does run, a
|
||||||
|
fatal hooks.RunReport will be returned.
|
||||||
|
*/
|
||||||
|
testCase{
|
||||||
|
Name: "exclude_all_filesystems",
|
||||||
|
Config: []string{
|
||||||
|
`{type: command, path: {{.WorkDir}}/test/test-error.sh, err_is_fatal: true, filesystems: {"<": false}}`,
|
||||||
|
},
|
||||||
|
ExpectStepReports: []expectStep{
|
||||||
|
expectStep{
|
||||||
|
ExpectedEdge: hooks.Callback,
|
||||||
|
ExpectStatus: hooks.StepOk,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
parseHookConfig := func(t *testing.T, in string) *config.Config {
|
||||||
|
t.Helper()
|
||||||
|
conf, err := config.ParseConfigBytes([]byte(in))
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, conf)
|
||||||
|
return conf
|
||||||
|
}
|
||||||
|
|
||||||
|
fillHooks := func(tt *testCase) string {
|
||||||
|
// make hook path absolute
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
panic("os.Getwd() failed")
|
||||||
|
}
|
||||||
|
var hooksTmpl string = "\n"
|
||||||
|
for _, l := range tt.Config {
|
||||||
|
hooksTmpl += fmt.Sprintf(" - %s\n", l)
|
||||||
|
}
|
||||||
|
tmpl.New("List").Parse(hooksTmpl)
|
||||||
|
|
||||||
|
var outBytes bytes.Buffer
|
||||||
|
data := struct {
|
||||||
|
WorkDir string
|
||||||
|
}{
|
||||||
|
WorkDir: cwd,
|
||||||
|
}
|
||||||
|
if err := tmpl.Execute(&outBytes, data); err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return outBytes.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
var c *config.Config
|
||||||
|
fs, err := zfs.NewDatasetPath(testFSName)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
log := logger.NewTestLogger(t)
|
||||||
|
|
||||||
|
var cbReached bool
|
||||||
|
cb := hooks.NewCallbackHookForFilesystem("testcallback", fs, func(_ context.Context) error {
|
||||||
|
cbReached = true
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
hookEnvExtra := hooks.Env{
|
||||||
|
hooks.EnvFS: fs.ToString(),
|
||||||
|
hooks.EnvSnapshot: testSnapshotName,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range testTable {
|
||||||
|
if testing.Short() && tt.IsSlow {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run(tt.Name, func(t *testing.T) {
|
||||||
|
c = parseHookConfig(t, fillHooks(&tt))
|
||||||
|
snp := c.Jobs[0].Ret.(*config.SnapJob).Snapshotting.Ret.(*config.SnapshottingPeriodic)
|
||||||
|
hookList, err := hooks.ListFromConfig(&snp.Hooks)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
filteredHooks, err := hookList.CopyFilteredForFilesystem(fs)
|
||||||
|
require.NoError(t, err)
|
||||||
|
plan, err := hooks.NewPlan(&filteredHooks, hooks.PhaseTesting, cb, hookEnvExtra)
|
||||||
|
require.NoError(t, err)
|
||||||
|
t.Logf("REPORT PRE EXECUTION:\n%s", plan.Report())
|
||||||
|
|
||||||
|
cbReached = false
|
||||||
|
|
||||||
|
if testing.Verbose() && !tt.SuppressOutput {
|
||||||
|
ctx = logging.WithLoggers(ctx, logging.SubsystemLoggersWithUniversalLogger(log))
|
||||||
|
}
|
||||||
|
plan.Run(ctx, false)
|
||||||
|
report := plan.Report()
|
||||||
|
|
||||||
|
t.Logf("REPORT POST EXECUTION:\n%s", report)
|
||||||
|
|
||||||
|
/*
|
||||||
|
* TEST ASSERTIONS
|
||||||
|
*/
|
||||||
|
|
||||||
|
t.Logf("len(runReports)=%v", len(report))
|
||||||
|
t.Logf("len(tt.ExpectStepReports)=%v", len(tt.ExpectStepReports))
|
||||||
|
require.Equal(t, len(tt.ExpectStepReports), len(report), "ExpectStepReports must be same length as expected number of hook runs, excluding possible Callback")
|
||||||
|
|
||||||
|
// Check if callback ran, when required
|
||||||
|
if tt.ExpectCallbackSkipped {
|
||||||
|
require.False(t, cbReached, "callback ran but should not have run")
|
||||||
|
} else {
|
||||||
|
require.True(t, cbReached, "callback should have run but did not")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if a fatal run error occurred and was expected
|
||||||
|
require.Equal(t, tt.ExpectHadFatalErr, report.HadFatalError(), "non-matching HadFatalError")
|
||||||
|
require.Equal(t, tt.ExpectHadError, report.HadError(), "non-matching HadError")
|
||||||
|
|
||||||
|
if tt.ExpectHadFatalErr {
|
||||||
|
require.True(t, tt.ExpectHadError, "ExpectHadFatalErr implies ExpectHadError")
|
||||||
|
}
|
||||||
|
if !tt.ExpectHadError {
|
||||||
|
require.False(t, tt.ExpectHadFatalErr, "!ExpectHadError implies !ExpectHadFatalErr")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterate through each expected hook run
|
||||||
|
for i, hook := range tt.ExpectStepReports {
|
||||||
|
t.Logf("expecting report conforming to %v", hook)
|
||||||
|
|
||||||
|
exp, act := hook.ExpectStatus, report[i].Status
|
||||||
|
require.Equal(t, exp, act, "%s != %s", exp, act)
|
||||||
|
|
||||||
|
// Check for required ExpectedEdge
|
||||||
|
require.NotZero(t, hook.ExpectedEdge, "each hook must have an ExpectedEdge")
|
||||||
|
require.Equal(t, hook.ExpectedEdge, report[i].Edge,
|
||||||
|
"incorrect edge: expected %q, actual %q", hook.ExpectedEdge.String(), report[i].Edge.String(),
|
||||||
|
)
|
||||||
|
|
||||||
|
// Check for expected output
|
||||||
|
if hook.OutputTest != nil {
|
||||||
|
require.IsType(t, (*hooks.CommandHookReport)(nil), report[i].Report)
|
||||||
|
chr := report[i].Report.(*hooks.CommandHookReport)
|
||||||
|
hook.OutputTest(t, string(chr.CapturedStdoutStderrCombined))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check for expected errors
|
||||||
|
if hook.ErrorTest != nil {
|
||||||
|
hook.ErrorTest(t, string(report[i].Report.Error()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
// Code generated by "enumer -type=StepStatus -trimprefix=Step"; DO NOT EDIT.
|
||||||
|
|
||||||
|
//
|
||||||
|
package hooks
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
_StepStatusName_0 = "PendingExec"
|
||||||
|
_StepStatusName_1 = "Ok"
|
||||||
|
_StepStatusName_2 = "Err"
|
||||||
|
_StepStatusName_3 = "SkippedDueToFatalErr"
|
||||||
|
_StepStatusName_4 = "SkippedDueToPreErr"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
_StepStatusIndex_0 = [...]uint8{0, 7, 11}
|
||||||
|
_StepStatusIndex_1 = [...]uint8{0, 2}
|
||||||
|
_StepStatusIndex_2 = [...]uint8{0, 3}
|
||||||
|
_StepStatusIndex_3 = [...]uint8{0, 20}
|
||||||
|
_StepStatusIndex_4 = [...]uint8{0, 18}
|
||||||
|
)
|
||||||
|
|
||||||
|
func (i StepStatus) String() string {
|
||||||
|
switch {
|
||||||
|
case 1 <= i && i <= 2:
|
||||||
|
i -= 1
|
||||||
|
return _StepStatusName_0[_StepStatusIndex_0[i]:_StepStatusIndex_0[i+1]]
|
||||||
|
case i == 4:
|
||||||
|
return _StepStatusName_1
|
||||||
|
case i == 8:
|
||||||
|
return _StepStatusName_2
|
||||||
|
case i == 16:
|
||||||
|
return _StepStatusName_3
|
||||||
|
case i == 32:
|
||||||
|
return _StepStatusName_4
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("StepStatus(%d)", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _StepStatusValues = []StepStatus{1, 2, 4, 8, 16, 32}
|
||||||
|
|
||||||
|
var _StepStatusNameToValueMap = map[string]StepStatus{
|
||||||
|
_StepStatusName_0[0:7]: 1,
|
||||||
|
_StepStatusName_0[7:11]: 2,
|
||||||
|
_StepStatusName_1[0:2]: 4,
|
||||||
|
_StepStatusName_2[0:3]: 8,
|
||||||
|
_StepStatusName_3[0:20]: 16,
|
||||||
|
_StepStatusName_4[0:18]: 32,
|
||||||
|
}
|
||||||
|
|
||||||
|
// StepStatusString retrieves an enum value from the enum constants string name.
|
||||||
|
// Throws an error if the param is not part of the enum.
|
||||||
|
func StepStatusString(s string) (StepStatus, error) {
|
||||||
|
if val, ok := _StepStatusNameToValueMap[s]; ok {
|
||||||
|
return val, nil
|
||||||
|
}
|
||||||
|
return 0, fmt.Errorf("%s does not belong to StepStatus values", s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StepStatusValues returns all values of the enum
|
||||||
|
func StepStatusValues() []StepStatus {
|
||||||
|
return _StepStatusValues
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsAStepStatus returns "true" if the value is listed in the enum definition. "false" otherwise
|
||||||
|
func (i StepStatus) IsAStepStatus() bool {
|
||||||
|
for _, v := range _StepStatusValues {
|
||||||
|
if i == v {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
>&2 echo "TEST ERROR $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME"
|
||||||
|
|
||||||
|
exit 1
|
||||||
Executable
+18
@@ -0,0 +1,18 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
# Exceed default hook log size of 1<<20 bytes by double
|
||||||
|
# The Go test should fail if buffer size exceeds 1MB
|
||||||
|
|
||||||
|
pre_testing() {
|
||||||
|
ln=0
|
||||||
|
while :; do printf '%06d: 012345678901234567890123456789012345678901234567890123456789012345678901\n' "$ln"; ln="$(($ln + 1))"; done \
|
||||||
|
| head -c$(( 2 << 20 ))
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$ZREPL_HOOKTYPE" in
|
||||||
|
pre_testing)
|
||||||
|
"$ZREPL_HOOKTYPE";;
|
||||||
|
*)
|
||||||
|
# Not handled by this script
|
||||||
|
exit 0;;
|
||||||
|
esac
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
post_testing() {
|
||||||
|
>&2 echo "TEST ERROR $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME"
|
||||||
|
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$ZREPL_HOOKTYPE" in
|
||||||
|
post_testing)
|
||||||
|
"$ZREPL_HOOKTYPE";;
|
||||||
|
*)
|
||||||
|
# Not handled by this script
|
||||||
|
exit 0;;
|
||||||
|
esac
|
||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
if [ "$ZREPL_HOOKTYPE" = "pre_testing" ]; then
|
||||||
|
>&2 echo "TEST ERROR $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME"
|
||||||
|
exit 1
|
||||||
|
elif [ "$ZREPL_HOOKTYPE" = "post_testing" ]; then
|
||||||
|
echo "TEST $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME"
|
||||||
|
else
|
||||||
|
printf "Unknown hook type: %s" "$ZREPL_HOOKTYPE"
|
||||||
|
exit 255
|
||||||
|
fi
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
echo "TEST $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME ${ZREPL_DRYRUN:+(dry run)}"
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh -eu
|
||||||
|
|
||||||
|
echo "TEST $ZREPL_HOOKTYPE $ZREPL_FS@$ZREPL_SNAPNAME ZREPL_TIMEOUT=$ZREPL_TIMEOUT"
|
||||||
|
|
||||||
|
exec sleep $(($ZREPL_TIMEOUT + 1))
|
||||||
+207
-63
@@ -2,17 +2,20 @@ package job
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/prometheus/common/log"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
"github.com/zrepl/zrepl/util/envconst"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/filters"
|
|
||||||
"github.com/zrepl/zrepl/daemon/job/reset"
|
"github.com/zrepl/zrepl/daemon/job/reset"
|
||||||
"github.com/zrepl/zrepl/daemon/job/wakeup"
|
"github.com/zrepl/zrepl/daemon/job/wakeup"
|
||||||
"github.com/zrepl/zrepl/daemon/logging"
|
|
||||||
"github.com/zrepl/zrepl/daemon/pruner"
|
"github.com/zrepl/zrepl/daemon/pruner"
|
||||||
"github.com/zrepl/zrepl/daemon/snapper"
|
"github.com/zrepl/zrepl/daemon/snapper"
|
||||||
"github.com/zrepl/zrepl/endpoint"
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
@@ -28,14 +31,18 @@ import (
|
|||||||
|
|
||||||
type ActiveSide struct {
|
type ActiveSide struct {
|
||||||
mode activeMode
|
mode activeMode
|
||||||
name string
|
name endpoint.JobID
|
||||||
connecter transport.Connecter
|
connecter transport.Connecter
|
||||||
|
|
||||||
|
replicationDriverConfig driver.Config
|
||||||
|
|
||||||
prunerFactory *pruner.PrunerFactory
|
prunerFactory *pruner.PrunerFactory
|
||||||
|
|
||||||
promRepStateSecs *prometheus.HistogramVec // labels: state
|
promRepStateSecs *prometheus.HistogramVec // labels: state
|
||||||
promPruneSecs *prometheus.HistogramVec // labels: prune_side
|
promPruneSecs *prometheus.HistogramVec // labels: prune_side
|
||||||
promBytesReplicated *prometheus.CounterVec // labels: filesystem
|
promBytesReplicated *prometheus.CounterVec // labels: filesystem
|
||||||
|
promReplicationErrors prometheus.Gauge
|
||||||
|
promLastSuccessful prometheus.Gauge
|
||||||
|
|
||||||
tasksMtx sync.Mutex
|
tasksMtx sync.Mutex
|
||||||
tasks activeSideTasks
|
tasks activeSideTasks
|
||||||
@@ -68,8 +75,7 @@ type activeSideTasks struct {
|
|||||||
func (a *ActiveSide) updateTasks(u func(*activeSideTasks)) activeSideTasks {
|
func (a *ActiveSide) updateTasks(u func(*activeSideTasks)) activeSideTasks {
|
||||||
a.tasksMtx.Lock()
|
a.tasksMtx.Lock()
|
||||||
defer a.tasksMtx.Unlock()
|
defer a.tasksMtx.Unlock()
|
||||||
var copy activeSideTasks
|
copy := a.tasks
|
||||||
copy = a.tasks
|
|
||||||
if u == nil {
|
if u == nil {
|
||||||
return copy
|
return copy
|
||||||
}
|
}
|
||||||
@@ -79,30 +85,33 @@ func (a *ActiveSide) updateTasks(u func(*activeSideTasks)) activeSideTasks {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type activeMode interface {
|
type activeMode interface {
|
||||||
ConnectEndpoints(rpcLoggers rpc.Loggers, connecter transport.Connecter)
|
ConnectEndpoints(ctx context.Context, connecter transport.Connecter)
|
||||||
DisconnectEndpoints()
|
DisconnectEndpoints()
|
||||||
SenderReceiver() (logic.Sender, logic.Receiver)
|
SenderReceiver() (logic.Sender, logic.Receiver)
|
||||||
Type() Type
|
Type() Type
|
||||||
|
PlannerPolicy() logic.PlannerPolicy
|
||||||
RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{})
|
RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{})
|
||||||
|
SnapperReport() *snapper.Report
|
||||||
ResetConnectBackoff()
|
ResetConnectBackoff()
|
||||||
}
|
}
|
||||||
|
|
||||||
type modePush struct {
|
type modePush struct {
|
||||||
setupMtx sync.Mutex
|
setupMtx sync.Mutex
|
||||||
sender *endpoint.Sender
|
sender *endpoint.Sender
|
||||||
receiver *rpc.Client
|
receiver *rpc.Client
|
||||||
fsfilter endpoint.FSFilter
|
senderConfig *endpoint.SenderConfig
|
||||||
snapper *snapper.PeriodicOrManual
|
plannerPolicy *logic.PlannerPolicy
|
||||||
|
snapper snapper.Snapper
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modePush) ConnectEndpoints(loggers rpc.Loggers, connecter transport.Connecter) {
|
func (m *modePush) ConnectEndpoints(ctx context.Context, connecter transport.Connecter) {
|
||||||
m.setupMtx.Lock()
|
m.setupMtx.Lock()
|
||||||
defer m.setupMtx.Unlock()
|
defer m.setupMtx.Unlock()
|
||||||
if m.receiver != nil || m.sender != nil {
|
if m.receiver != nil || m.sender != nil {
|
||||||
panic("inconsistent use of ConnectEndpoints and DisconnectEndpoints")
|
panic("inconsistent use of ConnectEndpoints and DisconnectEndpoints")
|
||||||
}
|
}
|
||||||
m.sender = endpoint.NewSender(m.fsfilter)
|
m.sender = endpoint.NewSender(*m.senderConfig)
|
||||||
m.receiver = rpc.NewClient(connecter, loggers)
|
m.receiver = rpc.NewClient(connecter, rpc.GetLoggersOrPanic(ctx))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modePush) DisconnectEndpoints() {
|
func (m *modePush) DisconnectEndpoints() {
|
||||||
@@ -121,10 +130,17 @@ func (m *modePush) SenderReceiver() (logic.Sender, logic.Receiver) {
|
|||||||
|
|
||||||
func (m *modePush) Type() Type { return TypePush }
|
func (m *modePush) Type() Type { return TypePush }
|
||||||
|
|
||||||
|
func (m *modePush) PlannerPolicy() logic.PlannerPolicy { return *m.plannerPolicy }
|
||||||
|
|
||||||
func (m *modePush) RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{}) {
|
func (m *modePush) RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{}) {
|
||||||
m.snapper.Run(ctx, wakeUpCommon)
|
m.snapper.Run(ctx, wakeUpCommon)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *modePush) SnapperReport() *snapper.Report {
|
||||||
|
r := m.snapper.Report()
|
||||||
|
return &r
|
||||||
|
}
|
||||||
|
|
||||||
func (m *modePush) ResetConnectBackoff() {
|
func (m *modePush) ResetConnectBackoff() {
|
||||||
m.setupMtx.Lock()
|
m.setupMtx.Lock()
|
||||||
defer m.setupMtx.Unlock()
|
defer m.setupMtx.Unlock()
|
||||||
@@ -133,15 +149,35 @@ func (m *modePush) ResetConnectBackoff() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func modePushFromConfig(g *config.Global, in *config.PushJob) (*modePush, error) {
|
func modePushFromConfig(g *config.Global, in *config.PushJob, jobID endpoint.JobID) (*modePush, error) {
|
||||||
m := &modePush{}
|
m := &modePush{}
|
||||||
fsf, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
var err error
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrap(err, "cannnot build filesystem filter")
|
|
||||||
}
|
|
||||||
m.fsfilter = fsf
|
|
||||||
|
|
||||||
if m.snapper, err = snapper.FromConfig(g, fsf, in.Snapshotting); err != nil {
|
m.senderConfig, err = buildSenderConfig(in, jobID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "sender config")
|
||||||
|
}
|
||||||
|
|
||||||
|
replicationConfig, err := logic.ReplicationConfigFromConfig(in.Replication)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "field `replication`")
|
||||||
|
}
|
||||||
|
|
||||||
|
conflictResolution, err := logic.ConflictResolutionFromConfig(in.ConflictResolution)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "field `conflict_resolution`")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.plannerPolicy = &logic.PlannerPolicy{
|
||||||
|
ConflictResolution: conflictResolution,
|
||||||
|
ReplicationConfig: replicationConfig,
|
||||||
|
SizeEstimationConcurrency: in.Replication.Concurrency.SizeEstimates,
|
||||||
|
}
|
||||||
|
if err := m.plannerPolicy.Validate(); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build planner policy")
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.snapper, err = snapper.FromConfig(g, m.senderConfig.FSF, in.Snapshotting); err != nil {
|
||||||
return nil, errors.Wrap(err, "cannot build snapper")
|
return nil, errors.Wrap(err, "cannot build snapper")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,21 +185,22 @@ func modePushFromConfig(g *config.Global, in *config.PushJob) (*modePush, error)
|
|||||||
}
|
}
|
||||||
|
|
||||||
type modePull struct {
|
type modePull struct {
|
||||||
setupMtx sync.Mutex
|
setupMtx sync.Mutex
|
||||||
receiver *endpoint.Receiver
|
receiver *endpoint.Receiver
|
||||||
sender *rpc.Client
|
receiverConfig endpoint.ReceiverConfig
|
||||||
rootFS *zfs.DatasetPath
|
sender *rpc.Client
|
||||||
interval config.PositiveDurationOrManual
|
plannerPolicy *logic.PlannerPolicy
|
||||||
|
interval config.PositiveDurationOrManual
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modePull) ConnectEndpoints(loggers rpc.Loggers, connecter transport.Connecter) {
|
func (m *modePull) ConnectEndpoints(ctx context.Context, connecter transport.Connecter) {
|
||||||
m.setupMtx.Lock()
|
m.setupMtx.Lock()
|
||||||
defer m.setupMtx.Unlock()
|
defer m.setupMtx.Unlock()
|
||||||
if m.receiver != nil || m.sender != nil {
|
if m.receiver != nil || m.sender != nil {
|
||||||
panic("inconsistent use of ConnectEndpoints and DisconnectEndpoints")
|
panic("inconsistent use of ConnectEndpoints and DisconnectEndpoints")
|
||||||
}
|
}
|
||||||
m.receiver = endpoint.NewReceiver(m.rootFS, false)
|
m.receiver = endpoint.NewReceiver(m.receiverConfig)
|
||||||
m.sender = rpc.NewClient(connecter, loggers)
|
m.sender = rpc.NewClient(connecter, rpc.GetLoggersOrPanic(ctx))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modePull) DisconnectEndpoints() {
|
func (m *modePull) DisconnectEndpoints() {
|
||||||
@@ -182,6 +219,8 @@ func (m *modePull) SenderReceiver() (logic.Sender, logic.Receiver) {
|
|||||||
|
|
||||||
func (*modePull) Type() Type { return TypePull }
|
func (*modePull) Type() Type { return TypePull }
|
||||||
|
|
||||||
|
func (m *modePull) PlannerPolicy() logic.PlannerPolicy { return *m.plannerPolicy }
|
||||||
|
|
||||||
func (m *modePull) RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{}) {
|
func (m *modePull) RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{}) {
|
||||||
if m.interval.Manual {
|
if m.interval.Manual {
|
||||||
GetLogger(ctx).Info("manual pull configured, periodic pull disabled")
|
GetLogger(ctx).Info("manual pull configured, periodic pull disabled")
|
||||||
@@ -207,6 +246,10 @@ func (m *modePull) RunPeriodic(ctx context.Context, wakeUpCommon chan<- struct{}
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (m *modePull) SnapperReport() *snapper.Report {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (m *modePull) ResetConnectBackoff() {
|
func (m *modePull) ResetConnectBackoff() {
|
||||||
m.setupMtx.Lock()
|
m.setupMtx.Lock()
|
||||||
defer m.setupMtx.Unlock()
|
defer m.setupMtx.Unlock()
|
||||||
@@ -215,41 +258,97 @@ func (m *modePull) ResetConnectBackoff() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func modePullFromConfig(g *config.Global, in *config.PullJob) (m *modePull, err error) {
|
func modePullFromConfig(g *config.Global, in *config.PullJob, jobID endpoint.JobID) (m *modePull, err error) {
|
||||||
m = &modePull{}
|
m = &modePull{}
|
||||||
m.interval = in.Interval
|
m.interval = in.Interval
|
||||||
|
|
||||||
m.rootFS, err = zfs.NewDatasetPath(in.RootFS)
|
replicationConfig, err := logic.ReplicationConfigFromConfig(in.Replication)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("RootFS is not a valid zfs filesystem path")
|
return nil, errors.Wrap(err, "field `replication`")
|
||||||
}
|
}
|
||||||
if m.rootFS.Length() <= 0 {
|
|
||||||
return nil, errors.New("RootFS must not be empty") // duplicates error check of receiver
|
conflictResolution, err := logic.ConflictResolutionFromConfig(in.ConflictResolution)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "field `conflict_resolution`")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.plannerPolicy = &logic.PlannerPolicy{
|
||||||
|
ConflictResolution: conflictResolution,
|
||||||
|
ReplicationConfig: replicationConfig,
|
||||||
|
SizeEstimationConcurrency: in.Replication.Concurrency.SizeEstimates,
|
||||||
|
}
|
||||||
|
if err := m.plannerPolicy.Validate(); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build planner policy")
|
||||||
|
}
|
||||||
|
|
||||||
|
m.receiverConfig, err = buildReceiverConfig(in, jobID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func activeSide(g *config.Global, in *config.ActiveJob, mode activeMode) (j *ActiveSide, err error) {
|
func replicationDriverConfigFromConfig(in *config.Replication) (c driver.Config, err error) {
|
||||||
|
c = driver.Config{
|
||||||
|
StepQueueConcurrency: in.Concurrency.Steps,
|
||||||
|
MaxAttempts: envconst.Int("ZREPL_REPLICATION_MAX_ATTEMPTS", 3),
|
||||||
|
ReconnectHardFailTimeout: envconst.Duration("ZREPL_REPLICATION_RECONNECT_HARD_FAIL_TIMEOUT", 10*time.Minute),
|
||||||
|
}
|
||||||
|
err = c.Validate()
|
||||||
|
return c, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func activeSide(g *config.Global, in *config.ActiveJob, configJob interface{}, parseFlags config.ParseFlags) (j *ActiveSide, err error) {
|
||||||
|
|
||||||
|
j = &ActiveSide{}
|
||||||
|
j.name, err = endpoint.MakeJobID(in.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "invalid job name")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch v := configJob.(type) {
|
||||||
|
case *config.PushJob:
|
||||||
|
j.mode, err = modePushFromConfig(g, v, j.name) // shadow
|
||||||
|
case *config.PullJob:
|
||||||
|
j.mode, err = modePullFromConfig(g, v, j.name) // shadow
|
||||||
|
default:
|
||||||
|
panic(fmt.Sprintf("implementation error: unknown job type %T", v))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err // no wrapping required
|
||||||
|
}
|
||||||
|
|
||||||
j = &ActiveSide{mode: mode}
|
|
||||||
j.name = in.Name
|
|
||||||
j.promRepStateSecs = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
j.promRepStateSecs = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||||
Namespace: "zrepl",
|
Namespace: "zrepl",
|
||||||
Subsystem: "replication",
|
Subsystem: "replication",
|
||||||
Name: "state_time",
|
Name: "state_time",
|
||||||
Help: "seconds spent during replication",
|
Help: "seconds spent during replication",
|
||||||
ConstLabels: prometheus.Labels{"zrepl_job": j.name},
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
}, []string{"state"})
|
}, []string{"state"})
|
||||||
j.promBytesReplicated = prometheus.NewCounterVec(prometheus.CounterOpts{
|
j.promBytesReplicated = prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
Namespace: "zrepl",
|
Namespace: "zrepl",
|
||||||
Subsystem: "replication",
|
Subsystem: "replication",
|
||||||
Name: "bytes_replicated",
|
Name: "bytes_replicated",
|
||||||
Help: "number of bytes replicated from sender to receiver per filesystem",
|
Help: "number of bytes replicated from sender to receiver per filesystem",
|
||||||
ConstLabels: prometheus.Labels{"zrepl_job": j.name},
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
}, []string{"filesystem"})
|
}, []string{"filesystem"})
|
||||||
|
j.promReplicationErrors = prometheus.NewGauge(prometheus.GaugeOpts{
|
||||||
|
Namespace: "zrepl",
|
||||||
|
Subsystem: "replication",
|
||||||
|
Name: "filesystem_errors",
|
||||||
|
Help: "number of filesystems that failed replication in the latest replication attempt, or -1 if the job failed before enumerating the filesystems",
|
||||||
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
|
})
|
||||||
|
j.promLastSuccessful = prometheus.NewGauge(prometheus.GaugeOpts{
|
||||||
|
Namespace: "zrepl",
|
||||||
|
Subsystem: "replication",
|
||||||
|
Name: "last_successful",
|
||||||
|
Help: "timestamp of last successful replication",
|
||||||
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
|
})
|
||||||
|
|
||||||
j.connecter, err = fromconfig.ConnecterFromConfig(g, in.Connect)
|
j.connecter, err = fromconfig.ConnecterFromConfig(g, in.Connect, parseFlags)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "cannot build client")
|
return nil, errors.Wrap(err, "cannot build client")
|
||||||
}
|
}
|
||||||
@@ -259,13 +358,18 @@ func activeSide(g *config.Global, in *config.ActiveJob, mode activeMode) (j *Act
|
|||||||
Subsystem: "pruning",
|
Subsystem: "pruning",
|
||||||
Name: "time",
|
Name: "time",
|
||||||
Help: "seconds spent in pruner",
|
Help: "seconds spent in pruner",
|
||||||
ConstLabels: prometheus.Labels{"zrepl_job": j.name},
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
}, []string{"prune_side"})
|
}, []string{"prune_side"})
|
||||||
j.prunerFactory, err = pruner.NewPrunerFactory(in.Pruning, j.promPruneSecs)
|
j.prunerFactory, err = pruner.NewPrunerFactory(in.Pruning, j.promPruneSecs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
j.replicationDriverConfig, err = replicationDriverConfigFromConfig(in.Replication)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build replication driver config")
|
||||||
|
}
|
||||||
|
|
||||||
return j, nil
|
return j, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,13 +377,16 @@ func (j *ActiveSide) RegisterMetrics(registerer prometheus.Registerer) {
|
|||||||
registerer.MustRegister(j.promRepStateSecs)
|
registerer.MustRegister(j.promRepStateSecs)
|
||||||
registerer.MustRegister(j.promPruneSecs)
|
registerer.MustRegister(j.promPruneSecs)
|
||||||
registerer.MustRegister(j.promBytesReplicated)
|
registerer.MustRegister(j.promBytesReplicated)
|
||||||
|
registerer.MustRegister(j.promReplicationErrors)
|
||||||
|
registerer.MustRegister(j.promLastSuccessful)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *ActiveSide) Name() string { return j.name }
|
func (j *ActiveSide) Name() string { return j.name.String() }
|
||||||
|
|
||||||
type ActiveSideStatus struct {
|
type ActiveSideStatus struct {
|
||||||
Replication *report.Report
|
Replication *report.Report
|
||||||
PruningSender, PruningReceiver *pruner.Report
|
PruningSender, PruningReceiver *pruner.Report
|
||||||
|
Snapshotting *snapper.Report
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *ActiveSide) Status() *Status {
|
func (j *ActiveSide) Status() *Status {
|
||||||
@@ -296,6 +403,7 @@ func (j *ActiveSide) Status() *Status {
|
|||||||
if tasks.prunerReceiver != nil {
|
if tasks.prunerReceiver != nil {
|
||||||
s.PruningReceiver = tasks.prunerReceiver.Report()
|
s.PruningReceiver = tasks.prunerReceiver.Report()
|
||||||
}
|
}
|
||||||
|
s.Snapshotting = j.mode.SnapperReport()
|
||||||
return &Status{Type: t, JobSpecific: s}
|
return &Status{Type: t, JobSpecific: s}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,19 +413,43 @@ func (j *ActiveSide) OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool) {
|
|||||||
_ = j.mode.(*modePush) // make sure we didn't introduce a new job type
|
_ = j.mode.(*modePush) // make sure we didn't introduce a new job type
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
return pull.rootFS.Copy(), true
|
return pull.receiverConfig.RootWithoutClientComponent.Copy(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *ActiveSide) SenderConfig() *endpoint.SenderConfig {
|
||||||
|
push, ok := j.mode.(*modePush)
|
||||||
|
if !ok {
|
||||||
|
_ = j.mode.(*modePull) // make sure we didn't introduce a new job type
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return push.senderConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// The active side of a replication uses one end (sender or receiver)
|
||||||
|
// directly by method invocation, without going through a transport that
|
||||||
|
// provides a client identity.
|
||||||
|
// However, in order to avoid the need to distinguish between direct-method-invocating
|
||||||
|
// clients and RPC client, we use an invalid client identity as a sentinel value.
|
||||||
|
func FakeActiveSideDirectMethodInvocationClientIdentity(jobId endpoint.JobID) string {
|
||||||
|
return fmt.Sprintf("<local><active><job><client><identity><job=%q>", jobId.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *ActiveSide) Run(ctx context.Context) {
|
func (j *ActiveSide) Run(ctx context.Context) {
|
||||||
|
ctx, endTask := trace.WithTaskAndSpan(ctx, "active-side-job", j.Name())
|
||||||
|
defer endTask()
|
||||||
|
|
||||||
|
ctx = context.WithValue(ctx, endpoint.ClientIdentityKey, FakeActiveSideDirectMethodInvocationClientIdentity(j.name))
|
||||||
|
|
||||||
log := GetLogger(ctx)
|
log := GetLogger(ctx)
|
||||||
ctx = logging.WithSubsystemLoggers(ctx, log)
|
|
||||||
|
|
||||||
defer log.Info("job exiting")
|
defer log.Info("job exiting")
|
||||||
|
|
||||||
periodicDone := make(chan struct{})
|
periodicDone := make(chan struct{})
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
go j.mode.RunPeriodic(ctx, periodicDone)
|
periodicCtx, endTask := trace.WithTask(ctx, "periodic")
|
||||||
|
defer endTask()
|
||||||
|
go j.mode.RunPeriodic(periodicCtx, periodicDone)
|
||||||
|
|
||||||
invocationCount := 0
|
invocationCount := 0
|
||||||
outer:
|
outer:
|
||||||
@@ -333,17 +465,15 @@ outer:
|
|||||||
case <-periodicDone:
|
case <-periodicDone:
|
||||||
}
|
}
|
||||||
invocationCount++
|
invocationCount++
|
||||||
invLog := log.WithField("invocation", invocationCount)
|
invocationCtx, endSpan := trace.WithSpan(ctx, fmt.Sprintf("invocation-%d", invocationCount))
|
||||||
j.do(WithLogger(ctx, invLog))
|
j.do(invocationCtx)
|
||||||
|
endSpan()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *ActiveSide) do(ctx context.Context) {
|
func (j *ActiveSide) do(ctx context.Context) {
|
||||||
|
|
||||||
log := GetLogger(ctx)
|
j.mode.ConnectEndpoints(ctx, j.connecter)
|
||||||
ctx = logging.WithSubsystemLoggers(ctx, log)
|
|
||||||
loggers := rpc.GetLoggersOrPanic(ctx) // filled by WithSubsystemLoggers
|
|
||||||
j.mode.ConnectEndpoints(loggers, j.connecter)
|
|
||||||
defer j.mode.DisconnectEndpoints()
|
defer j.mode.DisconnectEndpoints()
|
||||||
|
|
||||||
// allow cancellation of an invocation (this function)
|
// allow cancellation of an invocation (this function)
|
||||||
@@ -366,20 +496,30 @@ func (j *ActiveSide) do(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
ctx, endSpan := trace.WithSpan(ctx, "replication")
|
||||||
ctx, repCancel := context.WithCancel(ctx)
|
ctx, repCancel := context.WithCancel(ctx)
|
||||||
var repWait driver.WaitFunc
|
var repWait driver.WaitFunc
|
||||||
j.updateTasks(func(tasks *activeSideTasks) {
|
j.updateTasks(func(tasks *activeSideTasks) {
|
||||||
// reset it
|
// reset it
|
||||||
*tasks = activeSideTasks{}
|
*tasks = activeSideTasks{}
|
||||||
tasks.replicationCancel = repCancel
|
tasks.replicationCancel = func() { repCancel(); endSpan() }
|
||||||
tasks.replicationReport, repWait = replication.Do(
|
tasks.replicationReport, repWait = replication.Do(
|
||||||
ctx, logic.NewPlanner(j.promRepStateSecs, j.promBytesReplicated, sender, receiver),
|
ctx, j.replicationDriverConfig, logic.NewPlanner(j.promRepStateSecs, j.promBytesReplicated, sender, receiver, j.mode.PlannerPolicy()),
|
||||||
)
|
)
|
||||||
tasks.state = ActiveSideReplicating
|
tasks.state = ActiveSideReplicating
|
||||||
})
|
})
|
||||||
log.Info("start replication")
|
GetLogger(ctx).Info("start replication")
|
||||||
repWait(true) // wait blocking
|
repWait(true) // wait blocking
|
||||||
repCancel() // always cancel to free up context resources
|
repCancel() // always cancel to free up context resources
|
||||||
|
|
||||||
|
replicationReport := j.tasks.replicationReport()
|
||||||
|
var numErrors = replicationReport.GetFailedFilesystemsCountInLatestAttempt()
|
||||||
|
j.promReplicationErrors.Set(float64(numErrors))
|
||||||
|
if numErrors == 0 {
|
||||||
|
j.promLastSuccessful.SetToCurrentTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
endSpan()
|
||||||
}
|
}
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -388,16 +528,18 @@ func (j *ActiveSide) do(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
ctx, endSpan := trace.WithSpan(ctx, "prune_sender")
|
||||||
ctx, senderCancel := context.WithCancel(ctx)
|
ctx, senderCancel := context.WithCancel(ctx)
|
||||||
tasks := j.updateTasks(func(tasks *activeSideTasks) {
|
tasks := j.updateTasks(func(tasks *activeSideTasks) {
|
||||||
tasks.prunerSender = j.prunerFactory.BuildSenderPruner(ctx, sender, sender)
|
tasks.prunerSender = j.prunerFactory.BuildSenderPruner(ctx, sender, sender)
|
||||||
tasks.prunerSenderCancel = senderCancel
|
tasks.prunerSenderCancel = func() { senderCancel(); endSpan() }
|
||||||
tasks.state = ActiveSidePruneSender
|
tasks.state = ActiveSidePruneSender
|
||||||
})
|
})
|
||||||
log.Info("start pruning sender")
|
GetLogger(ctx).Info("start pruning sender")
|
||||||
tasks.prunerSender.Prune()
|
tasks.prunerSender.Prune()
|
||||||
log.Info("finished pruning sender")
|
GetLogger(ctx).Info("finished pruning sender")
|
||||||
senderCancel()
|
senderCancel()
|
||||||
|
endSpan()
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
select {
|
select {
|
||||||
@@ -405,16 +547,18 @@ func (j *ActiveSide) do(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
|
ctx, endSpan := trace.WithSpan(ctx, "prune_recever")
|
||||||
ctx, receiverCancel := context.WithCancel(ctx)
|
ctx, receiverCancel := context.WithCancel(ctx)
|
||||||
tasks := j.updateTasks(func(tasks *activeSideTasks) {
|
tasks := j.updateTasks(func(tasks *activeSideTasks) {
|
||||||
tasks.prunerReceiver = j.prunerFactory.BuildReceiverPruner(ctx, receiver, sender)
|
tasks.prunerReceiver = j.prunerFactory.BuildReceiverPruner(ctx, receiver, sender)
|
||||||
tasks.prunerReceiverCancel = receiverCancel
|
tasks.prunerReceiverCancel = func() { receiverCancel(); endSpan() }
|
||||||
tasks.state = ActiveSidePruneReceiver
|
tasks.state = ActiveSidePruneReceiver
|
||||||
})
|
})
|
||||||
log.Info("start pruning receiver")
|
GetLogger(ctx).Info("start pruning receiver")
|
||||||
tasks.prunerReceiver.Prune()
|
tasks.prunerReceiver.Prune()
|
||||||
log.Info("finished pruning receiver")
|
GetLogger(ctx).Info("finished pruning receiver")
|
||||||
receiverCancel()
|
receiverCancel()
|
||||||
|
endSpan()
|
||||||
}
|
}
|
||||||
|
|
||||||
j.updateTasks(func(tasks *activeSideTasks) {
|
j.updateTasks(func(tasks *activeSideTasks) {
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package job
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/transport"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFakeActiveSideDirectMethodInvocationClientIdentityDoesNotPassValidityTest(t *testing.T) {
|
||||||
|
jobid, err := endpoint.MakeJobID("validjobname")
|
||||||
|
require.NoError(t, err)
|
||||||
|
clientIdentity := FakeActiveSideDirectMethodInvocationClientIdentity(jobid)
|
||||||
|
t.Logf("%v", clientIdentity)
|
||||||
|
err = transport.ValidateClientIdentity(clientIdentity)
|
||||||
|
assert.Error(t, err)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
// Code generated by "enumer -type=ActiveSideState"; DO NOT EDIT.
|
// Code generated by "enumer -type=ActiveSideState"; DO NOT EDIT.
|
||||||
|
|
||||||
|
//
|
||||||
package job
|
package job
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
+27
-26
@@ -6,13 +6,15 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/util/bandwidthlimit"
|
||||||
)
|
)
|
||||||
|
|
||||||
func JobsFromConfig(c *config.Config) ([]Job, error) {
|
func JobsFromConfig(c *config.Config, parseFlags config.ParseFlags) ([]Job, error) {
|
||||||
js := make([]Job, len(c.Jobs))
|
js := make([]Job, len(c.Jobs))
|
||||||
for i := range c.Jobs {
|
for i := range c.Jobs {
|
||||||
j, err := buildJob(c.Global, c.Jobs[i])
|
j, err := buildJob(c.Global, c.Jobs[i], parseFlags)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -24,13 +26,13 @@ func JobsFromConfig(c *config.Config) ([]Job, error) {
|
|||||||
|
|
||||||
// receiving-side root filesystems must not overlap
|
// receiving-side root filesystems must not overlap
|
||||||
{
|
{
|
||||||
rfss := make([]string, len(js))
|
rfss := make([]string, 0, len(js))
|
||||||
for i, j := range js {
|
for _, j := range js {
|
||||||
jrfs, ok := j.OwnedDatasetSubtreeRoot()
|
jrfs, ok := j.OwnedDatasetSubtreeRoot()
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
rfss[i] = jrfs.ToString()
|
rfss = append(rfss, jrfs.ToString())
|
||||||
}
|
}
|
||||||
if err := validateReceivingSidesDoNotOverlap(rfss); err != nil {
|
if err := validateReceivingSidesDoNotOverlap(rfss); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -40,27 +42,19 @@ func JobsFromConfig(c *config.Config) ([]Job, error) {
|
|||||||
return js, nil
|
return js, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildJob(c *config.Global, in config.JobEnum) (j Job, err error) {
|
func buildJob(c *config.Global, in config.JobEnum, parseFlags config.ParseFlags) (j Job, err error) {
|
||||||
cannotBuildJob := func(e error, name string) (Job, error) {
|
cannotBuildJob := func(e error, name string) (Job, error) {
|
||||||
return nil, errors.Wrapf(e, "cannot build job %q", name)
|
return nil, errors.Wrapf(e, "cannot build job %q", name)
|
||||||
}
|
}
|
||||||
// FIXME prettify this
|
// FIXME prettify this
|
||||||
switch v := in.Ret.(type) {
|
switch v := in.Ret.(type) {
|
||||||
case *config.SinkJob:
|
case *config.SinkJob:
|
||||||
m, err := modeSinkFromConfig(c, v)
|
j, err = passiveSideFromConfig(c, &v.PassiveJob, v, parseFlags)
|
||||||
if err != nil {
|
|
||||||
return cannotBuildJob(err, v.Name)
|
|
||||||
}
|
|
||||||
j, err = passiveSideFromConfig(c, &v.PassiveJob, m)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cannotBuildJob(err, v.Name)
|
return cannotBuildJob(err, v.Name)
|
||||||
}
|
}
|
||||||
case *config.SourceJob:
|
case *config.SourceJob:
|
||||||
m, err := modeSourceFromConfig(c, v)
|
j, err = passiveSideFromConfig(c, &v.PassiveJob, v, parseFlags)
|
||||||
if err != nil {
|
|
||||||
return cannotBuildJob(err, v.Name)
|
|
||||||
}
|
|
||||||
j, err = passiveSideFromConfig(c, &v.PassiveJob, m)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cannotBuildJob(err, v.Name)
|
return cannotBuildJob(err, v.Name)
|
||||||
}
|
}
|
||||||
@@ -70,20 +64,12 @@ func buildJob(c *config.Global, in config.JobEnum) (j Job, err error) {
|
|||||||
return cannotBuildJob(err, v.Name)
|
return cannotBuildJob(err, v.Name)
|
||||||
}
|
}
|
||||||
case *config.PushJob:
|
case *config.PushJob:
|
||||||
m, err := modePushFromConfig(c, v)
|
j, err = activeSide(c, &v.ActiveJob, v, parseFlags)
|
||||||
if err != nil {
|
|
||||||
return cannotBuildJob(err, v.Name)
|
|
||||||
}
|
|
||||||
j, err = activeSide(c, &v.ActiveJob, m)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cannotBuildJob(err, v.Name)
|
return cannotBuildJob(err, v.Name)
|
||||||
}
|
}
|
||||||
case *config.PullJob:
|
case *config.PullJob:
|
||||||
m, err := modePullFromConfig(c, v)
|
j, err = activeSide(c, &v.ActiveJob, v, parseFlags)
|
||||||
if err != nil {
|
|
||||||
return cannotBuildJob(err, v.Name)
|
|
||||||
}
|
|
||||||
j, err = activeSide(c, &v.ActiveJob, m)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return cannotBuildJob(err, v.Name)
|
return cannotBuildJob(err, v.Name)
|
||||||
}
|
}
|
||||||
@@ -103,6 +89,11 @@ func validateReceivingSidesDoNotOverlap(receivingRootFSs []string) error {
|
|||||||
sort.Slice(rfss, func(i, j int) bool {
|
sort.Slice(rfss, func(i, j int) bool {
|
||||||
return strings.Compare(rfss[i], rfss[j]) == -1
|
return strings.Compare(rfss[i], rfss[j]) == -1
|
||||||
})
|
})
|
||||||
|
// add tailing slash because of hierarchy-simulation
|
||||||
|
// rootfs/ is not root of rootfs2/
|
||||||
|
for i := 0; i < len(rfss); i++ {
|
||||||
|
rfss[i] += "/"
|
||||||
|
}
|
||||||
// idea:
|
// idea:
|
||||||
// no path in rfss must be prefix of another
|
// no path in rfss must be prefix of another
|
||||||
//
|
//
|
||||||
@@ -117,3 +108,13 @@ func validateReceivingSidesDoNotOverlap(receivingRootFSs []string) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func buildBandwidthLimitConfig(in *config.BandwidthLimit) (c bandwidthlimit.Config, _ error) {
|
||||||
|
if in.Max.ToBytes() > 0 && int64(in.Max.ToBytes()) == 0 {
|
||||||
|
return c, fmt.Errorf("bandwidth limit `max` is too small, must at least specify one byte")
|
||||||
|
}
|
||||||
|
return bandwidthlimit.Config{
|
||||||
|
Max: int64(in.Max.ToBytes()),
|
||||||
|
BucketCapacity: int64(in.BucketCapacity.ToBytes()),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package job
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
|
"github.com/zrepl/zrepl/util/nodefault"
|
||||||
|
"github.com/zrepl/zrepl/zfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SendingJobConfig interface {
|
||||||
|
GetFilesystems() config.FilesystemsFilter
|
||||||
|
GetSendOptions() *config.SendOptions // must not be nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildSenderConfig(in SendingJobConfig, jobID endpoint.JobID) (*endpoint.SenderConfig, error) {
|
||||||
|
|
||||||
|
fsf, err := filters.DatasetMapFilterFromConfig(in.GetFilesystems())
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build filesystem filter")
|
||||||
|
}
|
||||||
|
sendOpts := in.GetSendOptions()
|
||||||
|
bwlim, err := buildBandwidthLimitConfig(sendOpts.BandwidthLimit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build bandwith limit config")
|
||||||
|
}
|
||||||
|
|
||||||
|
sc := &endpoint.SenderConfig{
|
||||||
|
FSF: fsf,
|
||||||
|
JobID: jobID,
|
||||||
|
|
||||||
|
Encrypt: &nodefault.Bool{B: sendOpts.Encrypted},
|
||||||
|
SendRaw: sendOpts.Raw,
|
||||||
|
SendProperties: sendOpts.SendProperties,
|
||||||
|
SendBackupProperties: sendOpts.BackupProperties,
|
||||||
|
SendLargeBlocks: sendOpts.LargeBlocks,
|
||||||
|
SendCompressed: sendOpts.Compressed,
|
||||||
|
SendEmbeddedData: sendOpts.EmbeddedData,
|
||||||
|
SendSaved: sendOpts.Saved,
|
||||||
|
|
||||||
|
BandwidthLimit: bwlim,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sc.Validate(); err != nil {
|
||||||
|
return nil, errors.Wrap(err, "cannot build sender config")
|
||||||
|
}
|
||||||
|
|
||||||
|
return sc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type ReceivingJobConfig interface {
|
||||||
|
GetRootFS() string
|
||||||
|
GetAppendClientIdentity() bool
|
||||||
|
GetRecvOptions() *config.RecvOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildReceiverConfig(in ReceivingJobConfig, jobID endpoint.JobID) (rc endpoint.ReceiverConfig, err error) {
|
||||||
|
rootFs, err := zfs.NewDatasetPath(in.GetRootFS())
|
||||||
|
if err != nil {
|
||||||
|
return rc, errors.New("root_fs is not a valid zfs filesystem path")
|
||||||
|
}
|
||||||
|
if rootFs.Length() <= 0 {
|
||||||
|
return rc, errors.New("root_fs must not be empty") // duplicates error check of receiver
|
||||||
|
}
|
||||||
|
|
||||||
|
recvOpts := in.GetRecvOptions()
|
||||||
|
|
||||||
|
bwlim, err := buildBandwidthLimitConfig(recvOpts.BandwidthLimit)
|
||||||
|
if err != nil {
|
||||||
|
return rc, errors.Wrap(err, "cannot build bandwith limit config")
|
||||||
|
}
|
||||||
|
|
||||||
|
placeholderEncryption, err := endpoint.PlaceholderCreationEncryptionPropertyString(recvOpts.Placeholder.Encryption)
|
||||||
|
if err != nil {
|
||||||
|
options := []string{}
|
||||||
|
for _, v := range endpoint.PlaceholderCreationEncryptionPropertyValues() {
|
||||||
|
options = append(options, endpoint.PlaceholderCreationEncryptionProperty(v).String())
|
||||||
|
}
|
||||||
|
return rc, errors.Errorf("placeholder encryption value %q is invalid, must be one of %s",
|
||||||
|
recvOpts.Placeholder.Encryption, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
rc = endpoint.ReceiverConfig{
|
||||||
|
JobID: jobID,
|
||||||
|
RootWithoutClientComponent: rootFs,
|
||||||
|
AppendClientIdentity: in.GetAppendClientIdentity(),
|
||||||
|
|
||||||
|
InheritProperties: recvOpts.Properties.Inherit,
|
||||||
|
OverrideProperties: recvOpts.Properties.Override,
|
||||||
|
|
||||||
|
BandwidthLimit: bwlim,
|
||||||
|
|
||||||
|
PlaceholderEncryption: placeholderEncryption,
|
||||||
|
}
|
||||||
|
if err := rc.Validate(); err != nil {
|
||||||
|
return rc, errors.Wrap(err, "cannot build receiver config")
|
||||||
|
}
|
||||||
|
|
||||||
|
return rc, nil
|
||||||
|
}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
package job
|
package job
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"github.com/kr/pretty"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestValidateReceivingSidesDoNotOverlap(t *testing.T) {
|
func TestValidateReceivingSidesDoNotOverlap(t *testing.T) {
|
||||||
@@ -18,6 +25,7 @@ func TestValidateReceivingSidesDoNotOverlap(t *testing.T) {
|
|||||||
{false, []string{"a"}},
|
{false, []string{"a"}},
|
||||||
{false, []string{"some/path"}},
|
{false, []string{"some/path"}},
|
||||||
{false, []string{"zroot/sink1", "zroot/sink2", "zroot/sink3"}},
|
{false, []string{"zroot/sink1", "zroot/sink2", "zroot/sink3"}},
|
||||||
|
{false, []string{"zroot/foo", "zroot/foobar"}},
|
||||||
{true, []string{"zroot/b", "zroot/b"}},
|
{true, []string{"zroot/b", "zroot/b"}},
|
||||||
{true, []string{"zroot/foo", "zroot/foo/bar", "zroot/baz"}},
|
{true, []string{"zroot/foo", "zroot/foo/bar", "zroot/baz"}},
|
||||||
{false, []string{"a/x", "b/x"}},
|
{false, []string{"a/x", "b/x"}},
|
||||||
@@ -40,3 +48,271 @@ func TestValidateReceivingSidesDoNotOverlap(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestJobIDErrorHandling(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: %s
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: foo
|
||||||
|
client_identity: bar
|
||||||
|
filesystems: {"<": true}
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`
|
||||||
|
fill := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
|
||||||
|
type Case struct {
|
||||||
|
jobName string
|
||||||
|
valid bool
|
||||||
|
}
|
||||||
|
cases := []Case{
|
||||||
|
{"validjobname", true},
|
||||||
|
{"valid with spaces", true},
|
||||||
|
{"invalid\twith\ttabs", false},
|
||||||
|
{"invalid#withdelimiter", false},
|
||||||
|
{"invalid@withdelimiter", false},
|
||||||
|
{"withnewline\\nmiddle", false},
|
||||||
|
{"withnewline\\n", false},
|
||||||
|
{"withslash/", false},
|
||||||
|
{"withslash/inthemiddle", false},
|
||||||
|
{"/", false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range cases {
|
||||||
|
t.Run(cases[i].jobName, func(t *testing.T) {
|
||||||
|
c := cases[i]
|
||||||
|
|
||||||
|
conf, err := config.ParseConfigBytes([]byte(fill(c.jobName)))
|
||||||
|
require.NoError(t, err, "not expecting yaml-config to know about job ids")
|
||||||
|
require.NotNil(t, conf)
|
||||||
|
jobs, err := JobsFromConfig(conf, config.ParseFlagsNone)
|
||||||
|
|
||||||
|
if c.valid {
|
||||||
|
assert.NoError(t, err)
|
||||||
|
require.Len(t, jobs, 1)
|
||||||
|
assert.Equal(t, c.jobName, jobs[0].Name())
|
||||||
|
} else {
|
||||||
|
t.Logf("error: %s", err)
|
||||||
|
assert.Error(t, err)
|
||||||
|
assert.Nil(t, jobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSampleConfigsAreBuiltWithoutErrors(t *testing.T) {
|
||||||
|
paths, err := filepath.Glob("../../config/samples/*")
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("glob failed: %+v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type additionalCheck struct {
|
||||||
|
state int
|
||||||
|
test func(t *testing.T, jobs []Job)
|
||||||
|
}
|
||||||
|
additionalChecks := map[string]*additionalCheck{
|
||||||
|
"bandwidth_limit.yml": {test: testSampleConfig_BandwidthLimit},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, p := range paths {
|
||||||
|
|
||||||
|
if path.Ext(p) != ".yml" {
|
||||||
|
t.Logf("skipping file %s", p)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
filename := path.Base(p)
|
||||||
|
t.Logf("checking for presence additonal checks for file %q", filename)
|
||||||
|
additionalCheck := additionalChecks[filename]
|
||||||
|
if additionalCheck == nil {
|
||||||
|
t.Logf("no additional checks")
|
||||||
|
} else {
|
||||||
|
t.Logf("additional check present")
|
||||||
|
additionalCheck.state = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run(p, func(t *testing.T) {
|
||||||
|
c, err := config.ParseConfig(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("error parsing %s:\n%+v", p, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("file: %s", p)
|
||||||
|
t.Log(pretty.Sprint(c))
|
||||||
|
|
||||||
|
jobs, err := JobsFromConfig(c, config.ParseFlagsNoCertCheck)
|
||||||
|
t.Logf("jobs: %#v", jobs)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
if additionalCheck != nil {
|
||||||
|
additionalCheck.test(t, jobs)
|
||||||
|
additionalCheck.state = 2
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
for basename, c := range additionalChecks {
|
||||||
|
if c.state == 0 {
|
||||||
|
panic("univisited additional check " + basename)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func testSampleConfig_BandwidthLimit(t *testing.T, jobs []Job) {
|
||||||
|
require.Len(t, jobs, 3)
|
||||||
|
|
||||||
|
{
|
||||||
|
limitedSink, ok := jobs[0].(*PassiveSide)
|
||||||
|
require.True(t, ok, "%T", jobs[0])
|
||||||
|
limitedSinkMode, ok := limitedSink.mode.(*modeSink)
|
||||||
|
require.True(t, ok, "%T", limitedSink)
|
||||||
|
|
||||||
|
assert.Equal(t, int64(12345), limitedSinkMode.receiverConfig.BandwidthLimit.Max)
|
||||||
|
assert.Equal(t, int64(1<<17), limitedSinkMode.receiverConfig.BandwidthLimit.BucketCapacity)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
limitedPush, ok := jobs[1].(*ActiveSide)
|
||||||
|
require.True(t, ok, "%T", jobs[1])
|
||||||
|
limitedPushMode, ok := limitedPush.mode.(*modePush)
|
||||||
|
require.True(t, ok, "%T", limitedPush)
|
||||||
|
|
||||||
|
assert.Equal(t, int64(54321), limitedPushMode.senderConfig.BandwidthLimit.Max)
|
||||||
|
assert.Equal(t, int64(1024), limitedPushMode.senderConfig.BandwidthLimit.BucketCapacity)
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
unlimitedSink, ok := jobs[2].(*PassiveSide)
|
||||||
|
require.True(t, ok, "%T", jobs[2])
|
||||||
|
unlimitedSinkMode, ok := unlimitedSink.mode.(*modeSink)
|
||||||
|
require.True(t, ok, "%T", unlimitedSink)
|
||||||
|
|
||||||
|
max := unlimitedSinkMode.receiverConfig.BandwidthLimit.Max
|
||||||
|
assert.Less(t, max, int64(0), max, "unlimited mode <=> negative value for .Max, see bandwidthlimit.Config")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplicationOptions(t *testing.T) {
|
||||||
|
tmpl := `
|
||||||
|
jobs:
|
||||||
|
- name: foo
|
||||||
|
type: push
|
||||||
|
connect:
|
||||||
|
type: local
|
||||||
|
listener_name: foo
|
||||||
|
client_identity: bar
|
||||||
|
filesystems: {"<": true}
|
||||||
|
%s
|
||||||
|
snapshotting:
|
||||||
|
type: manual
|
||||||
|
pruning:
|
||||||
|
keep_sender:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
keep_receiver:
|
||||||
|
- type: last_n
|
||||||
|
count: 10
|
||||||
|
`
|
||||||
|
|
||||||
|
type Test struct {
|
||||||
|
name string
|
||||||
|
input string
|
||||||
|
expectOk func(t *testing.T, a *ActiveSide, m *modePush)
|
||||||
|
expectError bool
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []Test{
|
||||||
|
{
|
||||||
|
name: "defaults",
|
||||||
|
input: `
|
||||||
|
replication: {}
|
||||||
|
`,
|
||||||
|
expectOk: func(t *testing.T, a *ActiveSide, m *modePush) {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "steps_zero",
|
||||||
|
input: `
|
||||||
|
replication:
|
||||||
|
concurrency:
|
||||||
|
steps: 0
|
||||||
|
`,
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "size_estimates_zero",
|
||||||
|
input: `
|
||||||
|
replication:
|
||||||
|
concurrency:
|
||||||
|
size_estimates: 0
|
||||||
|
`,
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "custom_values",
|
||||||
|
input: `
|
||||||
|
replication:
|
||||||
|
concurrency:
|
||||||
|
steps: 23
|
||||||
|
size_estimates: 42
|
||||||
|
`,
|
||||||
|
expectOk: func(t *testing.T, a *ActiveSide, m *modePush) {
|
||||||
|
assert.Equal(t, 23, a.replicationDriverConfig.StepQueueConcurrency)
|
||||||
|
assert.Equal(t, 42, m.plannerPolicy.SizeEstimationConcurrency)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "negative_values_forbidden",
|
||||||
|
input: `
|
||||||
|
replication:
|
||||||
|
concurrency:
|
||||||
|
steps: -23
|
||||||
|
size_estimates: -42
|
||||||
|
`,
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
fill := func(s string) string { return fmt.Sprintf(tmpl, s) }
|
||||||
|
|
||||||
|
for _, ts := range tests {
|
||||||
|
t.Run(ts.name, func(t *testing.T) {
|
||||||
|
assert.True(t, (ts.expectError) != (ts.expectOk != nil))
|
||||||
|
|
||||||
|
cstr := fill(ts.input)
|
||||||
|
t.Logf("testing config:\n%s", cstr)
|
||||||
|
c, err := config.ParseConfigBytes([]byte(cstr))
|
||||||
|
require.NoError(t, err)
|
||||||
|
jobs, err := JobsFromConfig(c, config.ParseFlagsNone)
|
||||||
|
if ts.expectOk != nil {
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NotNil(t, c)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, jobs, 1)
|
||||||
|
a := jobs[0].(*ActiveSide)
|
||||||
|
m := a.mode.(*modePush)
|
||||||
|
ts.expectOk(t, a, m)
|
||||||
|
} else if ts.expectError {
|
||||||
|
require.Error(t, err)
|
||||||
|
} else {
|
||||||
|
t.Fatalf("test must define expectOk or expectError")
|
||||||
|
}
|
||||||
|
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
+20
-25
@@ -6,30 +6,19 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
"github.com/zrepl/zrepl/zfs"
|
"github.com/zrepl/zrepl/zfs"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Logger = logger.Logger
|
type Logger = logger.Logger
|
||||||
|
|
||||||
type contextKey int
|
|
||||||
|
|
||||||
const (
|
|
||||||
contextKeyLog contextKey = iota
|
|
||||||
)
|
|
||||||
|
|
||||||
func GetLogger(ctx context.Context) Logger {
|
func GetLogger(ctx context.Context) Logger {
|
||||||
if l, ok := ctx.Value(contextKeyLog).(Logger); ok {
|
return logging.GetLogger(ctx, logging.SubsysJob)
|
||||||
return l
|
|
||||||
}
|
|
||||||
return logger.NewNullLogger()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func WithLogger(ctx context.Context, l Logger) context.Context {
|
|
||||||
return context.WithValue(ctx, contextKeyLog, l)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
type Job interface {
|
type Job interface {
|
||||||
Name() string
|
Name() string
|
||||||
Run(ctx context.Context)
|
Run(ctx context.Context)
|
||||||
@@ -38,21 +27,22 @@ type Job interface {
|
|||||||
// Jobs that return a subtree of the dataset hierarchy
|
// Jobs that return a subtree of the dataset hierarchy
|
||||||
// must return the root of that subtree as rfs and ok = true
|
// must return the root of that subtree as rfs and ok = true
|
||||||
OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool)
|
OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool)
|
||||||
|
SenderConfig() *endpoint.SenderConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
type Type string
|
type Type string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TypeInternal Type = "internal"
|
TypeInternal Type = "internal"
|
||||||
TypeSnap Type = "snap"
|
TypeSnap Type = "snap"
|
||||||
TypePush Type = "push"
|
TypePush Type = "push"
|
||||||
TypeSink Type = "sink"
|
TypeSink Type = "sink"
|
||||||
TypePull Type = "pull"
|
TypePull Type = "pull"
|
||||||
TypeSource Type = "source"
|
TypeSource Type = "source"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Status struct {
|
type Status struct {
|
||||||
Type Type
|
Type Type
|
||||||
JobSpecific interface{}
|
JobSpecific interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,8 +55,8 @@ func (s *Status) MarshalJSON() ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
m := map[string]json.RawMessage {
|
m := map[string]json.RawMessage{
|
||||||
"type": typeJson,
|
"type": typeJson,
|
||||||
string(s.Type): jobJSON,
|
string(s.Type): jobJSON,
|
||||||
}
|
}
|
||||||
return json.Marshal(m)
|
return json.Marshal(m)
|
||||||
@@ -94,16 +84,21 @@ func (s *Status) UnmarshalJSON(in []byte) (err error) {
|
|||||||
var st SnapJobStatus
|
var st SnapJobStatus
|
||||||
err = json.Unmarshal(jobJSON, &st)
|
err = json.Unmarshal(jobJSON, &st)
|
||||||
s.JobSpecific = &st
|
s.JobSpecific = &st
|
||||||
case TypePull: fallthrough
|
|
||||||
|
case TypePull:
|
||||||
|
fallthrough
|
||||||
case TypePush:
|
case TypePush:
|
||||||
var st ActiveSideStatus
|
var st ActiveSideStatus
|
||||||
err = json.Unmarshal(jobJSON, &st)
|
err = json.Unmarshal(jobJSON, &st)
|
||||||
s.JobSpecific = &st
|
s.JobSpecific = &st
|
||||||
case TypeSource: fallthrough
|
|
||||||
|
case TypeSource:
|
||||||
|
fallthrough
|
||||||
case TypeSink:
|
case TypeSink:
|
||||||
var st PassiveStatus
|
var st PassiveStatus
|
||||||
err = json.Unmarshal(jobJSON, &st)
|
err = json.Unmarshal(jobJSON, &st)
|
||||||
s.JobSpecific = &st
|
s.JobSpecific = &st
|
||||||
|
|
||||||
case TypeInternal:
|
case TypeInternal:
|
||||||
// internal jobs do not report specifics
|
// internal jobs do not report specifics
|
||||||
default:
|
default:
|
||||||
|
|||||||
+78
-33
@@ -7,8 +7,9 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/filters"
|
|
||||||
"github.com/zrepl/zrepl/daemon/logging"
|
"github.com/zrepl/zrepl/daemon/logging"
|
||||||
"github.com/zrepl/zrepl/daemon/snapper"
|
"github.com/zrepl/zrepl/daemon/snapper"
|
||||||
"github.com/zrepl/zrepl/endpoint"
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
@@ -20,55 +21,56 @@ import (
|
|||||||
|
|
||||||
type PassiveSide struct {
|
type PassiveSide struct {
|
||||||
mode passiveMode
|
mode passiveMode
|
||||||
name string
|
name endpoint.JobID
|
||||||
listen transport.AuthenticatedListenerFactory
|
listen transport.AuthenticatedListenerFactory
|
||||||
}
|
}
|
||||||
|
|
||||||
type passiveMode interface {
|
type passiveMode interface {
|
||||||
Handler() rpc.Handler
|
Handler() rpc.Handler
|
||||||
RunPeriodic(ctx context.Context)
|
RunPeriodic(ctx context.Context)
|
||||||
|
SnapperReport() *snapper.Report // may be nil
|
||||||
Type() Type
|
Type() Type
|
||||||
}
|
}
|
||||||
|
|
||||||
type modeSink struct {
|
type modeSink struct {
|
||||||
rootDataset *zfs.DatasetPath
|
receiverConfig endpoint.ReceiverConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modeSink) Type() Type { return TypeSink }
|
func (m *modeSink) Type() Type { return TypeSink }
|
||||||
|
|
||||||
func (m *modeSink) Handler() rpc.Handler {
|
func (m *modeSink) Handler() rpc.Handler {
|
||||||
return endpoint.NewReceiver(m.rootDataset, true)
|
return endpoint.NewReceiver(m.receiverConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modeSink) RunPeriodic(_ context.Context) {}
|
func (m *modeSink) RunPeriodic(_ context.Context) {}
|
||||||
|
func (m *modeSink) SnapperReport() *snapper.Report { return nil }
|
||||||
|
|
||||||
func modeSinkFromConfig(g *config.Global, in *config.SinkJob) (m *modeSink, err error) {
|
func modeSinkFromConfig(g *config.Global, in *config.SinkJob, jobID endpoint.JobID) (m *modeSink, err error) {
|
||||||
m = &modeSink{}
|
m = &modeSink{}
|
||||||
m.rootDataset, err = zfs.NewDatasetPath(in.RootFS)
|
|
||||||
|
m.receiverConfig, err = buildReceiverConfig(in, jobID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("root dataset is not a valid zfs filesystem path")
|
return nil, err
|
||||||
}
|
|
||||||
if m.rootDataset.Length() <= 0 {
|
|
||||||
return nil, errors.New("root dataset must not be empty") // duplicates error check of receiver
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return m, nil
|
return m, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type modeSource struct {
|
type modeSource struct {
|
||||||
fsfilter zfs.DatasetFilter
|
senderConfig *endpoint.SenderConfig
|
||||||
snapper *snapper.PeriodicOrManual
|
snapper snapper.Snapper
|
||||||
}
|
}
|
||||||
|
|
||||||
func modeSourceFromConfig(g *config.Global, in *config.SourceJob) (m *modeSource, err error) {
|
func modeSourceFromConfig(g *config.Global, in *config.SourceJob, jobID endpoint.JobID) (m *modeSource, err error) {
|
||||||
// FIXME exact dedup of modePush
|
// FIXME exact dedup of modePush
|
||||||
m = &modeSource{}
|
m = &modeSource{}
|
||||||
fsf, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.Wrap(err, "cannnot build filesystem filter")
|
|
||||||
}
|
|
||||||
m.fsfilter = fsf
|
|
||||||
|
|
||||||
if m.snapper, err = snapper.FromConfig(g, fsf, in.Snapshotting); err != nil {
|
m.senderConfig, err = buildSenderConfig(in, jobID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "send options")
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.snapper, err = snapper.FromConfig(g, m.senderConfig.FSF, in.Snapshotting); err != nil {
|
||||||
return nil, errors.Wrap(err, "cannot build snapper")
|
return nil, errors.Wrap(err, "cannot build snapper")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,29 +80,55 @@ func modeSourceFromConfig(g *config.Global, in *config.SourceJob) (m *modeSource
|
|||||||
func (m *modeSource) Type() Type { return TypeSource }
|
func (m *modeSource) Type() Type { return TypeSource }
|
||||||
|
|
||||||
func (m *modeSource) Handler() rpc.Handler {
|
func (m *modeSource) Handler() rpc.Handler {
|
||||||
return endpoint.NewSender(m.fsfilter)
|
return endpoint.NewSender(*m.senderConfig)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *modeSource) RunPeriodic(ctx context.Context) {
|
func (m *modeSource) RunPeriodic(ctx context.Context) {
|
||||||
m.snapper.Run(ctx, nil)
|
m.snapper.Run(ctx, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
func passiveSideFromConfig(g *config.Global, in *config.PassiveJob, mode passiveMode) (s *PassiveSide, err error) {
|
func (m *modeSource) SnapperReport() *snapper.Report {
|
||||||
|
r := m.snapper.Report()
|
||||||
|
return &r
|
||||||
|
}
|
||||||
|
|
||||||
s = &PassiveSide{mode: mode, name: in.Name}
|
func passiveSideFromConfig(g *config.Global, in *config.PassiveJob, configJob interface{}, parseFlags config.ParseFlags) (s *PassiveSide, err error) {
|
||||||
if s.listen, err = fromconfig.ListenerFactoryFromConfig(g, in.Serve); err != nil {
|
|
||||||
|
s = &PassiveSide{}
|
||||||
|
|
||||||
|
s.name, err = endpoint.MakeJobID(in.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "invalid job name")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch v := configJob.(type) {
|
||||||
|
case *config.SinkJob:
|
||||||
|
s.mode, err = modeSinkFromConfig(g, v, s.name) // shadow
|
||||||
|
case *config.SourceJob:
|
||||||
|
s.mode, err = modeSourceFromConfig(g, v, s.name) // shadow
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err // no wrapping necessary
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.listen, err = fromconfig.ListenerFactoryFromConfig(g, in.Serve, parseFlags); err != nil {
|
||||||
return nil, errors.Wrap(err, "cannot build listener factory")
|
return nil, errors.Wrap(err, "cannot build listener factory")
|
||||||
}
|
}
|
||||||
|
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *PassiveSide) Name() string { return j.name }
|
func (j *PassiveSide) Name() string { return j.name.String() }
|
||||||
|
|
||||||
type PassiveStatus struct{}
|
type PassiveStatus struct {
|
||||||
|
Snapper *snapper.Report
|
||||||
|
}
|
||||||
|
|
||||||
func (s *PassiveSide) Status() *Status {
|
func (s *PassiveSide) Status() *Status {
|
||||||
return &Status{Type: s.mode.Type()} // FIXME PassiveStatus
|
st := &PassiveStatus{
|
||||||
|
Snapper: s.mode.SnapperReport(),
|
||||||
|
}
|
||||||
|
return &Status{Type: s.mode.Type(), JobSpecific: st}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *PassiveSide) OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool) {
|
func (j *PassiveSide) OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool) {
|
||||||
@@ -109,18 +137,29 @@ func (j *PassiveSide) OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool)
|
|||||||
_ = j.mode.(*modeSource) // make sure we didn't introduce a new job type
|
_ = j.mode.(*modeSource) // make sure we didn't introduce a new job type
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
return sink.rootDataset.Copy(), true
|
return sink.receiverConfig.RootWithoutClientComponent.Copy(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *PassiveSide) SenderConfig() *endpoint.SenderConfig {
|
||||||
|
source, ok := j.mode.(*modeSource)
|
||||||
|
if !ok {
|
||||||
|
_ = j.mode.(*modeSink) // make sure we didn't introduce a new job type
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return source.senderConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
func (*PassiveSide) RegisterMetrics(registerer prometheus.Registerer) {}
|
func (*PassiveSide) RegisterMetrics(registerer prometheus.Registerer) {}
|
||||||
|
|
||||||
func (j *PassiveSide) Run(ctx context.Context) {
|
func (j *PassiveSide) Run(ctx context.Context) {
|
||||||
|
ctx, endTask := trace.WithTaskAndSpan(ctx, "passive-side-job", j.Name())
|
||||||
|
defer endTask()
|
||||||
log := GetLogger(ctx)
|
log := GetLogger(ctx)
|
||||||
defer log.Info("job exiting")
|
defer log.Info("job exiting")
|
||||||
ctx = logging.WithSubsystemLoggers(ctx, log)
|
|
||||||
{
|
{
|
||||||
ctx, cancel := context.WithCancel(ctx) // shadowing
|
ctx, endTask := trace.WithTask(ctx, "periodic") // shadowing
|
||||||
|
defer endTask()
|
||||||
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
go j.mode.RunPeriodic(ctx)
|
go j.mode.RunPeriodic(ctx)
|
||||||
}
|
}
|
||||||
@@ -130,8 +169,14 @@ func (j *PassiveSide) Run(ctx context.Context) {
|
|||||||
panic(fmt.Sprintf("implementation error: j.mode.Handler() returned nil: %#v", j))
|
panic(fmt.Sprintf("implementation error: j.mode.Handler() returned nil: %#v", j))
|
||||||
}
|
}
|
||||||
|
|
||||||
ctxInterceptor := func(handlerCtx context.Context) context.Context {
|
ctxInterceptor := func(handlerCtx context.Context, info rpc.HandlerContextInterceptorData, handler func(ctx context.Context)) {
|
||||||
return logging.WithSubsystemLoggers(handlerCtx, log)
|
// the handlerCtx is clean => need to inherit logging and tracing config from job context
|
||||||
|
handlerCtx = logging.WithInherit(handlerCtx, ctx)
|
||||||
|
handlerCtx = trace.WithInherit(handlerCtx, ctx)
|
||||||
|
|
||||||
|
handlerCtx, endTask := trace.WithTaskAndSpan(handlerCtx, "handler", fmt.Sprintf("job=%q client=%q method=%q", j.Name(), info.ClientIdentity(), info.FullMethod()))
|
||||||
|
defer endTask()
|
||||||
|
handler(handlerCtx)
|
||||||
}
|
}
|
||||||
|
|
||||||
rpcLoggers := rpc.GetLoggersOrPanic(ctx) // WithSubsystemLoggers above
|
rpcLoggers := rpc.GetLoggersOrPanic(ctx) // WithSubsystemLoggers above
|
||||||
|
|||||||
+49
-20
@@ -4,13 +4,18 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"sort"
|
"sort"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
|
||||||
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
|
"github.com/zrepl/zrepl/util/bandwidthlimit"
|
||||||
|
"github.com/zrepl/zrepl/util/nodefault"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/filters"
|
"github.com/zrepl/zrepl/daemon/filters"
|
||||||
"github.com/zrepl/zrepl/daemon/job/wakeup"
|
"github.com/zrepl/zrepl/daemon/job/wakeup"
|
||||||
"github.com/zrepl/zrepl/daemon/logging"
|
|
||||||
"github.com/zrepl/zrepl/daemon/pruner"
|
"github.com/zrepl/zrepl/daemon/pruner"
|
||||||
"github.com/zrepl/zrepl/daemon/snapper"
|
"github.com/zrepl/zrepl/daemon/snapper"
|
||||||
"github.com/zrepl/zrepl/endpoint"
|
"github.com/zrepl/zrepl/endpoint"
|
||||||
@@ -19,18 +24,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type SnapJob struct {
|
type SnapJob struct {
|
||||||
name string
|
name endpoint.JobID
|
||||||
fsfilter zfs.DatasetFilter
|
fsfilter zfs.DatasetFilter
|
||||||
snapper *snapper.PeriodicOrManual
|
snapper snapper.Snapper
|
||||||
|
|
||||||
prunerFactory *pruner.LocalPrunerFactory
|
prunerFactory *pruner.LocalPrunerFactory
|
||||||
|
|
||||||
promPruneSecs *prometheus.HistogramVec // labels: prune_side
|
promPruneSecs *prometheus.HistogramVec // labels: prune_side
|
||||||
|
|
||||||
pruner *pruner.Pruner
|
prunerMtx sync.Mutex
|
||||||
|
pruner *pruner.Pruner
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *SnapJob) Name() string { return j.name }
|
func (j *SnapJob) Name() string { return j.name.String() }
|
||||||
|
|
||||||
func (j *SnapJob) Type() Type { return TypeSnap }
|
func (j *SnapJob) Type() Type { return TypeSnap }
|
||||||
|
|
||||||
@@ -38,20 +44,23 @@ func snapJobFromConfig(g *config.Global, in *config.SnapJob) (j *SnapJob, err er
|
|||||||
j = &SnapJob{}
|
j = &SnapJob{}
|
||||||
fsf, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
fsf, err := filters.DatasetMapFilterFromConfig(in.Filesystems)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrap(err, "cannnot build filesystem filter")
|
return nil, errors.Wrap(err, "cannot build filesystem filter")
|
||||||
}
|
}
|
||||||
j.fsfilter = fsf
|
j.fsfilter = fsf
|
||||||
|
|
||||||
if j.snapper, err = snapper.FromConfig(g, fsf, in.Snapshotting); err != nil {
|
if j.snapper, err = snapper.FromConfig(g, fsf, in.Snapshotting); err != nil {
|
||||||
return nil, errors.Wrap(err, "cannot build snapper")
|
return nil, errors.Wrap(err, "cannot build snapper")
|
||||||
}
|
}
|
||||||
j.name = in.Name
|
j.name, err = endpoint.MakeJobID(in.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "invalid job name")
|
||||||
|
}
|
||||||
j.promPruneSecs = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
j.promPruneSecs = prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||||
Namespace: "zrepl",
|
Namespace: "zrepl",
|
||||||
Subsystem: "pruning",
|
Subsystem: "pruning",
|
||||||
Name: "time",
|
Name: "time",
|
||||||
Help: "seconds spent in pruner",
|
Help: "seconds spent in pruner",
|
||||||
ConstLabels: prometheus.Labels{"zrepl_job": j.name},
|
ConstLabels: prometheus.Labels{"zrepl_job": j.name.String()},
|
||||||
}, []string{"prune_side"})
|
}, []string{"prune_side"})
|
||||||
j.prunerFactory, err = pruner.NewLocalPrunerFactory(in.Pruning, j.promPruneSecs)
|
j.prunerFactory, err = pruner.NewLocalPrunerFactory(in.Pruning, j.promPruneSecs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -65,15 +74,20 @@ func (j *SnapJob) RegisterMetrics(registerer prometheus.Registerer) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SnapJobStatus struct {
|
type SnapJobStatus struct {
|
||||||
Pruning *pruner.Report
|
Pruning *pruner.Report
|
||||||
|
Snapshotting *snapper.Report // may be nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (j *SnapJob) Status() *Status {
|
func (j *SnapJob) Status() *Status {
|
||||||
s := &SnapJobStatus{}
|
s := &SnapJobStatus{}
|
||||||
t := j.Type()
|
t := j.Type()
|
||||||
|
j.prunerMtx.Lock()
|
||||||
if j.pruner != nil {
|
if j.pruner != nil {
|
||||||
s.Pruning = j.pruner.Report()
|
s.Pruning = j.pruner.Report()
|
||||||
}
|
}
|
||||||
|
j.prunerMtx.Unlock()
|
||||||
|
r := j.snapper.Report()
|
||||||
|
s.Snapshotting = &r
|
||||||
return &Status{Type: t, JobSpecific: s}
|
return &Status{Type: t, JobSpecific: s}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,16 +95,21 @@ func (j *SnapJob) OwnedDatasetSubtreeRoot() (rfs *zfs.DatasetPath, ok bool) {
|
|||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (j *SnapJob) SenderConfig() *endpoint.SenderConfig { return nil }
|
||||||
|
|
||||||
func (j *SnapJob) Run(ctx context.Context) {
|
func (j *SnapJob) Run(ctx context.Context) {
|
||||||
|
ctx, endTask := trace.WithTaskAndSpan(ctx, "snap-job", j.Name())
|
||||||
|
defer endTask()
|
||||||
log := GetLogger(ctx)
|
log := GetLogger(ctx)
|
||||||
ctx = logging.WithSubsystemLoggers(ctx, log)
|
|
||||||
|
|
||||||
defer log.Info("job exiting")
|
defer log.Info("job exiting")
|
||||||
|
|
||||||
periodicDone := make(chan struct{})
|
periodicDone := make(chan struct{})
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
ctx, cancel := context.WithCancel(ctx)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
go j.snapper.Run(ctx, periodicDone)
|
periodicCtx, endTask := trace.WithTask(ctx, "snapshotting")
|
||||||
|
defer endTask()
|
||||||
|
go j.snapper.Run(periodicCtx, periodicDone)
|
||||||
|
|
||||||
invocationCount := 0
|
invocationCount := 0
|
||||||
outer:
|
outer:
|
||||||
@@ -105,8 +124,10 @@ outer:
|
|||||||
case <-periodicDone:
|
case <-periodicDone:
|
||||||
}
|
}
|
||||||
invocationCount++
|
invocationCount++
|
||||||
invLog := log.WithField("invocation", invocationCount)
|
|
||||||
j.doPrune(WithLogger(ctx, invLog))
|
invocationCtx, endSpan := trace.WithSpan(ctx, fmt.Sprintf("invocation-%d", invocationCount))
|
||||||
|
j.doPrune(invocationCtx)
|
||||||
|
endSpan()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,7 +138,7 @@ outer:
|
|||||||
// TODO:
|
// TODO:
|
||||||
// This is a work-around for the current package daemon/pruner
|
// This is a work-around for the current package daemon/pruner
|
||||||
// and package pruning.Snapshot limitation: they require the
|
// and package pruning.Snapshot limitation: they require the
|
||||||
// `Replicated` getter method be present, but obviously,
|
// `Replicated` getter method be present, but obviously,
|
||||||
// a local job like SnapJob can't deliver on that.
|
// a local job like SnapJob can't deliver on that.
|
||||||
// But the pruner.Pruner gives up on an FS if no replication
|
// But the pruner.Pruner gives up on an FS if no replication
|
||||||
// cursor is present, which is why this pruner returns the
|
// cursor is present, which is why this pruner returns the
|
||||||
@@ -127,12 +148,9 @@ type alwaysUpToDateReplicationCursorHistory struct {
|
|||||||
target pruner.Target
|
target pruner.Target
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ pruner.History = (*alwaysUpToDateReplicationCursorHistory)(nil)
|
var _ pruner.Sender = (*alwaysUpToDateReplicationCursorHistory)(nil)
|
||||||
|
|
||||||
func (h alwaysUpToDateReplicationCursorHistory) ReplicationCursor(ctx context.Context, req *pdu.ReplicationCursorReq) (*pdu.ReplicationCursorRes, error) {
|
func (h alwaysUpToDateReplicationCursorHistory) ReplicationCursor(ctx context.Context, req *pdu.ReplicationCursorReq) (*pdu.ReplicationCursorRes, error) {
|
||||||
if req.GetGet() == nil {
|
|
||||||
return nil, fmt.Errorf("unsupported ReplicationCursor request: SnapJob only supports GETting a (faked) cursor")
|
|
||||||
}
|
|
||||||
fsvReq := &pdu.ListFilesystemVersionsReq{
|
fsvReq := &pdu.ListFilesystemVersionsReq{
|
||||||
Filesystem: req.GetFilesystem(),
|
Filesystem: req.GetFilesystem(),
|
||||||
}
|
}
|
||||||
@@ -157,10 +175,21 @@ func (h alwaysUpToDateReplicationCursorHistory) ListFilesystems(ctx context.Cont
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (j *SnapJob) doPrune(ctx context.Context) {
|
func (j *SnapJob) doPrune(ctx context.Context) {
|
||||||
|
ctx, endSpan := trace.WithSpan(ctx, "snap-job-do-prune")
|
||||||
|
defer endSpan()
|
||||||
log := GetLogger(ctx)
|
log := GetLogger(ctx)
|
||||||
ctx = logging.WithSubsystemLoggers(ctx, log)
|
sender := endpoint.NewSender(endpoint.SenderConfig{
|
||||||
sender := endpoint.NewSender(j.fsfilter)
|
JobID: j.name,
|
||||||
|
FSF: j.fsfilter,
|
||||||
|
// FIXME the following config fields are irrelevant for SnapJob
|
||||||
|
// because the endpoint is only used as pruner.Target.
|
||||||
|
// However, the implementation requires them to be set.
|
||||||
|
Encrypt: &nodefault.Bool{B: true},
|
||||||
|
BandwidthLimit: bandwidthlimit.NoLimitConfig(),
|
||||||
|
})
|
||||||
|
j.prunerMtx.Lock()
|
||||||
j.pruner = j.prunerFactory.BuildLocalPruner(ctx, sender, alwaysUpToDateReplicationCursorHistory{sender})
|
j.pruner = j.prunerFactory.BuildLocalPruner(ctx, sender, alwaysUpToDateReplicationCursorHistory{sender})
|
||||||
|
j.prunerMtx.Unlock()
|
||||||
log.Info("start pruning")
|
log.Info("start pruning")
|
||||||
j.pruner.Prune()
|
j.pruner.Prune()
|
||||||
log.Info("finished pruning")
|
log.Info("finished pruning")
|
||||||
|
|||||||
+101
-29
@@ -11,16 +11,9 @@ import (
|
|||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/config"
|
"github.com/zrepl/zrepl/config"
|
||||||
"github.com/zrepl/zrepl/daemon/pruner"
|
"github.com/zrepl/zrepl/daemon/logging/trace"
|
||||||
"github.com/zrepl/zrepl/daemon/snapper"
|
|
||||||
"github.com/zrepl/zrepl/endpoint"
|
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
"github.com/zrepl/zrepl/replication/driver"
|
|
||||||
"github.com/zrepl/zrepl/replication/logic"
|
|
||||||
"github.com/zrepl/zrepl/rpc"
|
|
||||||
"github.com/zrepl/zrepl/rpc/transportmux"
|
|
||||||
"github.com/zrepl/zrepl/tlsconf"
|
"github.com/zrepl/zrepl/tlsconf"
|
||||||
"github.com/zrepl/zrepl/transport"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func OutletsFromConfig(in config.LoggingOutletEnumList) (*logger.Outlets, error) {
|
func OutletsFromConfig(in config.LoggingOutletEnumList) (*logger.Outlets, error) {
|
||||||
@@ -37,7 +30,7 @@ func OutletsFromConfig(in config.LoggingOutletEnumList) (*logger.Outlets, error)
|
|||||||
var syslogOutlets, stdoutOutlets int
|
var syslogOutlets, stdoutOutlets int
|
||||||
for lei, le := range in {
|
for lei, le := range in {
|
||||||
|
|
||||||
outlet, minLevel, err := parseOutlet(le)
|
outlet, minLevel, err := ParseOutlet(le)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.Wrapf(err, "cannot parse outlet #%d", lei)
|
return nil, errors.Wrapf(err, "cannot parse outlet #%d", lei)
|
||||||
}
|
}
|
||||||
@@ -68,37 +61,116 @@ func OutletsFromConfig(in config.LoggingOutletEnumList) (*logger.Outlets, error)
|
|||||||
type Subsystem string
|
type Subsystem string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
SubsysMeta Subsystem = "meta"
|
||||||
|
SubsysJob Subsystem = "job"
|
||||||
SubsysReplication Subsystem = "repl"
|
SubsysReplication Subsystem = "repl"
|
||||||
SubsyEndpoint Subsystem = "endpoint"
|
SubsysEndpoint Subsystem = "endpoint"
|
||||||
SubsysPruning Subsystem = "pruning"
|
SubsysPruning Subsystem = "pruning"
|
||||||
SubsysSnapshot Subsystem = "snapshot"
|
SubsysSnapshot Subsystem = "snapshot"
|
||||||
|
SubsysHooks Subsystem = "hook"
|
||||||
SubsysTransport Subsystem = "transport"
|
SubsysTransport Subsystem = "transport"
|
||||||
SubsysTransportMux Subsystem = "transportmux"
|
SubsysTransportMux Subsystem = "transportmux"
|
||||||
SubsysRPC Subsystem = "rpc"
|
SubsysRPC Subsystem = "rpc"
|
||||||
SubsysRPCControl Subsystem = "rpc.ctrl"
|
SubsysRPCControl Subsystem = "rpc.ctrl"
|
||||||
SubsysRPCData Subsystem = "rpc.data"
|
SubsysRPCData Subsystem = "rpc.data"
|
||||||
|
SubsysZFSCmd Subsystem = "zfs.cmd"
|
||||||
|
SubsysTraceData Subsystem = "trace.data"
|
||||||
|
SubsysPlatformtest Subsystem = "platformtest"
|
||||||
)
|
)
|
||||||
|
|
||||||
func WithSubsystemLoggers(ctx context.Context, log logger.Logger) context.Context {
|
var AllSubsystems = []Subsystem{
|
||||||
ctx = logic.WithLogger(ctx, log.WithField(SubsysField, SubsysReplication))
|
SubsysMeta,
|
||||||
ctx = driver.WithLogger(ctx, log.WithField(SubsysField, SubsysReplication))
|
SubsysJob,
|
||||||
ctx = endpoint.WithLogger(ctx, log.WithField(SubsysField, SubsyEndpoint))
|
SubsysReplication,
|
||||||
ctx = pruner.WithLogger(ctx, log.WithField(SubsysField, SubsysPruning))
|
SubsysEndpoint,
|
||||||
ctx = snapper.WithLogger(ctx, log.WithField(SubsysField, SubsysSnapshot))
|
SubsysPruning,
|
||||||
ctx = transport.WithLogger(ctx, log.WithField(SubsysField, SubsysTransport))
|
SubsysSnapshot,
|
||||||
ctx = transportmux.WithLogger(ctx, log.WithField(SubsysField, SubsysTransportMux))
|
SubsysHooks,
|
||||||
ctx = rpc.WithLoggers(ctx,
|
SubsysTransport,
|
||||||
rpc.Loggers{
|
SubsysTransportMux,
|
||||||
General: log.WithField(SubsysField, SubsysRPC),
|
SubsysRPC,
|
||||||
Control: log.WithField(SubsysField, SubsysRPCControl),
|
SubsysRPCControl,
|
||||||
Data: log.WithField(SubsysField, SubsysRPCData),
|
SubsysRPCData,
|
||||||
},
|
SubsysZFSCmd,
|
||||||
)
|
SubsysTraceData,
|
||||||
return ctx
|
SubsysPlatformtest,
|
||||||
}
|
}
|
||||||
|
|
||||||
func LogSubsystem(log logger.Logger, subsys Subsystem) logger.Logger {
|
type injectedField struct {
|
||||||
return log.ReplaceField(SubsysField, subsys)
|
field string
|
||||||
|
value interface{}
|
||||||
|
parent *injectedField
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInjectedField(ctx context.Context, field string, value interface{}) context.Context {
|
||||||
|
var parent *injectedField
|
||||||
|
parentI := ctx.Value(contextKeyInjectedField)
|
||||||
|
if parentI != nil {
|
||||||
|
parent = parentI.(*injectedField)
|
||||||
|
}
|
||||||
|
// TODO sanity-check `field` now
|
||||||
|
this := &injectedField{field, value, parent}
|
||||||
|
return context.WithValue(ctx, contextKeyInjectedField, this)
|
||||||
|
}
|
||||||
|
|
||||||
|
func iterInjectedFields(ctx context.Context, cb func(field string, value interface{})) {
|
||||||
|
injI := ctx.Value(contextKeyInjectedField)
|
||||||
|
if injI == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
inj := injI.(*injectedField)
|
||||||
|
for ; inj != nil; inj = inj.parent {
|
||||||
|
cb(inj.field, inj.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type SubsystemLoggers map[Subsystem]logger.Logger
|
||||||
|
|
||||||
|
func SubsystemLoggersWithUniversalLogger(l logger.Logger) SubsystemLoggers {
|
||||||
|
loggers := make(SubsystemLoggers)
|
||||||
|
for _, s := range AllSubsystems {
|
||||||
|
loggers[s] = l
|
||||||
|
}
|
||||||
|
return loggers
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithLoggers(ctx context.Context, loggers SubsystemLoggers) context.Context {
|
||||||
|
return context.WithValue(ctx, contextKeyLoggers, loggers)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetLoggers(ctx context.Context) SubsystemLoggers {
|
||||||
|
loggers, ok := ctx.Value(contextKeyLoggers).(SubsystemLoggers)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return loggers
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetLogger(ctx context.Context, subsys Subsystem) logger.Logger {
|
||||||
|
return getLoggerImpl(ctx, subsys, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLoggerImpl(ctx context.Context, subsys Subsystem, panicIfEnded bool) logger.Logger {
|
||||||
|
loggers, ok := ctx.Value(contextKeyLoggers).(SubsystemLoggers)
|
||||||
|
if !ok || loggers == nil {
|
||||||
|
return logger.NewNullLogger()
|
||||||
|
}
|
||||||
|
l, ok := loggers[subsys]
|
||||||
|
if !ok {
|
||||||
|
return logger.NewNullLogger()
|
||||||
|
}
|
||||||
|
|
||||||
|
l = l.WithField(SubsysField, subsys)
|
||||||
|
|
||||||
|
l = l.WithField(SpanField, trace.GetSpanStackOrDefault(ctx, *trace.StackKindId, "NOSPAN"))
|
||||||
|
|
||||||
|
fields := make(logger.Fields)
|
||||||
|
iterInjectedFields(ctx, func(field string, value interface{}) {
|
||||||
|
fields[field] = value
|
||||||
|
})
|
||||||
|
l = l.WithFields(fields)
|
||||||
|
|
||||||
|
return l
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseLogFormat(i interface{}) (f EntryFormatter, err error) {
|
func parseLogFormat(i interface{}) (f EntryFormatter, err error) {
|
||||||
@@ -123,7 +195,7 @@ func parseLogFormat(i interface{}) (f EntryFormatter, err error) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseOutlet(in config.LoggingOutletEnum) (o logger.Outlet, level logger.Level, err error) {
|
func ParseOutlet(in config.LoggingOutletEnum) (o logger.Outlet, level logger.Level, err error) {
|
||||||
|
|
||||||
parseCommon := func(common config.LoggingOutletCommon) (logger.Level, EntryFormatter, error) {
|
parseCommon := func(common config.LoggingOutletCommon) (logger.Level, EntryFormatter, error) {
|
||||||
if common.Level == "" || common.Format == "" {
|
if common.Level == "" || common.Format == "" {
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package logging
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type contextKey int
|
||||||
|
|
||||||
|
const (
|
||||||
|
contextKeyLoggers contextKey = 1 + iota
|
||||||
|
contextKeyInjectedField
|
||||||
|
)
|
||||||
|
|
||||||
|
var contextKeys = []contextKey{
|
||||||
|
contextKeyLoggers,
|
||||||
|
contextKeyInjectedField,
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithInherit(ctx, inheritFrom context.Context) context.Context {
|
||||||
|
for _, k := range contextKeys {
|
||||||
|
if v := inheritFrom.Value(k); v != nil {
|
||||||
|
ctx = context.WithValue(ctx, k, v) // no shadow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
@@ -4,11 +4,13 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/fatih/color"
|
"github.com/fatih/color"
|
||||||
"github.com/go-logfmt/logfmt"
|
"github.com/go-logfmt/logfmt"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/zrepl/zrepl/logger"
|
"github.com/zrepl/zrepl/logger"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -20,6 +22,7 @@ const (
|
|||||||
const (
|
const (
|
||||||
JobField string = "job"
|
JobField string = "job"
|
||||||
SubsysField string = "subsystem"
|
SubsysField string = "subsystem"
|
||||||
|
SpanField string = "span"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MetadataFlags int64
|
type MetadataFlags int64
|
||||||
@@ -83,10 +86,10 @@ func (f *HumanFormatter) Format(e *logger.Entry) (out []byte, err error) {
|
|||||||
fmt.Fprintf(&line, "[%s]", col.Sprint(e.Level.Short()))
|
fmt.Fprintf(&line, "[%s]", col.Sprint(e.Level.Short()))
|
||||||
}
|
}
|
||||||
|
|
||||||
prefixFields := []string{JobField, SubsysField}
|
prefixFields := []string{JobField, SubsysField, SpanField}
|
||||||
prefixed := make(map[string]bool, len(prefixFields)+2)
|
prefixed := make(map[string]bool, len(prefixFields)+2)
|
||||||
for _, field := range prefixFields {
|
for _, field := range prefixFields {
|
||||||
val, ok := e.Fields[field].(string)
|
val, ok := e.Fields[field]
|
||||||
if !ok {
|
if !ok {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -159,15 +162,21 @@ func (f *LogfmtFormatter) Format(e *logger.Entry) ([]byte, error) {
|
|||||||
enc := logfmt.NewEncoder(&buf)
|
enc := logfmt.NewEncoder(&buf)
|
||||||
|
|
||||||
if f.metadataFlags&MetadataTime != 0 {
|
if f.metadataFlags&MetadataTime != 0 {
|
||||||
enc.EncodeKeyval(FieldTime, e.Time)
|
err := enc.EncodeKeyval(FieldTime, e.Time)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "logfmt: encode time")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if f.metadataFlags&MetadataLevel != 0 {
|
if f.metadataFlags&MetadataLevel != 0 {
|
||||||
enc.EncodeKeyval(FieldLevel, e.Level)
|
err := enc.EncodeKeyval(FieldLevel, e.Level)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "logfmt: encode level")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// at least try and put job and task in front
|
// at least try and put job and task in front
|
||||||
prefixed := make(map[string]bool, 2)
|
prefixed := make(map[string]bool, 3)
|
||||||
prefix := []string{JobField, SubsysField}
|
prefix := []string{JobField, SubsysField, SpanField}
|
||||||
for _, pf := range prefix {
|
for _, pf := range prefix {
|
||||||
v, ok := e.Fields[pf]
|
v, ok := e.Fields[pf]
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -179,8 +188,10 @@ func (f *LogfmtFormatter) Format(e *logger.Entry) ([]byte, error) {
|
|||||||
prefixed[pf] = true
|
prefixed[pf] = true
|
||||||
}
|
}
|
||||||
|
|
||||||
enc.EncodeKeyval(FieldMessage, e.Message)
|
err := enc.EncodeKeyval(FieldMessage, e.Message)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "logfmt: encode message")
|
||||||
|
}
|
||||||
for k, v := range e.Fields {
|
for k, v := range e.Fields {
|
||||||
if !prefixed[k] {
|
if !prefixed[k] {
|
||||||
if err := logfmtTryEncodeKeyval(enc, k, v); err != nil {
|
if err := logfmtTryEncodeKeyval(enc, k, v); err != nil {
|
||||||
@@ -199,7 +210,10 @@ func logfmtTryEncodeKeyval(enc *logfmt.Encoder, field, value interface{}) error
|
|||||||
case nil: // ok
|
case nil: // ok
|
||||||
return nil
|
return nil
|
||||||
case logfmt.ErrUnsupportedValueType:
|
case logfmt.ErrUnsupportedValueType:
|
||||||
enc.EncodeKeyval(field, fmt.Sprintf("<%T>", value))
|
err := enc.EncodeKeyval(field, fmt.Sprintf("<%T>", value))
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "cannot encode unsupported value type Go type")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return errors.Wrapf(err, "cannot encode field '%s'", field)
|
return errors.Wrapf(err, "cannot encode field '%s'", field)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user