mirror of
https://github.com/deuxfleurs-org/garage.git
synced 2026-08-14 16:13:11 +00:00
Compare commits
44 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 08b1e8a7ea | |||
| ad7ab31411 | |||
| 74a7a550eb | |||
| cc255d46cd | |||
| 8e25a37f0e | |||
| e342db19aa | |||
| f3405b6378 | |||
| 860ccf2811 | |||
| 9df7559446 | |||
| a97467075d | |||
| 9d7535c3f5 | |||
| da6efb4b23 | |||
| e8811f7c9d | |||
| 2090a6187f | |||
| 6f13d083ab | |||
| 8c4f418fe8 | |||
| bef6d627b0 | |||
| e93d7fb228 | |||
| eaf54efb25 | |||
| 93f8d59e4c | |||
| cc1caa87fb | |||
| 69b89fb46d | |||
| 6b47c294f5 | |||
| 28c015d9ff | |||
| 4e8af1d956 | |||
| 3e7f766d95 | |||
| 43e13a501d | |||
| ada7899b24 | |||
| b2c51844a1 | |||
| f6ebcbc7a7 | |||
| df8a4068d9 | |||
| de4276202a | |||
| 1b450c4b49 | |||
| 4067797d01 | |||
| dc017a0cab | |||
| 1acf7e4c66 | |||
| f6060b92aa | |||
| 0f9d9df83b | |||
| f3a097abdf | |||
| 1aed317818 | |||
| c5574c8409 | |||
| 78f0c9ed38 | |||
| de0228ca2a | |||
| df345e37db |
+451
-79
@@ -6,103 +6,90 @@ workspace:
|
||||
base: /drone/garage
|
||||
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
- name: nix_config
|
||||
temp: {}
|
||||
|
||||
environment:
|
||||
HOME: /drone/garage
|
||||
|
||||
steps:
|
||||
- name: restore-cache
|
||||
image: meltwater/drone-cache:dev
|
||||
- name: setup nix
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: cache_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: cache_aws_secret_access_key
|
||||
pull: true
|
||||
settings:
|
||||
restore: true
|
||||
archive_format: "gzip"
|
||||
bucket: drone-cache
|
||||
cache_key: '{{ .Repo.Name }}_{{ checksum "Cargo.lock" }}_{{ arch }}_{{ os }}_gzip'
|
||||
region: garage
|
||||
mount:
|
||||
- '/drone/cargo'
|
||||
- 'target'
|
||||
path_style: true
|
||||
endpoint: https://garage.deuxfleurs.fr
|
||||
when:
|
||||
branch:
|
||||
- nonexistent_skip_this_step
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-build --no-build-output --no-out-link shell.nix --arg release false -A inputDerivation
|
||||
|
||||
- name: code quality
|
||||
image: superboum/garage_builder_amd64:4
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
CARGO_HOME: /drone/cargo
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cargo fmt -- --check
|
||||
- cargo clippy -- --deny warnings
|
||||
- nix-shell --arg release false --run "cargo fmt -- --check"
|
||||
- nix-shell --arg release false --run "cargo clippy -- --deny warnings"
|
||||
|
||||
- name: build
|
||||
image: superboum/garage_builder_amd64:4
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
CARGO_HOME: /drone/cargo
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- pwd
|
||||
- cargo build
|
||||
- nix-build --no-build-output --argstr target x86_64-unknown-linux-musl --arg release false --argstr git_version $DRONE_COMMIT
|
||||
|
||||
- name: cargo-test
|
||||
image: superboum/garage_builder_amd64:4
|
||||
- name: unit tests
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
CARGO_HOME: /drone/cargo
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cargo test
|
||||
|
||||
- name: rebuild-cache
|
||||
image: meltwater/drone-cache:dev
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: cache_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: cache_aws_secret_access_key
|
||||
pull: true
|
||||
settings:
|
||||
rebuild: true
|
||||
archive_format: "gzip"
|
||||
bucket: drone-cache
|
||||
cache_key: '{{ .Repo.Name }}_{{ checksum "Cargo.lock" }}_{{ arch }}_{{ os }}_gzip'
|
||||
region: garage
|
||||
mount:
|
||||
- '/drone/cargo'
|
||||
- 'target'
|
||||
path_style: true
|
||||
endpoint: https://garage.deuxfleurs.fr
|
||||
when:
|
||||
branch:
|
||||
- nonexistent_skip_this_step
|
||||
- |
|
||||
nix-build \
|
||||
--no-build-output \
|
||||
--argstr target x86_64-unknown-linux-musl \
|
||||
--argstr compileMode test
|
||||
- ./result*/bin/garage_api*
|
||||
- ./result*/bin/garage_model*
|
||||
- ./result*/bin/garage_rpc*
|
||||
- ./result*/bin/garage_table*
|
||||
- ./result*/bin/garage_util*
|
||||
- ./result*/bin/garage_web*
|
||||
- ./result*/bin/garage*
|
||||
|
||||
- name: smoke-test
|
||||
image: superboum/garage_builder_amd64:4
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: cargo_home
|
||||
path: /drone/cargo
|
||||
environment:
|
||||
CARGO_HOME: /drone/cargo
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- ./script/test-smoke.sh || (cat /tmp/garage.log; false)
|
||||
- nix-build --no-build-output --argstr target x86_64-unknown-linux-musl --arg release false --argstr git_version $DRONE_COMMIT
|
||||
- nix-shell --arg release false --run ./script/test-smoke.sh || (cat /tmp/garage.log; false)
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- custom
|
||||
- push
|
||||
- pull_request
|
||||
- tag
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
@@ -137,8 +124,393 @@ steps:
|
||||
repo:
|
||||
- Deuxfleurs/garage
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- custom
|
||||
- push
|
||||
- pull_request
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: release-linux-x86_64
|
||||
|
||||
volumes:
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
- name: nix_config
|
||||
temp: {}
|
||||
|
||||
environment:
|
||||
TARGET: x86_64-unknown-linux-musl
|
||||
|
||||
steps:
|
||||
- name: setup nix
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-build --no-build-output --no-out-link shell.nix -A inputDerivation
|
||||
|
||||
- name: build
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-build --no-build-output --argstr target $TARGET --arg release true --argstr git_version $DRONE_COMMIT
|
||||
|
||||
- name: integration
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-shell --run ./script/test-smoke.sh || (cat /tmp/garage.log; false)
|
||||
|
||||
- name: push static binary
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: garagehq_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: garagehq_aws_secret_access_key
|
||||
commands:
|
||||
- nix-shell --arg rust false --arg integration false --run "to_s3"
|
||||
|
||||
- name: docker build and publish
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
DOCKER_AUTH:
|
||||
from_secret: docker_auth
|
||||
DOCKER_PLATFORM: "linux/amd64"
|
||||
CONTAINER_NAME: "dxflrs/amd64_garage"
|
||||
HOME: "/kaniko"
|
||||
commands:
|
||||
- mkdir -p /kaniko/.docker
|
||||
- echo $DOCKER_AUTH > /kaniko/.docker/config.json
|
||||
- export CONTAINER_TAG=${DRONE_TAG:-$DRONE_COMMIT}
|
||||
- nix-shell --arg rust false --arg integration false --run "to_docker"
|
||||
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: release-linux-i686
|
||||
|
||||
volumes:
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
- name: nix_config
|
||||
temp: {}
|
||||
|
||||
environment:
|
||||
TARGET: i686-unknown-linux-musl
|
||||
|
||||
steps:
|
||||
- name: setup nix
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-build --no-build-output --no-out-link shell.nix -A inputDerivation
|
||||
|
||||
- name: build
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-build --no-build-output --argstr target $TARGET --arg release true --argstr git_version $DRONE_COMMIT
|
||||
|
||||
- name: integration
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-shell --run ./script/test-smoke.sh || (cat /tmp/garage.log; false)
|
||||
|
||||
- name: push static binary
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: garagehq_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: garagehq_aws_secret_access_key
|
||||
commands:
|
||||
- nix-shell --arg rust false --arg integration false --run "to_s3"
|
||||
|
||||
- name: docker build and publish
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
DOCKER_AUTH:
|
||||
from_secret: docker_auth
|
||||
DOCKER_PLATFORM: "linux/386"
|
||||
CONTAINER_NAME: "dxflrs/386_garage"
|
||||
HOME: "/kaniko"
|
||||
commands:
|
||||
- mkdir -p /kaniko/.docker
|
||||
- echo $DOCKER_AUTH > /kaniko/.docker/config.json
|
||||
- export CONTAINER_TAG=${DRONE_TAG:-$DRONE_COMMIT}
|
||||
- nix-shell --arg rust false --arg integration false --run "to_docker"
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: release-linux-aarch64
|
||||
|
||||
volumes:
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
- name: nix_config
|
||||
temp: {}
|
||||
|
||||
environment:
|
||||
TARGET: aarch64-unknown-linux-musl
|
||||
|
||||
steps:
|
||||
- name: setup nix
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-build --no-build-output --no-out-link ./shell.nix --arg rust false --arg integration false -A inputDerivation
|
||||
|
||||
- name: build
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-build --no-build-output --argstr target $TARGET --arg release true --argstr git_version $DRONE_COMMIT
|
||||
|
||||
- name: push static binary
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: garagehq_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: garagehq_aws_secret_access_key
|
||||
commands:
|
||||
- nix-shell --arg rust false --arg integration false --run "to_s3"
|
||||
|
||||
- name: docker build and publish
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
DOCKER_AUTH:
|
||||
from_secret: docker_auth
|
||||
DOCKER_PLATFORM: "linux/arm64"
|
||||
CONTAINER_NAME: "dxflrs/arm64_garage"
|
||||
HOME: "/kaniko"
|
||||
commands:
|
||||
- mkdir -p /kaniko/.docker
|
||||
- echo $DOCKER_AUTH > /kaniko/.docker/config.json
|
||||
- export CONTAINER_TAG=${DRONE_TAG:-$DRONE_COMMIT}
|
||||
- nix-shell --arg rust false --arg integration false --run "to_docker"
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: release-linux-armv6l
|
||||
|
||||
volumes:
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
- name: nix_config
|
||||
temp: {}
|
||||
|
||||
environment:
|
||||
TARGET: armv6l-unknown-linux-musleabihf
|
||||
|
||||
steps:
|
||||
- name: setup nix
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-build --no-build-output --no-out-link --arg rust false --arg integration false -A inputDerivation
|
||||
|
||||
- name: build
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
commands:
|
||||
- nix-build --no-build-output --argstr target $TARGET --arg release true --argstr git_version $DRONE_COMMIT
|
||||
|
||||
- name: push static binary
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: garagehq_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: garagehq_aws_secret_access_key
|
||||
commands:
|
||||
- nix-shell --arg integration false --arg rust false --run "to_s3"
|
||||
|
||||
- name: docker build and publish
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
- name: nix_config
|
||||
path: /etc/nix
|
||||
environment:
|
||||
DOCKER_AUTH:
|
||||
from_secret: docker_auth
|
||||
DOCKER_PLATFORM: "linux/arm"
|
||||
CONTAINER_NAME: "dxflrs/arm_garage"
|
||||
HOME: "/kaniko"
|
||||
commands:
|
||||
- mkdir -p /kaniko/.docker
|
||||
- echo $DOCKER_AUTH > /kaniko/.docker/config.json
|
||||
- export CONTAINER_TAG=${DRONE_TAG:-$DRONE_COMMIT}
|
||||
- nix-shell --arg rust false --arg integration false --run "to_docker"
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: refresh-release-page
|
||||
|
||||
volumes:
|
||||
- name: nix_store
|
||||
host:
|
||||
path: /var/lib/drone/nix
|
||||
|
||||
steps:
|
||||
- name: refresh-index
|
||||
image: nixpkgs/nix:nixos-21.05
|
||||
volumes:
|
||||
- name: nix_store
|
||||
path: /nix
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID:
|
||||
from_secret: garagehq_aws_access_key_id
|
||||
AWS_SECRET_ACCESS_KEY:
|
||||
from_secret: garagehq_aws_secret_access_key
|
||||
commands:
|
||||
- mkdir -p /etc/nix && cp nix/nix.conf /etc/nix/nix.conf
|
||||
- nix-shell --arg integration false --arg rust false --run "refresh_index"
|
||||
|
||||
depends_on:
|
||||
- release-linux-x86_64
|
||||
- release-linux-i686
|
||||
- release-linux-aarch64
|
||||
- release-linux-armv6l
|
||||
|
||||
trigger:
|
||||
event:
|
||||
- promote
|
||||
- cron
|
||||
|
||||
node:
|
||||
nix: 1
|
||||
|
||||
---
|
||||
kind: signature
|
||||
hmac: e919f8a66d20ebfeeec56b291a8a0fdd59a482601da987fcf533d96d24768744
|
||||
hmac: 1c33490cc2902564c4250a409c156683d0d549b8c9d5aee4e46d1bde4e0ccf2c
|
||||
|
||||
...
|
||||
|
||||
Generated
+372
-491
File diff suppressed because it is too large
Load Diff
+3
-6
@@ -1,10 +1,7 @@
|
||||
FROM archlinux:latest
|
||||
FROM scratch
|
||||
|
||||
RUN mkdir -p /garage/meta
|
||||
RUN mkdir -p /garage/data
|
||||
ENV RUST_BACKTRACE=1
|
||||
ENV RUST_LOG=garage=info
|
||||
|
||||
COPY target/release/garage.stripped /garage/garage
|
||||
|
||||
CMD /garage/garage server -c /garage/config.toml
|
||||
COPY result/bin/garage /
|
||||
CMD [ "/garage", "server"]
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
.PHONY: doc all release shell
|
||||
|
||||
all:
|
||||
clear; cargo build
|
||||
|
||||
doc:
|
||||
cd doc/book; mdbook build
|
||||
|
||||
release:
|
||||
RUSTFLAGS="-C link-arg=-fuse-ld=lld -C target-cpu=x86-64 -C target-feature=+sse2" cargo build --release --no-default-features
|
||||
nix-build --arg release true
|
||||
|
||||
shell:
|
||||
nix-shell
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
{
|
||||
system ? builtins.currentSystem,
|
||||
release ? false,
|
||||
target ? "x86_64-unknown-linux-musl",
|
||||
compileMode ? null,
|
||||
git_version ? null,
|
||||
}:
|
||||
|
||||
with import ./nix/common.nix;
|
||||
|
||||
let
|
||||
crossSystem = { config = target; };
|
||||
in let
|
||||
pkgs = import pkgsSrc {
|
||||
inherit system crossSystem;
|
||||
overlays = [ cargo2nixOverlay ];
|
||||
};
|
||||
|
||||
/*
|
||||
The following complexity should be abstracted by makePackageSet' (note the final quote).
|
||||
However its code uses deprecated features of rust-overlay that can lead to bug.
|
||||
Instead, we build our own rustChannel object with the recommended API of rust-overlay.
|
||||
*/
|
||||
rustChannel = pkgs.rustPlatform.rust;
|
||||
|
||||
overrides = pkgs.buildPackages.rustBuilder.overrides.all ++ [
|
||||
(pkgs.rustBuilder.rustLib.makeOverride {
|
||||
name = "garage";
|
||||
overrideAttrs = drv: if git_version != null then {
|
||||
preConfigure = ''
|
||||
${drv.preConfigure or ""}
|
||||
export GIT_VERSION="${git_version}"
|
||||
'';
|
||||
} else {};
|
||||
})
|
||||
];
|
||||
|
||||
packageFun = import ./Cargo.nix;
|
||||
|
||||
rustPkgs = pkgs.rustBuilder.makePackageSet {
|
||||
inherit packageFun rustChannel release;
|
||||
packageOverrides = overrides;
|
||||
|
||||
buildRustPackages = pkgs.buildPackages.rustBuilder.makePackageSet {
|
||||
inherit rustChannel packageFun;
|
||||
packageOverrides = overrides;
|
||||
};
|
||||
|
||||
localPatterns = [
|
||||
/*
|
||||
The way the default rules are written make think we match recursively, on full path, but the rules are misleading.
|
||||
In fact, the regex is only called on root elements of the crate (and not recursively).
|
||||
This behavior does not work well with our nested modules.
|
||||
We tried to build a "deny list" but negative lookup ahead are not supported on Nix.
|
||||
As a workaround, we have to register all our submodules in this allow list...
|
||||
*/
|
||||
''^(src|tests)'' # fixed default
|
||||
''.*\.(rs|toml)$'' # fixed default
|
||||
''^(crdt|replication|cli)'' # our crate submodules
|
||||
];
|
||||
};
|
||||
|
||||
in
|
||||
if compileMode == "test"
|
||||
then builtins.mapAttrs (name: value: rustPkgs.workspace.${name} { inherit compileMode; }) rustPkgs.workspace
|
||||
else rustPkgs.workspace.garage { inherit compileMode; }
|
||||
+18
-8
@@ -5,14 +5,21 @@
|
||||
- [Quick start](./quick_start/index.md)
|
||||
|
||||
- [Cookbook](./cookbook/index.md)
|
||||
- [Deploying Garage](./cookbook/real_world.md)
|
||||
- [Configuring S3 clients](./cookbook/clients.md)
|
||||
- [Hosting a website](./cookbook/website.md)
|
||||
- [Recovering from failures](./cookbook/recovering.md)
|
||||
- [Building from source](./cookbook/from_source.md)
|
||||
- [Starting with Systemd](./cookbook/systemd.md)
|
||||
- [Integrate as a media backend]()
|
||||
- [Operate a cluster]()
|
||||
- [Integration with systemd](./cookbook/systemd.md)
|
||||
- [Gateways](./cookbook/gateways.md)
|
||||
- [Exposing buckets as websites](./cookbook/exposing_websites.md)
|
||||
- [Configuring a reverse proxy](./cookbook/reverse_proxy.md)
|
||||
- [Production Deployment](./cookbook/real_world.md)
|
||||
- [Recovering from failures](./cookbook/recovering.md)
|
||||
|
||||
- [Integrations](./connect/index.md)
|
||||
- [Apps (Nextcloud, Peertube...)](./connect/apps.md)
|
||||
- [Websites (Hugo, Jekyll, Publii...)](./connect/websites.md)
|
||||
- [Repositories (Docker, Nix...)](./connect/repositories.md)
|
||||
- [CLI tools (rclone, awscli, mc...)](./connect/cli.md)
|
||||
- [Your code (PHP, JS, Go...)](./connect/code.md)
|
||||
|
||||
|
||||
- [Reference Manual](./reference_manual/index.md)
|
||||
- [Garage configuration file](./reference_manual/configuration.md)
|
||||
@@ -22,10 +29,13 @@
|
||||
- [Design](./design/index.md)
|
||||
- [Related Work](./design/related_work.md)
|
||||
- [Internals](./design/internals.md)
|
||||
- [Design draft](./design/design_draft.md)
|
||||
|
||||
- [Development](./development/index.md)
|
||||
- [Setup your environment](./development/devenv.md)
|
||||
- [Your first contribution]()
|
||||
- [Development scripts](./development/scripts.md)
|
||||
- [Release process](./development/release_process.md)
|
||||
|
||||
- [Working Documents](./working_documents/index.md)
|
||||
- [Load Balancing Data](./working_documents/load_balancing.md)
|
||||
- [Migrating from 0.3 to 0.4](./working_documents/migration_04.md)
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
# Apps (Nextcloud, Peertube...)
|
||||
|
||||
In this section, we cover the following software: [Nextcloud](#nextcloud), [Peertube](#peertube), [Mastodon](#mastodon), [Matrix](#matrix)
|
||||
|
||||
## Nextcloud
|
||||
|
||||
Nextcloud is a popular file synchronisation and backup service.
|
||||
By default, Nextcloud stores its data on the local filesystem.
|
||||
If you want to expand your storage to aggregate multiple servers, Garage is the way to go.
|
||||
|
||||
A S3 backend can be configured in two ways on Nextcloud, either as Primary Storage or as an External Storage.
|
||||
Primary storage will store all your data on S3, in an opaque manner, and will provide the best performances.
|
||||
External storage enable you to select which data will be stored on S3, your file hierarchy will be preserved in S3, but it might be slower.
|
||||
|
||||
In the following, we cover both methods but before reading our guide, we suppose you have done some preliminary steps.
|
||||
First, we expect you have an already installed and configured Nextcloud instance.
|
||||
Second, we suppose you have created a key and a bucket.
|
||||
|
||||
As a reminder, you can create a key for your nextcloud instance as follow:
|
||||
|
||||
```bash
|
||||
garage key new --name nextcloud-key
|
||||
```
|
||||
|
||||
Keep the Key ID and the Secret key in a pad, they will be needed later.
|
||||
Then you can create a bucket and give read/write rights to your key on this bucket with:
|
||||
|
||||
```bash
|
||||
garage bucket create nextcloud
|
||||
garage bucket allow nextcloud --read --write --key nextcloud-key
|
||||
```
|
||||
|
||||
|
||||
### Primary Storage
|
||||
|
||||
Now edit your Nextcloud configuration file to enable object storage.
|
||||
On my installation, the config. file is located at the following path: `/var/www/nextcloud/config/config.php`.
|
||||
We will add a new root key to the `$CONFIG` dictionnary named `objectstore`:
|
||||
|
||||
```php
|
||||
<?php
|
||||
$CONFIG = array(
|
||||
/* your existing configuration */
|
||||
'objectstore' => [
|
||||
'class' => '\\OC\\Files\\ObjectStore\\S3',
|
||||
'arguments' => [
|
||||
'bucket' => 'nextcloud', // Your bucket name, must be created before
|
||||
'autocreate' => false, // Garage does not support autocreate
|
||||
'key' => 'xxxxxxxxx', // The Key ID generated previously
|
||||
'secret' => 'xxxxxxxxx', // The Secret key generated previously
|
||||
'hostname' => '127.0.0.1', // Can also be a domain name, eg. garage.example.com
|
||||
'port' => 3900, // Put your reverse proxy port or your S3 API port
|
||||
'use_ssl' => false, // Set it to true if you have a TLS enabled reverse proxy
|
||||
'region' => 'garage', // Garage has only one region named "garage"
|
||||
'use_path_style' => true // Garage supports only path style, must be set to true
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
That's all, your Nextcloud will store all your data to S3.
|
||||
To test your new configuration, just reload your Nextcloud webpage and start sending data.
|
||||
|
||||
*External link:* [Nextcloud Documentation > Primary Storage](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/primary_storage.html)
|
||||
|
||||
### External Storage
|
||||
|
||||
**From the GUI.** Activate the "External storage support" app from the "Applications" page (click on your account icon on the top right corner of your screen to display the menu). Go to your parameters page (also located below your account icon). Click on external storage (or the corresponding translation in your language).
|
||||
|
||||
[](./cli-nextcloud-gui.png)
|
||||
*Click on the picture to zoom*
|
||||
|
||||
Add a new external storage. Put what you want in "folder name" (eg. "shared"). Select "Amazon S3". Keep "Access Key" for the Authentication field.
|
||||
In Configuration, put your bucket name (eg. nextcloud), the host (eg. 127.0.0.1), the port (eg. 3900 or 443), the region (garage). Tick the SSL box if you have put an HTTPS proxy in front of garage. You must tick the "Path access" box and you must leave the "Legacy authentication (v2)" box empty. Put your Key ID (eg. GK...) and your Secret Key in the last two input boxes. Finally click on the tick symbol on the right of your screen.
|
||||
|
||||
Now go to your "Files" app and a new "linked folder" has appeared with the name you chose earlier (eg. "shared").
|
||||
|
||||
*External link:* [Nextcloud Documentation > External Storage Configuration GUI](https://docs.nextcloud.com/server/latest/admin_manual/configuration_files/external_storage_configuration_gui.html)
|
||||
|
||||
**From the CLI.** First install the external storage application:
|
||||
|
||||
```bash
|
||||
php occ app:install files_external
|
||||
```
|
||||
|
||||
Then add a new mount point with:
|
||||
|
||||
```bash
|
||||
php occ files_external:create \
|
||||
-c bucket=nextcloud \
|
||||
-c hostname=127.0.0.1 \
|
||||
-c port=3900 \
|
||||
-c region=garage \
|
||||
-c use_ssl=false \
|
||||
-c use_path_style=true \
|
||||
-c legacy_auth=false \
|
||||
-c key=GKxxxx \
|
||||
-c secret=xxxx \
|
||||
shared amazons3 amazons3::accesskey
|
||||
```
|
||||
|
||||
Adapt the `hostname`, `port`, `use_ssl`, `key`, and `secret` entries to your configuration.
|
||||
Do not change the `use_path_style` and `legacy_auth` entries, other configurations are not supported.
|
||||
|
||||
*External link:* [Nextcloud Documentation > occ command > files external](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/occ_command.html#files-external-label)
|
||||
|
||||
|
||||
## Peertube
|
||||
|
||||
Peertube proposes a clever integration of S3 by directly exposing its endpoint instead of proxifying requests through the application.
|
||||
In other words, Peertube is only responsible of the "control plane" and offload the "data plane" to Garage.
|
||||
In return, this system is a bit harder to configure, especially with Garage that supports less feature than other older S3 backends.
|
||||
We show that it is still possible to configure Garage with Peertube, allowing you to spread the load and the bandiwdth usage on the Garage cluster.
|
||||
|
||||
### Enable path-style access by patching Peertube
|
||||
|
||||
First, you will need to apply a small patch on Peertube ([#4510](https://github.com/Chocobozzz/PeerTube/pull/4510)):
|
||||
|
||||
```diff
|
||||
From e3b4c641bdf67e07d406a1d49d6aa6b1fbce2ab4 Mon Sep 17 00:00:00 2001
|
||||
From: Martin Honermeyer <maze@strahlungsfrei.de>
|
||||
Date: Sun, 31 Oct 2021 12:34:04 +0100
|
||||
Subject: [PATCH] Allow setting path-style access for object storage
|
||||
|
||||
---
|
||||
config/default.yaml | 4 ++++
|
||||
config/production.yaml.example | 4 ++++
|
||||
server/initializers/config.ts | 1 +
|
||||
server/lib/object-storage/shared/client.ts | 3 ++-
|
||||
.../production/config/custom-environment-variables.yaml | 2 ++
|
||||
5 files changed, 13 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/config/default.yaml b/config/default.yaml
|
||||
index cf9d69a6211..4efd56fb804 100644
|
||||
--- a/config/default.yaml
|
||||
+++ b/config/default.yaml
|
||||
@@ -123,6 +123,10 @@ object_storage:
|
||||
# You can also use AWS_SECRET_ACCESS_KEY env variable
|
||||
secret_access_key: ''
|
||||
|
||||
+ # Reference buckets via path rather than subdomain
|
||||
+ # (i.e. "my-endpoint.com/bucket" instead of "bucket.my-endpoint.com")
|
||||
+ force_path_style: false
|
||||
+
|
||||
# Maximum amount to upload in one request to object storage
|
||||
max_upload_part: 2GB
|
||||
|
||||
diff --git a/config/production.yaml.example b/config/production.yaml.example
|
||||
index 70993bf57a3..9ca2de5f4c9 100644
|
||||
--- a/config/production.yaml.example
|
||||
+++ b/config/production.yaml.example
|
||||
@@ -121,6 +121,10 @@ object_storage:
|
||||
# You can also use AWS_SECRET_ACCESS_KEY env variable
|
||||
secret_access_key: ''
|
||||
|
||||
+ # Reference buckets via path rather than subdomain
|
||||
+ # (i.e. "my-endpoint.com/bucket" instead of "bucket.my-endpoint.com")
|
||||
+ force_path_style: false
|
||||
+
|
||||
# Maximum amount to upload in one request to object storage
|
||||
max_upload_part: 2GB
|
||||
|
||||
diff --git a/server/initializers/config.ts b/server/initializers/config.ts
|
||||
index 8375bf4304c..d726c59a4b6 100644
|
||||
--- a/server/initializers/config.ts
|
||||
+++ b/server/initializers/config.ts
|
||||
@@ -91,6 +91,7 @@ const CONFIG = {
|
||||
ACCESS_KEY_ID: config.get<string>('object_storage.credentials.access_key_id'),
|
||||
SECRET_ACCESS_KEY: config.get<string>('object_storage.credentials.secret_access_key')
|
||||
},
|
||||
+ FORCE_PATH_STYLE: config.get<boolean>('object_storage.force_path_style'),
|
||||
VIDEOS: {
|
||||
BUCKET_NAME: config.get<string>('object_storage.videos.bucket_name'),
|
||||
PREFIX: config.get<string>('object_storage.videos.prefix'),
|
||||
diff --git a/server/lib/object-storage/shared/client.ts b/server/lib/object-storage/shared/client.ts
|
||||
index c9a61459336..eadad02f93f 100644
|
||||
--- a/server/lib/object-storage/shared/client.ts
|
||||
+++ b/server/lib/object-storage/shared/client.ts
|
||||
@@ -26,7 +26,8 @@ function getClient () {
|
||||
accessKeyId: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID,
|
||||
secretAccessKey: OBJECT_STORAGE.CREDENTIALS.SECRET_ACCESS_KEY
|
||||
}
|
||||
- : undefined
|
||||
+ : undefined,
|
||||
+ forcePathStyle: CONFIG.OBJECT_STORAGE.FORCE_PATH_STYLE
|
||||
})
|
||||
|
||||
logger.info('Initialized S3 client %s with region %s.', getEndpoint(), OBJECT_STORAGE.REGION, lTags())
|
||||
diff --git a/support/docker/production/config/custom-environment-variables.yaml b/support/docker/production/config/custom-environment-variables.yaml
|
||||
index c7cd28e6521..a960bab0bc9 100644
|
||||
--- a/support/docker/production/config/custom-environment-variables.yaml
|
||||
+++ b/support/docker/production/config/custom-environment-variables.yaml
|
||||
@@ -54,6 +54,8 @@ object_storage:
|
||||
|
||||
region: "PEERTUBE_OBJECT_STORAGE_REGION"
|
||||
|
||||
+ force_path_style: "PEERTUBE_OBJECT_STORAGE_FORCE_PATH_STYLE"
|
||||
+
|
||||
max_upload_part:
|
||||
__name: "PEERTUBE_OBJECT_STORAGE_MAX_UPLOAD_PART"
|
||||
__format: "json"
|
||||
```
|
||||
|
||||
You can then recompile it with:
|
||||
|
||||
```
|
||||
npm run build
|
||||
```
|
||||
|
||||
And it can be started with:
|
||||
|
||||
```
|
||||
NODE_ENV=production NODE_CONFIG_DIR=/srv/peertube/config node dist/server.js
|
||||
```
|
||||
|
||||
|
||||
### Create resources in Garage
|
||||
|
||||
Create a key for Peertube:
|
||||
|
||||
```bash
|
||||
garage key new --name peertube-key
|
||||
```
|
||||
|
||||
Keep the Key ID and the Secret key in a pad, they will be needed later.
|
||||
|
||||
We need two buckets, one for normal videos (named peertube-video) and one for webtorrent videos (named peertube-playlist).
|
||||
```bash
|
||||
garage bucket create peertube-video
|
||||
garage bucket create peertube-playlist
|
||||
```
|
||||
|
||||
Now we allow our key to read and write on these buckets:
|
||||
|
||||
```
|
||||
garage bucket allow peertube-playlist --read --write --key peertube-key
|
||||
garage bucket allow peertube-video --read --write --key peertube-key
|
||||
```
|
||||
|
||||
Finally, we need to expose these buckets publicly to serve their content to users:
|
||||
|
||||
```bash
|
||||
garage bucket website --allow peertube-playlist
|
||||
garage bucket website --allow peertube-video
|
||||
```
|
||||
|
||||
These buckets are now accessible on the web port (by default 3902) with the following URL: `http://<bucket><root_domain>:<web_port>` where the root domain is defined in your configuration file (by default `.web.garage`). So we have currently the following URLs:
|
||||
* http://peertube-playlist.web.garage:3902
|
||||
* http://peertube-video.web.garage:3902
|
||||
|
||||
Make sure you (will) have a corresponding DNS entry for them.
|
||||
|
||||
### Configure a Reverse Proxy to serve CORS
|
||||
|
||||
Now we will configure a reverse proxy in front of Garage.
|
||||
This is required as we have no other way to serve CORS headers yet.
|
||||
Check the [Configuring a reverse proxy](/cookbook/reverse_proxy.html) section to know how.
|
||||
|
||||
Now make sure that your 2 dns entries are pointing to your reverse proxy.
|
||||
|
||||
### Configure Peertube
|
||||
|
||||
You must edit the file named `config/production.yaml`, we are only modifying the root key named `object_storage`:
|
||||
|
||||
```yaml
|
||||
object_storage:
|
||||
enabled: true
|
||||
|
||||
# Put localhost only if you have a garage instance running on that node
|
||||
endpoint: 'http://localhost:3900' # or "garage.example.com" if you have TLS on port 443
|
||||
|
||||
# This entry has been added by our patch, must be set to true
|
||||
force_path_style: true
|
||||
|
||||
# Garage supports only one region for now, named garage
|
||||
region: 'garage'
|
||||
|
||||
credentials:
|
||||
access_key_id: 'GKxxxx'
|
||||
secret_access_key: 'xxxx'
|
||||
|
||||
max_upload_part: 2GB
|
||||
|
||||
streaming_playlists:
|
||||
bucket_name: 'peertube-playlist'
|
||||
|
||||
# Keep it empty for our example
|
||||
prefix: ''
|
||||
|
||||
# You must fill this field to make Peertube use our reverse proxy/website logic
|
||||
base_url: 'http://peertube-playlist.web.garage' # Example: 'https://mirror.example.com'
|
||||
|
||||
# Same settings but for webtorrent videos
|
||||
videos:
|
||||
bucket_name: 'peertube-video'
|
||||
prefix: ''
|
||||
# You must fill this field to make Peertube use our reverse proxy/website logic
|
||||
base_url: 'http://peertube-video.web.garage'
|
||||
```
|
||||
|
||||
### That's all
|
||||
|
||||
Everything must be configured now, simply restart Peertube and try to upload a video.
|
||||
You must see in your browser console that data are fetched directly from our bucket (through the reverse proxy).
|
||||
|
||||
### Miscellaneous
|
||||
|
||||
*Known bug:* The playback does not start and some 400 Bad Request Errors appear in your browser console and on Garage.
|
||||
If the description of the error contains HTTP Invalid Range: InvalidRange, the error is due to a buggy ffmpeg version.
|
||||
You must avoid the 4.4.0 and use either a newer or older version.
|
||||
|
||||
*Associated issues:* [#137](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/137), [#138](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/138), [#140](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/140). These issues are non blocking.
|
||||
|
||||
*External link:* [Peertube Documentation > Remote Storage](https://docs.joinpeertube.org/admin-remote-storage)
|
||||
|
||||
## Mastodon
|
||||
|
||||
https://docs.joinmastodon.org/admin/config/#cdn
|
||||
|
||||
## Matrix
|
||||
|
||||
Matrix is a chat communication protocol. Its main stable server implementation, [Synapse](https://matrix-org.github.io/synapse/latest/), provides a module to store media on a S3 backend. Additionally, a server independent media store supporting S3 has been developped by the community, it has been made possible thanks to how the matrix API has been designed and will work with implementations like Conduit, Dendrite, etc.
|
||||
|
||||
### synapse-s3-storage-provider (synapse only)
|
||||
|
||||
Supposing you have a working synapse installation, you can add the module with pip:
|
||||
|
||||
```bash
|
||||
pip3 install --user git+https://github.com/matrix-org/synapse-s3-storage-provider.git
|
||||
```
|
||||
|
||||
Now create a bucket and a key for your matrix instance (note your Key ID and Secret Key somewhere, they will be needed later):
|
||||
|
||||
```bash
|
||||
garage key new --name matrix-key
|
||||
garage bucket create matrix
|
||||
garage bucket allow matrix --read --write --key matrix-key
|
||||
```
|
||||
|
||||
Then you must edit your server configuration (eg. `/etc/matrix-synapse/homeserver.yaml`) and add the `media_storage_providers` root key:
|
||||
|
||||
```yaml
|
||||
media_storage_providers:
|
||||
- module: s3_storage_provider.S3StorageProviderBackend
|
||||
store_local: True # do we want to store on S3 media created by our users?
|
||||
store_remote: True # do we want to store on S3 media created
|
||||
# by users of others servers federated to ours?
|
||||
store_synchronous: True # do we want to wait that the file has been written before returning?
|
||||
config:
|
||||
bucket: matrix # the name of our bucket, we chose matrix earlier
|
||||
region_name: garage # only "garage" is supported for the region field
|
||||
endpoint_url: http://localhost:3900 # the path to the S3 endpoint
|
||||
access_key_id: "GKxxx" # your Key ID
|
||||
secret_access_key: "xxxx" # your Secret Key
|
||||
```
|
||||
|
||||
Note that uploaded media will also be stored locally and this behavior can not be deactivated, it is even required for
|
||||
some operations like resizing images.
|
||||
In fact, your local filesysem is considered as a cache but without any automated way to garbage collect it.
|
||||
|
||||
We can build our garbage collector with `s3_media_upload`, a tool provided with the module.
|
||||
If you installed the module with the command provided before, you should be able to bring it in your path:
|
||||
|
||||
```
|
||||
PATH=$HOME/.local/bin/:$PATH
|
||||
command -v s3_media_upload
|
||||
```
|
||||
|
||||
Now we can write a simple script (eg `~/.local/bin/matrix-cache-gc`):
|
||||
|
||||
```bash
|
||||
#!/bin/bash
|
||||
|
||||
## CONFIGURATION ##
|
||||
AWS_ACCESS_KEY_ID=GKxxx
|
||||
AWS_SECRET_ACCESS_KEY=xxxx
|
||||
S3_ENDPOINT=http://localhost:3900
|
||||
S3_BUCKET=matrix
|
||||
MEDIA_STORE=/var/lib/matrix-synapse/media
|
||||
PG_USER=matrix
|
||||
PG_PASS=xxxx
|
||||
PG_DB=synapse
|
||||
PG_HOST=localhost
|
||||
PG_PORT=5432
|
||||
|
||||
## CODE ##
|
||||
PATH=$HOME/.local/bin/:$PATH
|
||||
cat > database.yaml <<EOF
|
||||
user: $PG_USER
|
||||
password: $PG_PASS
|
||||
database: $PG_DB
|
||||
host: $PG_HOST
|
||||
port: $PG_PORT
|
||||
EOF
|
||||
|
||||
s3_media_upload update-db 1d
|
||||
s3_media_upload --no-progress check-deleted $MEDIA_STORE
|
||||
s3_media_upload --no-progress upload $MEDIA_STORE $S3_BUCKET --delete --endpoint-url $S3_ENDPOINT
|
||||
```
|
||||
|
||||
This script will list all the medias that were not accessed in the 24 hours according to your database.
|
||||
It will check if, in this list, the file still exists in the local media store.
|
||||
For files that are still in the cache, it will upload them to S3 if they are not already present (in case of a crash or an initial synchronisation).
|
||||
Finally, the script will delete these files from the cache.
|
||||
|
||||
Make this script executable and check that it works:
|
||||
|
||||
```bash
|
||||
chmod +x $HOME/.local/bin/matrix-cache-gc
|
||||
matrix-cache-gc
|
||||
```
|
||||
|
||||
Add it to your crontab. Open the editor with:
|
||||
|
||||
```bash
|
||||
crontab -e
|
||||
```
|
||||
|
||||
And add a new line. For example, to run it every 10 minutes:
|
||||
|
||||
```cron
|
||||
*/10 * * * * $HOME/.local/bin/matrix-cache-gc
|
||||
```
|
||||
|
||||
*External link:* [Github > matrix-org/synapse-s3-storage-provider](https://github.com/matrix-org/synapse-s3-storage-provider)
|
||||
|
||||
### matrix-media-repo (server independent)
|
||||
|
||||
*External link:* [matrix-media-repo Documentation > S3](https://docs.t2bot.io/matrix-media-repo/configuration/s3-datastore.html)
|
||||
|
||||
## Pixelfed
|
||||
|
||||
https://docs.pixelfed.org/technical-documentation/env.html#filesystem
|
||||
|
||||
## Pleroma
|
||||
|
||||
https://docs-develop.pleroma.social/backend/configuration/cheatsheet/#pleromauploaderss3
|
||||
|
||||
## Lemmy
|
||||
|
||||
via pict-rs
|
||||
https://git.asonix.dog/asonix/pict-rs/commit/f9f4fc63d670f357c93f24147c2ee3e1278e2d97
|
||||
|
||||
## Funkwhale
|
||||
|
||||
https://docs.funkwhale.audio/admin/configuration.html#s3-storage
|
||||
|
||||
## Misskey
|
||||
|
||||
https://github.com/misskey-dev/misskey/commit/9d944243a3a59e8880a360cbfe30fd5a3ec8d52d
|
||||
|
||||
## Prismo
|
||||
|
||||
https://gitlab.com/prismosuite/prismo/-/blob/dev/.env.production.sample#L26-33
|
||||
|
||||
## Owncloud Infinite Scale (ocis)
|
||||
|
||||
## Unsupported
|
||||
|
||||
- Mobilizon: No S3 integration
|
||||
- WriteFreely: No S3 integration
|
||||
- Plume: No S3 integration
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 197 KiB |
@@ -0,0 +1,127 @@
|
||||
# CLI tools
|
||||
|
||||
CLI tools allow you to query the S3 API without too many abstractions.
|
||||
These tools are particularly suitable for debug, backups, website deployments or any scripted task that need to handle data.
|
||||
|
||||
## Minio client (recommended)
|
||||
|
||||
Use the following command to set an "alias", i.e. define a new S3 server to be
|
||||
used by the Minio client:
|
||||
|
||||
```bash
|
||||
mc alias set \
|
||||
garage \
|
||||
<endpoint> \
|
||||
<access key> \
|
||||
<secret key> \
|
||||
--api S3v4
|
||||
```
|
||||
|
||||
Remember that `mc` is sometimes called `mcli` (such as on Arch Linux), to avoid conflicts
|
||||
with Midnight Commander.
|
||||
|
||||
Some commands:
|
||||
|
||||
```bash
|
||||
# list buckets
|
||||
mc ls garage/
|
||||
|
||||
# list objets in a bucket
|
||||
mc ls garage/my_files
|
||||
|
||||
# copy from your filesystem to garage
|
||||
mc cp /proc/cpuinfo garage/my_files/cpuinfo.txt
|
||||
|
||||
# copy from garage to your filesystem
|
||||
mc cp garage/my_files/cpuinfo.txt /tmp/cpuinfo.txt
|
||||
|
||||
# mirror a folder from your filesystem to garage
|
||||
mc mirror --overwrite ./book garage/garagehq.deuxfleurs.fr
|
||||
```
|
||||
|
||||
|
||||
## AWS CLI
|
||||
|
||||
Create a file named `~/.aws/credentials` and put:
|
||||
|
||||
```toml
|
||||
[default]
|
||||
aws_access_key_id=xxxx
|
||||
aws_secret_access_key=xxxx
|
||||
```
|
||||
|
||||
Then a file named `~/.aws/config` and put:
|
||||
|
||||
```toml
|
||||
[default]
|
||||
region=garage
|
||||
```
|
||||
|
||||
Now, supposing Garage is listening on `http://127.0.0.1:3900`, you can list your buckets with:
|
||||
|
||||
```bash
|
||||
aws --endpoint-url http://127.0.0.1:3900 s3 ls
|
||||
```
|
||||
|
||||
Passing the `--endpoint-url` parameter to each command is annoying but AWS developers do not provide a corresponding configuration entry.
|
||||
As a workaround, you can redefine the aws command by editing the file `~/.bashrc`:
|
||||
|
||||
```
|
||||
function aws { command aws --endpoint-url http://127.0.0.1:3900 $@ ; }
|
||||
```
|
||||
|
||||
*Do not forget to run `source ~/.bashrc` or to start a new terminal before running the next commands.*
|
||||
|
||||
Now you can simply run:
|
||||
|
||||
```bash
|
||||
# list buckets
|
||||
aws s3 ls
|
||||
|
||||
# list objects of a bucket
|
||||
aws s3 ls s3://my_files
|
||||
|
||||
# copy from your filesystem to garage
|
||||
aws s3 cp /proc/cpuinfo s3://my_files/cpuinfo.txt
|
||||
|
||||
# copy from garage to your filesystem
|
||||
aws s3 cp s3/my_files/cpuinfo.txt /tmp/cpuinfo.txt
|
||||
```
|
||||
|
||||
## `rclone`
|
||||
|
||||
`rclone` can be configured using the interactive assistant invoked using `rclone configure`.
|
||||
|
||||
You can also configure `rclone` by writing directly its configuration file.
|
||||
Here is a template `rclone.ini` configuration file:
|
||||
|
||||
```ini
|
||||
[garage]
|
||||
type = s3
|
||||
provider = Other
|
||||
env_auth = false
|
||||
access_key_id = <access key>
|
||||
secret_access_key = <secret key>
|
||||
region = <region>
|
||||
endpoint = <endpoint>
|
||||
force_path_style = true
|
||||
acl = private
|
||||
bucket_acl = private
|
||||
```
|
||||
|
||||
## Cyberduck
|
||||
|
||||
TODO
|
||||
|
||||
## `s3cmd`
|
||||
|
||||
Here is a template for the `s3cmd.cfg` file to talk with Garage:
|
||||
|
||||
```ini
|
||||
[default]
|
||||
access_key = <access key>
|
||||
secret_key = <secret key>
|
||||
host_base = <endpoint without http(s)://>
|
||||
host_bucket = <same as host_base>
|
||||
use_https = False | True
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
# Your code (PHP, JS, Go...)
|
||||
@@ -1,4 +1,4 @@
|
||||
# Configuring S3 clients to interact with Garage
|
||||
# Connect it to
|
||||
|
||||
To configure an S3 client to interact with Garage, you will need the following
|
||||
parameters:
|
||||
@@ -28,78 +28,11 @@ provided that you follow the following guidelines:
|
||||
Garage should normally redirect your client to the correct region,
|
||||
but in case your client does not support this you might have to configure it manually.
|
||||
|
||||
We will now provide example configurations for the most common S3 clients.
|
||||
We will now provide example configurations for the most common clients per category:
|
||||
|
||||
## AWS CLI
|
||||
- [Apps](./apps.md)
|
||||
- [Websites](./websites.md)
|
||||
- [Repositories](./repositories.md)
|
||||
- [CLI tools](./cli.md)
|
||||
- [Your code](./code.md)
|
||||
|
||||
Export the following environment variables:
|
||||
|
||||
```bash
|
||||
export AWS_ACCESS_KEY_ID=<access key>
|
||||
export AWS_SECRET_ACCESS_KEY=<secret key>
|
||||
export AWS_DEFAULT_REGION=<region>
|
||||
```
|
||||
|
||||
Now invoke `aws` as follows:
|
||||
|
||||
```bash
|
||||
aws --endpoint-url <endpoint> s3 <command...>
|
||||
```
|
||||
|
||||
For instance: `aws --endpoint-url http://127.0.0.1:3901 s3 ls s3://my-bucket/`.
|
||||
|
||||
## Minio client
|
||||
|
||||
Use the following command to set an "alias", i.e. define a new S3 server to be
|
||||
used by the Minio client:
|
||||
|
||||
```bash
|
||||
mc alias set \
|
||||
garage \
|
||||
<endpoint> \
|
||||
<access key> \
|
||||
<secret key> \
|
||||
--api S3v4
|
||||
```
|
||||
|
||||
Remember that `mc` is sometimes called `mcli` (such as on Arch Linux), to avoid conflicts
|
||||
with the Midnight Commander.
|
||||
|
||||
|
||||
## `rclone`
|
||||
|
||||
`rclone` can be configured using the interactive assistant invoked using `rclone configure`.
|
||||
|
||||
You can also configure `rclone` by writing directly its configuration file.
|
||||
Here is a template `rclone.ini` configuration file:
|
||||
|
||||
```ini
|
||||
[garage]
|
||||
type = s3
|
||||
provider = Other
|
||||
env_auth = false
|
||||
access_key_id = <access key>
|
||||
secret_access_key = <secret key>
|
||||
region = <region>
|
||||
endpoint = <endpoint>
|
||||
force_path_style = true
|
||||
acl = private
|
||||
bucket_acl = private
|
||||
```
|
||||
|
||||
## Cyberduck
|
||||
|
||||
TODO
|
||||
|
||||
## `s3cmd`
|
||||
|
||||
Here is a template for the `s3cmd.cfg` file to talk with Garage:
|
||||
|
||||
```ini
|
||||
[default]
|
||||
access_key = <access key>
|
||||
secret_key = <secret key>
|
||||
host_base = <endpoint without http(s)://>
|
||||
host_bucket = <same as host_base>
|
||||
use_https = False | True
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
# Repositories (Docker, Nix...)
|
||||
@@ -0,0 +1,77 @@
|
||||
# Websites (Hugo, Jekyll, Publii...)
|
||||
|
||||
Garage is also suitable to host static websites.
|
||||
While they can be deployed with traditional CLI tools, some static website generators have integrated options to ease your workflow.
|
||||
|
||||
## Hugo
|
||||
|
||||
Add to your `config.toml` the following section:
|
||||
|
||||
```toml
|
||||
[[deployment.targets]]
|
||||
URL = "s3://<bucket>?endpoint=<endpoint>&disableSSL=<bool>&s3ForcePathStyle=true®ion=garage"
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```toml
|
||||
[[deployment.targets]]
|
||||
URL = "s3://my-blog?endpoint=localhost:9000&disableSSL=true&s3ForcePathStyle=true®ion=garage"
|
||||
```
|
||||
|
||||
Then inform hugo of your credentials:
|
||||
|
||||
```bash
|
||||
export AWS_ACCESS_KEY_ID=GKxxx
|
||||
export AWS_SECRET_ACCESS_KEY=xxx
|
||||
```
|
||||
|
||||
And finally deploy your website:
|
||||
|
||||
```bsh
|
||||
hugo deploy
|
||||
```
|
||||
|
||||
*External links:*
|
||||
- [gocloud.dev > aws > Supported URL parameters](https://pkg.go.dev/gocloud.dev/aws?utm_source=godoc#ConfigFromURLParams)
|
||||
- [Hugo Documentation > hugo deploy](https://gohugo.io/hosting-and-deployment/hugo-deploy/)
|
||||
|
||||
## Publii
|
||||
|
||||
It would require a patch either on Garage or on Publii to make both systems work.
|
||||
|
||||
Currently, the proposed workaround is to deploy your website manually:
|
||||
- On the left menu, click on Server, choose Manual Deployment (the logo looks like a compressed file)
|
||||
- Set your website URL, keep Output type as "Non-compressed catalog"
|
||||
- Click on Save changes
|
||||
- Click on Sync your website (bottom left of the app)
|
||||
- On the new page, click again on Sync your website
|
||||
- Click on Get website files
|
||||
- You need to synchronize the output folder you see in your file explorer, we will use minio client.
|
||||
|
||||
Be sure that you [configured minio client](cli.html#minio-client-recommended).
|
||||
|
||||
Then copy this output folder
|
||||
|
||||
```bash
|
||||
mc mirror --overwrite output garage/my-site
|
||||
```
|
||||
|
||||
## Generic (eg. Jekyll)
|
||||
|
||||
Some tools do not support sending to a S3 backend but output a compiled folder on your system.
|
||||
We can then use any CLI tool to upload this content to our S3 target.
|
||||
|
||||
First, start by [configuring minio client](cli.html#minio-client-recommended).
|
||||
|
||||
Then build your website:
|
||||
|
||||
```bash
|
||||
jekyll build
|
||||
```
|
||||
|
||||
And copy jekyll's output folder on S3:
|
||||
|
||||
```bash
|
||||
mc mirror --overwrite _site garage/my-site
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
# Exposing buckets as websites
|
||||
|
||||
You can expose your bucket as a website with this simple command:
|
||||
|
||||
```bash
|
||||
garage bucket website --allow my-website
|
||||
```
|
||||
|
||||
Now it will be **publicly** exposed on the web endpoint (by default listening on port 3902).
|
||||
|
||||
Our website serving logic is as follow:
|
||||
- Supports only static websites (no support for PHP or other languages)
|
||||
- Does not support directory listing
|
||||
- The index is defined in your `garage.toml`. ([ref](/reference_manual/configuration.html#index))
|
||||
|
||||
Now we need to infer the URL of your website through your bucket name.
|
||||
Let assume:
|
||||
- we set `root_domain = ".web.example.com"` in `garage.toml` ([ref](/reference_manual/configuration.html#root_domain))
|
||||
- our bucket name is `garagehq.deuxfleurs.fr`.
|
||||
|
||||
Our bucket will be served if the Host field matches one of these 2 values (the port is ignored):
|
||||
|
||||
- `garagehq.deuxfleurs.fr.web.example.com`: you can dedicate a subdomain to your users (here `web.example.com`).
|
||||
|
||||
- `garagehq.deuxfleurs.fr`: your users can bring their own domain name, they just need to point them to your Garage cluster.
|
||||
|
||||
You can try this logic locally, without configuring any DNS, thanks to `curl`:
|
||||
|
||||
```bash
|
||||
# prepare your test
|
||||
echo hello world > /tmp/index.html
|
||||
mc cp /tmp/index.html garage/garagehq.deuxfleurs.fr
|
||||
|
||||
curl -H 'Host: garagehq.deuxfleurs.fr' http://localhost:3902
|
||||
# should print "hello world"
|
||||
|
||||
curl -H 'Host: garagehq.deuxfleurs.fr.web.example.com' http://localhost:3902
|
||||
# should also print "hello world"
|
||||
```
|
||||
|
||||
Now that you understand how website logic works on Garage, you can:
|
||||
|
||||
- make the website endpoint listens on port 80 (instead of 3902)
|
||||
- use iptables to redirect the port 80 to the port 3902:
|
||||
`iptables -t nat -A PREROUTING -p tcp -dport 80 -j REDIRECT -to-port 3902`
|
||||
- or configure a [reverse proxy](reverse_proxy.html) in front of Garage to add TLS (HTTPS), CORS support, etc.
|
||||
|
||||
You can also take a look at [Website Integration](/connect/websites.html) to see how you can add Garage to your workflow.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Gateways
|
||||
|
||||
Gateways allow you to expose Garage endpoints (S3 API and websites) without storing data on the node.
|
||||
|
||||
## Benefits
|
||||
|
||||
You can configure Garage as a gateway on all nodes that will consume your S3 API, it will provide you the following benefits:
|
||||
|
||||
- **It removes 1 or 2 network RTT** Instead of (querying your reverse proxy then) querying a random node of the cluster that will forward your request to the nodes effectively storing the data, your local gateway will directly knows which node to query.
|
||||
|
||||
- **It ease server management** Instead of tracking in your reverse proxy and DNS what are the current Garage nodes, your gateway being part of the cluster keeps this information for you. In your software, you will always specify `http://localhost:3900`.
|
||||
|
||||
- **It simplifies security** Instead of having to maintain and renew a TLS certificate, you leverage the Secret Handshake protocol we use for our cluster. The S3 API protocol will be in plain text but limited to your local machine.
|
||||
|
||||
## Limitations
|
||||
|
||||
Currently it will not work with minio client. Follow issue [#64](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/64) for more information.
|
||||
|
||||
## Spawn a Gateway
|
||||
|
||||
The instructions are similar to a regular node, the only option that is different is while configuring the node, you must set the `--gateway` parameter:
|
||||
|
||||
```bash
|
||||
garage node configure --gateway --tag gw1 xxxx
|
||||
```
|
||||
|
||||
Then use `http://localhost:3900` when a S3 endpoint is required:
|
||||
|
||||
```bash
|
||||
aws --endpoint-url http://127.0.0.1:3900 s3 ls
|
||||
```
|
||||
@@ -11,15 +11,12 @@ to get familiar with Garage's command line and usage patterns.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To run a real-world deployment, make sure you the following conditions are met:
|
||||
To run a real-world deployment, make sure the following conditions are met:
|
||||
|
||||
- You have at least three machines with sufficient storage space available.
|
||||
|
||||
- Each machine has a public IP address which is reachable by other machines.
|
||||
Running behind a NAT is possible, but having several Garage nodes behind a single NAT
|
||||
is slightly more involved as each will have to have a different RPC port number
|
||||
(the local port number of a node must be the same as the port number exposed publicly
|
||||
by the NAT).
|
||||
Running behind a NAT is likely to be possible but hasn't been tested for the latest version (TODO).
|
||||
|
||||
- Ideally, each machine should have a SSD available in addition to the HDD you are dedicating
|
||||
to Garage. This will allow for faster access to metadata and has the potential
|
||||
@@ -45,44 +42,22 @@ For our example, we will suppose the following infrastructure with IPv6 connecti
|
||||
## Get a Docker image
|
||||
|
||||
Our docker image is currently named `lxpz/garage_amd64` and is stored on the [Docker Hub](https://hub.docker.com/r/lxpz/garage_amd64/tags?page=1&ordering=last_updated).
|
||||
We encourage you to use a fixed tag (eg. `v0.3.0`) and not the `latest` tag.
|
||||
For this example, we will use the latest published version at the time of the writing which is `v0.3.0` but it's up to you
|
||||
We encourage you to use a fixed tag (eg. `v0.4.0`) and not the `latest` tag.
|
||||
For this example, we will use the latest published version at the time of the writing which is `v0.4.0` but it's up to you
|
||||
to check [the most recent versions on the Docker Hub](https://hub.docker.com/r/lxpz/garage_amd64/tags?page=1&ordering=last_updated).
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
sudo docker pull lxpz/garage_amd64:v0.3.0
|
||||
sudo docker pull lxpz/garage_amd64:v0.4.0
|
||||
```
|
||||
|
||||
|
||||
## Generating TLS certificates
|
||||
|
||||
You first need to generate TLS certificates to encrypt traffic between Garage nodes
|
||||
(reffered to as RPC traffic).
|
||||
|
||||
To generate your TLS certificates, run on your machine:
|
||||
|
||||
```
|
||||
wget https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/branch/main/genkeys.sh
|
||||
chmod +x genkeys.sh
|
||||
./genkeys.sh
|
||||
```
|
||||
|
||||
It will creates a folder named `pki/` containing the keys that you will used for the cluster.
|
||||
These files will have to be copied to all of your cluster nodes, as explained below.
|
||||
|
||||
|
||||
## Deploying and configuring Garage
|
||||
|
||||
On each machine, we will have a similar setup,
|
||||
especially you must consider the following folders/files:
|
||||
|
||||
- `/etc/garage/garage.toml`: Garage daemon's configuration (see below)
|
||||
|
||||
- `/etc/garage/pki/`: Folder containing Garage certificates,
|
||||
must be generated on your computer and copied on the servers.
|
||||
Only the files `garage-ca.crt`, `garage.crt` and `garage.key` are necessary.
|
||||
- `/etc/garage.toml`: Garage daemon's configuration (see below)
|
||||
|
||||
- `/var/lib/garage/meta/`: Folder containing Garage's metadata,
|
||||
put this folder on a SSD if possible
|
||||
@@ -91,7 +66,7 @@ especially you must consider the following folders/files:
|
||||
this folder will be your main data storage and must be on a large storage (e.g. large HDD)
|
||||
|
||||
|
||||
A valid `/etc/garage/garage.toml` for our cluster would be:
|
||||
A valid `/etc/garage/garage.toml` for our cluster would look as follows:
|
||||
|
||||
```toml
|
||||
metadata_dir = "/var/lib/garage/meta"
|
||||
@@ -100,18 +75,10 @@ data_dir = "/var/lib/garage/data"
|
||||
replication_mode = "3"
|
||||
|
||||
rpc_bind_addr = "[::]:3901"
|
||||
rpc_public_addr = "<this node's public IP>:3901"
|
||||
rpc_secret = "<RPC secret>"
|
||||
|
||||
bootstrap_peers = [
|
||||
"[fc00:1::1]:3901",
|
||||
"[fc00:1::2]:3901",
|
||||
"[fc00:B::1]:3901",
|
||||
"[fc00:F::1]:3901",
|
||||
]
|
||||
|
||||
[rpc_tls]
|
||||
ca_cert = "/etc/garage/pki/garage-ca.crt"
|
||||
node_cert = "/etc/garage/pki/garage.crt"
|
||||
node_key = "/etc/garage/pki/garage.key"
|
||||
bootstrap_peers = []
|
||||
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
@@ -123,11 +90,14 @@ root_domain = ".web.garage"
|
||||
index = "index.html"
|
||||
```
|
||||
|
||||
Please make sure to change `bootstrap_peers` to **your** IP addresses!
|
||||
Check the following for your configuration files:
|
||||
|
||||
Check the [configuration file reference documentation](../reference_manual/configuration.md)
|
||||
to learn more about all available configuration options.
|
||||
- Make sure `rpc_public_addr` contains the public IP address of the node you are configuring.
|
||||
This parameter is optional but recommended: if your nodes have trouble communicating with
|
||||
one another, consider adding it.
|
||||
|
||||
- Make sure `rpc_secret` is the same value on all nodes. It should be a 32-bytes hex-encoded secret key.
|
||||
You can generate such a key with `openssl rand -hex 32`.
|
||||
|
||||
## Starting Garage using Docker
|
||||
|
||||
@@ -139,11 +109,10 @@ docker run \
|
||||
--name garaged \
|
||||
--restart always \
|
||||
--network host \
|
||||
-v /etc/garage/pki:/etc/garage/pki \
|
||||
-v /etc/garage/garage.toml:/garage/garage.toml \
|
||||
-v /etc/garage.toml:/etc/garage.toml \
|
||||
-v /var/lib/garage/meta:/var/lib/garage/meta \
|
||||
-v /var/lib/garage/data:/var/lib/garage/data \
|
||||
lxpz/garage_amd64:v0.3.0
|
||||
lxpz/garage_amd64:v0.4.0
|
||||
```
|
||||
|
||||
It should be restarted automatically at each reboot.
|
||||
@@ -155,101 +124,102 @@ but please check the relase notes before doing so!
|
||||
To upgrade, simply stop and remove this container and
|
||||
start again the command with a new version of Garage.
|
||||
|
||||
|
||||
## Controling the daemon
|
||||
|
||||
The `garage` binary has two purposes:
|
||||
- it acts as a daemon when launched with `garage server ...`
|
||||
- it acts as a daemon when launched with `garage server`
|
||||
- it acts as a control tool for the daemon when launched with any other command
|
||||
|
||||
In this section, we will see how to use the `garage` binary as a control tool for the daemon we just started.
|
||||
You first need to get a shell having access to this binary. For instance, enter the Docker container with:
|
||||
Ensure an appropriate `garage` binary (the same version as your Docker image) is available in your path.
|
||||
If your configuration file is at `/etc/garage.toml`, the `garage` binary should work with no further change.
|
||||
|
||||
You can test your `garage` CLI utility by running a simple command such as:
|
||||
|
||||
```bash
|
||||
sudo docker exec -ti garaged bash
|
||||
garage status
|
||||
```
|
||||
|
||||
You will now have a shell where the Garage binary is available as `/garage/garage`
|
||||
|
||||
*You can also install the binary on your machine to remotely control the cluster.*
|
||||
|
||||
## Talk to the daemon and create an alias
|
||||
|
||||
`garage` requires 4 options to talk with the daemon:
|
||||
At this point, nodes are not yet talking to one another.
|
||||
Your output should therefore look like follows:
|
||||
|
||||
```
|
||||
--ca-cert <ca-cert>
|
||||
--client-cert <client-cert>
|
||||
--client-key <client-key>
|
||||
-h, --rpc-host <rpc-host>
|
||||
Mercury$ garage node-id
|
||||
==== HEALTHY NODES ====
|
||||
ID Hostname Address Tag Zone Capacity
|
||||
563e1ac825ee3323… Mercury [fc00:1::1]:3901 NO ROLE ASSIGNED
|
||||
```
|
||||
|
||||
The 3 first ones are certificates and keys needed by TLS, the last one is simply the address of Garage's RPC endpoint.
|
||||
|
||||
If you are invoking `garage` from a server node directly, you do not need to set `--rpc-host`
|
||||
as the default value `127.0.0.1:3901` will allow it to contact Garage correctly.
|
||||
## Connecting nodes together
|
||||
|
||||
To avoid typing the 3 first options each time we want to run a command,
|
||||
you can use the following alias:
|
||||
When your Garage nodes first start, they will generate a local node identifier
|
||||
(based on a public/private key pair).
|
||||
|
||||
To obtain the node identifier of a node, once it is generated,
|
||||
run `garage node-id`.
|
||||
This will print keys as follows:
|
||||
|
||||
```bash
|
||||
alias garagectl='/garage/garage \
|
||||
--ca-cert /etc/garage/pki/garage-ca.crt \
|
||||
--client-cert /etc/garage/pki/garage.crt \
|
||||
--client-key /etc/garage/pki/garage.key'
|
||||
Mercury$ garage node-id
|
||||
563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d@[fc00:1::1]:3901
|
||||
|
||||
Venus$ garage node-id
|
||||
86f0f26ae4afbd59aaf9cfb059eefac844951efd5b8caeec0d53f4ed6c85f332@[fc00:1::2]:3901
|
||||
|
||||
etc.
|
||||
```
|
||||
|
||||
You can now use all of the commands presented in the [quick start guide](../quick_start/index.md),
|
||||
simply replace occurences of `garage` by `garagectl`.
|
||||
You can then instruct nodes to connect to one another as follows:
|
||||
|
||||
#### Test the alias
|
||||
|
||||
You can test your alias by running a simple command such as:
|
||||
|
||||
```
|
||||
garagectl status
|
||||
```bash
|
||||
# Instruct Venus to connect to Mercury (this will establish communication both ways)
|
||||
Venus$ garage node connect 563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d@[fc00:1::1]:3901
|
||||
```
|
||||
|
||||
You should get something like that as result:
|
||||
You don't nead to instruct all node to connect to all other nodes:
|
||||
nodes will discover one another transitively.
|
||||
|
||||
Now if your run `garage status` on any node, you should have an output that looks as follows:
|
||||
|
||||
```
|
||||
Healthy nodes:
|
||||
8781c50c410a41b3… Mercury [fc00:1::1]:3901 UNCONFIGURED/REMOVED
|
||||
2a638ed6c775b69a… Venus [fc00:1::2]:3901 UNCONFIGURED/REMOVED
|
||||
68143d720f20c89d… Earth [fc00:B::1]:3901 UNCONFIGURED/REMOVED
|
||||
212f7572f0c89da9… Mars [fc00:F::1]:3901 UNCONFIGURED/REMOVED
|
||||
==== HEALTHY NODES ====
|
||||
ID Hostname Address Tag Zone Capacity
|
||||
563e1ac825ee3323… Mercury [fc00:1::1]:3901 NO ROLE ASSIGNED
|
||||
86f0f26ae4afbd59… Venus [fc00:1::2]:3901 NO ROLE ASSIGNED
|
||||
68143d720f20c89d… Earth [fc00:B::1]:3901 NO ROLE ASSIGNED
|
||||
212f7572f0c89da9… Mars [fc00:F::1]:3901 NO ROLE ASSIGNED
|
||||
```
|
||||
|
||||
|
||||
## Configuring a cluster
|
||||
## Giving roles to nodes
|
||||
|
||||
We will now inform Garage of the disk space available on each node of the cluster
|
||||
as well as the zone (e.g. datacenter) in which each machine is located.
|
||||
|
||||
For our example, we will suppose we have the following infrastructure (Capacity, Identifier and Datacenter are specific values to Garage described in the following):
|
||||
For our example, we will suppose we have the following infrastructure
|
||||
(Capacity, Identifier and Zone are specific values to Garage described in the following):
|
||||
|
||||
| Location | Name | Disk Space | `Capacity` | `Identifier` | `Zone` |
|
||||
|----------|---------|------------|------------|--------------|--------------|
|
||||
| Paris | Mercury | 1 To | `2` | `8781c5` | `par1` |
|
||||
| Paris | Venus | 2 To | `4` | `2a638e` | `par1` |
|
||||
| London | Earth | 2 To | `4` | `68143d` | `lon1` |
|
||||
| Brussels | Mars | 1.5 To | `3` | `212f75` | `bru1` |
|
||||
| Paris | Mercury | 1 To | `2` | `563e` | `par1` |
|
||||
| Paris | Venus | 2 To | `4` | `86f0` | `par1` |
|
||||
| London | Earth | 2 To | `4` | `6814` | `lon1` |
|
||||
| Brussels | Mars | 1.5 To | `3` | `212f` | `bru1` |
|
||||
|
||||
#### Node identifiers
|
||||
|
||||
After its first launch, Garage generates a random and unique identifier for each nodes, such as:
|
||||
|
||||
```
|
||||
8781c50c410a41b363167e9d49cc468b6b9e4449b6577b64f15a249a149bdcbc
|
||||
563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d
|
||||
```
|
||||
|
||||
Often a shorter form can be used, containing only the beginning of the identifier, like `8781c5`,
|
||||
Often a shorter form can be used, containing only the beginning of the identifier, like `563e`,
|
||||
which identifies the server "Mercury" located in "Paris" according to our previous table.
|
||||
|
||||
The most simple way to match an identifier to a node is to run:
|
||||
|
||||
```
|
||||
garagectl status
|
||||
garage status
|
||||
```
|
||||
|
||||
It will display the IP address associated with each node;
|
||||
@@ -287,16 +257,16 @@ have 66% chance of being stored by Venus and 33% chance of being stored by Mercu
|
||||
Given the information above, we will configure our cluster as follow:
|
||||
|
||||
```
|
||||
garagectl node configure -z par1 -c 2 -t mercury 8781c5
|
||||
garagectl node configure -z par1 -c 4 -t venus 2a638e
|
||||
garagectl node configure -z lon1 -c 4 -t earth 68143d
|
||||
garagectl node configure -z bru1 -c 3 -t mars 212f75
|
||||
garage node configure -z par1 -c 2 -t mercury 563e
|
||||
garage node configure -z par1 -c 4 -t venus 86f0
|
||||
garage node configure -z lon1 -c 4 -t earth 6814
|
||||
garage node configure -z bru1 -c 3 -t mars 212f
|
||||
```
|
||||
|
||||
|
||||
## Using your Garage cluster
|
||||
|
||||
Creating buckets and managing keys is done using the `garagectl` CLI,
|
||||
Creating buckets and managing keys is done using the `garage` CLI,
|
||||
and is covered in the [quick start guide](../quick_start/index.md).
|
||||
Remember also that the CLI is self-documented thanks to the `--help` flag and
|
||||
the `help` subcommand (e.g. `garage help`, `garage key --help`).
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
# Configuring a reverse proxy
|
||||
|
||||
The main reason to add a reverse proxy in front of Garage is to provide TLS to your users.
|
||||
|
||||
In production you will likely need your certificates signed by a certificate authority.
|
||||
The most automated way is to use a provider supporting the [ACME protocol](https://datatracker.ietf.org/doc/html/rfc8555)
|
||||
such as [Let's Encrypt](https://letsencrypt.org/), [ZeroSSL](https://zerossl.com/) or [Buypass Go SSL](https://www.buypass.com/ssl/products/acme).
|
||||
|
||||
If you are only testing Garage, you can generate a self-signed certificate to follow the documentation:
|
||||
|
||||
```bash
|
||||
openssl req \
|
||||
-new \
|
||||
-x509 \
|
||||
-keyout /tmp/garage.key \
|
||||
-out /tmp/garage.crt \
|
||||
-nodes \
|
||||
-subj "/C=XX/ST=XX/L=XX/O=XX/OU=XX/CN=localhost/emailAddress=X@X.XX" \
|
||||
-addext "subjectAltName = DNS:localhost, IP:127.0.0.1"
|
||||
|
||||
cat /tmp/garage.key /tmp/garage.crt > /tmp/garage.pem
|
||||
```
|
||||
|
||||
Be careful as you will need to allow self signed certificates in your client.
|
||||
For example, with minio, you must add the `--insecure` flag.
|
||||
An example:
|
||||
|
||||
```bash
|
||||
mc ls --insecure garage/
|
||||
```
|
||||
|
||||
## socat (only for testing purposes)
|
||||
|
||||
If you want to test Garage with a TLS frontend, socat can do it for you in a single command:
|
||||
|
||||
```bash
|
||||
socat \
|
||||
"openssl-listen:443,\
|
||||
reuseaddr,\
|
||||
fork,\
|
||||
verify=0,\
|
||||
cert=/tmp/garage.pem" \
|
||||
tcp4-connect:localhost:3900
|
||||
```
|
||||
|
||||
## Nginx
|
||||
|
||||
Nginx is a well-known reverse proxy suitable for production.
|
||||
We do the configuration in 3 steps: first we define the upstream blocks ("the backends")
|
||||
then we define the server blocks ("the frontends") for the S3 endpoint and finally for the web endpoint.
|
||||
|
||||
The following configuration blocks can be all put in the same `/etc/nginx/sites-available/garage.conf`.
|
||||
To make your configuration active, run `ln -s /etc/nginx/sites-available/garage.conf /etc/nginx/sites-enabled/`.
|
||||
If you directly put the instructions in the root `nginx.conf`, keep in mind that these configurations must be enclosed inside a `http { }` block.
|
||||
|
||||
And do not forget to reload nginx with `systemctl reload nginx` or `nginx -s reload`.
|
||||
|
||||
### Defining backends
|
||||
|
||||
First, we need to tell to nginx how to access our Garage cluster.
|
||||
Because we have multiple nodes, we want to leverage all of them by spreading the load.
|
||||
|
||||
In nginx, we can do that with the upstream directive.
|
||||
Because we have 2 endpoints: one for the S3 API and one to serve websites,
|
||||
we create 2 backends named respectively `s3_backend` and `web_backend`.
|
||||
|
||||
A documented example for the `s3_backend` assuming you chose port 3900:
|
||||
|
||||
```nginx
|
||||
upstream s3_backend {
|
||||
# if you have a garage instance locally
|
||||
server 127.0.0.1:3900;
|
||||
# you can also put your other instances
|
||||
server 192.168.1.3:3900;
|
||||
# domain names also work
|
||||
server garage1.example.com:3900;
|
||||
# you can assign weights if you have some servers
|
||||
# that are more powerful than others
|
||||
server garage2.example.com:3900 weight=2;
|
||||
}
|
||||
```
|
||||
|
||||
A similar example for the `web_backend` assuming you chose port 3902:
|
||||
|
||||
```nginx
|
||||
upstream web_backend {
|
||||
server 127.0.0.1:3902;
|
||||
server 192.168.1.3:3902;
|
||||
server garage1.example.com:3902;
|
||||
server garage2.example.com:3902 weight=2;
|
||||
}
|
||||
```
|
||||
|
||||
### Exposing the S3 API
|
||||
|
||||
The configuration section for the S3 API is simple as we only support path-access style yet.
|
||||
We simply configure the TLS parameters and forward all the requests to the backend:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen [::]:443 http2 ssl;
|
||||
ssl_certificate /tmp/garage.crt;
|
||||
ssl_certificate_key /tmp/garage.key;
|
||||
|
||||
# should be the endpoint you want
|
||||
# aws uses s3.amazonaws.com for example
|
||||
server_name garage.example.com;
|
||||
|
||||
location / {
|
||||
proxy_pass http://s3_backend;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Exposing the web endpoint
|
||||
|
||||
The web endpoint is a bit more complicated to configure as it listens on many different `Host` fields.
|
||||
To better understand the logic involved, you can refer to the [Exposing buckets as websites](/cookbook/exposing_websites.html) section.
|
||||
Also, for some applications, you may need to serve CORS headers: Garage can not serve them directly but we show how we can use nginx to serve them.
|
||||
You can use the following example as your starting point:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen [::]:443 http2 ssl;
|
||||
ssl_certificate /tmp/garage.crt;
|
||||
ssl_certificate_key /tmp/garage.key;
|
||||
|
||||
# We list all the Hosts fields that can access our buckets
|
||||
server_name *.web.garage
|
||||
example.com
|
||||
my-site.tld
|
||||
;
|
||||
|
||||
location / {
|
||||
# Add these headers only if you want to allow CORS requests
|
||||
# For production use, more specific rules would be better for your security
|
||||
add_header Access-Control-Allow-Origin *;
|
||||
add_header Access-Control-Max-Age 3600;
|
||||
add_header Access-Control-Expose-Headers Content-Length;
|
||||
add_header Access-Control-Allow-Headers Range;
|
||||
|
||||
# We do not forward OPTIONS requests to Garage
|
||||
# as it does not support them but they are needed for CORS.
|
||||
if ($request_method = OPTIONS) {
|
||||
return 200;
|
||||
}
|
||||
|
||||
proxy_pass http://web_backend;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Apache httpd
|
||||
|
||||
@TODO
|
||||
|
||||
## Traefik
|
||||
|
||||
@TODO
|
||||
@@ -1,9 +1,14 @@
|
||||
# Starting Garage with systemd instead of Docker
|
||||
# Starting Garage with systemd
|
||||
|
||||
We make some assumptions for this systemd deployment.
|
||||
|
||||
- Your garage binary is located at `/usr/local/bin/garage`.
|
||||
|
||||
- Your configuration file is located at `/etc/garage.toml`.
|
||||
|
||||
- Your `garage.toml` must be set with `metadata_dir=/var/lib/garage/meta` and `data_dir=/var/lib/garage/data`. This is mandatory to use `systemd` hardening feature [Dynamic User](https://0pointer.net/blog/dynamic-users-with-systemd.html). Note that in your host filesystem, Garage data will be held in `/var/lib/private/garage`.
|
||||
|
||||
NOTE: This guide is incomplete. Typicall you would also want to create a separate
|
||||
Unix user to run Garage.
|
||||
|
||||
Make sure you have the Garage binary installed on your system (see [quick start](../quick_start/index.md)), e.g. at `/usr/local/bin/garage`.
|
||||
|
||||
Create a file named `/etc/systemd/system/garage.service`:
|
||||
|
||||
@@ -15,12 +20,18 @@ Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Environment='RUST_LOG=garage=info' 'RUST_BACKTRACE=1'
|
||||
ExecStart=/usr/local/bin/garage server -c /etc/garage/garage.toml
|
||||
ExecStart=/usr/local/bin/garage server
|
||||
StateDirectory=garage
|
||||
DynamicUser=true
|
||||
ProtectHome=true
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
*A note on hardening: garage will be run as a non privileged user, its user id is dynamically allocated by systemd. It cannot access (read or write) home folders (/home, /root and /run/user), the rest of the filesystem can only be read but not written, only the path seen as /var/lib/garage is writable as seen by the service (mapped to /var/lib/private/garage on your host). Additionnaly, the process can not gain new privileges over time.*
|
||||
|
||||
To start the service then automatically enable it at boot:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
# Design draft
|
||||
|
||||
**WARNING: this documentation is a design draft which was written before Garage's actual implementation.
|
||||
The general principle are similar, but details have not been updated.**
|
||||
|
||||
|
||||
#### Modules
|
||||
|
||||
- `membership/`: configuration, membership management (gossip of node's presence and status), ring generation --> what about Serf (used by Consul/Nomad) : https://www.serf.io/? Seems a huge library with many features so maybe overkill/hard to integrate
|
||||
- `metadata/`: metadata management
|
||||
- `blocks/`: block management, writing, GC and rebalancing
|
||||
- `internal/`: server to server communication (HTTP server and client that reuses connections, TLS if we want, etc)
|
||||
- `api/`: S3 API
|
||||
- `web/`: web management interface
|
||||
|
||||
#### Metadata tables
|
||||
|
||||
**Objects:**
|
||||
|
||||
- *Hash key:* Bucket name (string)
|
||||
- *Sort key:* Object key (string)
|
||||
- *Sort key:* Version timestamp (int)
|
||||
- *Sort key:* Version UUID (string)
|
||||
- Complete: bool
|
||||
- Inline: bool, true for objects < threshold (say 1024)
|
||||
- Object size (int)
|
||||
- Mime type (string)
|
||||
- Data for inlined objects (blob)
|
||||
- Hash of first block otherwise (string)
|
||||
|
||||
*Having only a hash key on the bucket name will lead to storing all file entries of this table for a specific bucket on a single node. At the same time, it is the only way I see to rapidly being able to list all bucket entries...*
|
||||
|
||||
**Blocks:**
|
||||
|
||||
- *Hash key:* Version UUID (string)
|
||||
- *Sort key:* Offset of block in total file (int)
|
||||
- Hash of data block (string)
|
||||
|
||||
A version is defined by the existence of at least one entry in the blocks table for a certain version UUID.
|
||||
We must keep the following invariant: if a version exists in the blocks table, it has to be referenced in the objects table.
|
||||
We explicitly manage concurrent versions of an object: the version timestamp and version UUID columns are index columns, thus we may have several concurrent versions of an object.
|
||||
Important: before deleting an older version from the objects table, we must make sure that we did a successfull delete of the blocks of that version from the blocks table.
|
||||
|
||||
Thus, the workflow for reading an object is as follows:
|
||||
|
||||
1. Check permissions (LDAP)
|
||||
2. Read entry in object table. If data is inline, we have its data, stop here.
|
||||
-> if several versions, take newest one and launch deletion of old ones in background
|
||||
3. Read first block from cluster. If size <= 1 block, stop here.
|
||||
4. Simultaneously with previous step, if size > 1 block: query the Blocks table for the IDs of the next blocks
|
||||
5. Read subsequent blocks from cluster
|
||||
|
||||
Workflow for PUT:
|
||||
|
||||
1. Check write permission (LDAP)
|
||||
2. Select a new version UUID
|
||||
3. Write a preliminary entry for the new version in the objects table with complete = false
|
||||
4. Send blocks to cluster and write entries in the blocks table
|
||||
5. Update the version with complete = true and all of the accurate information (size, etc)
|
||||
6. Return success to the user
|
||||
7. Launch a background job to check and delete older versions
|
||||
|
||||
Workflow for DELETE:
|
||||
|
||||
1. Check write permission (LDAP)
|
||||
2. Get current version (or versions) in object table
|
||||
3. Do the deletion of those versions NOT IN A BACKGROUND JOB THIS TIME
|
||||
4. Return succes to the user if we were able to delete blocks from the blocks table and entries from the object table
|
||||
|
||||
To delete a version:
|
||||
|
||||
1. List the blocks from Cassandra
|
||||
2. For each block, delete it from cluster. Don't care if some deletions fail, we can do GC.
|
||||
3. Delete all of the blocks from the blocks table
|
||||
4. Finally, delete the version from the objects table
|
||||
|
||||
Known issue: if someone is reading from a version that we want to delete and the object is big, the read might be interrupted. I think it is ok to leave it like this, we just cut the connection if data disappears during a read.
|
||||
|
||||
("Soit P un problème, on s'en fout est une solution à ce problème")
|
||||
|
||||
#### Block storage on disk
|
||||
|
||||
**Blocks themselves:**
|
||||
|
||||
- file path = /blobs/(first 3 hex digits of hash)/(rest of hash)
|
||||
|
||||
**Reverse index for GC & other block-level metadata:**
|
||||
|
||||
- file path = /meta/(first 3 hex digits of hash)/(rest of hash)
|
||||
- map block hash -> set of version UUIDs where it is referenced
|
||||
|
||||
Usefull metadata:
|
||||
|
||||
- list of versions that reference this block in the Casandra table, so that we can do GC by checking in Cassandra that the lines still exist
|
||||
- list of other nodes that we know have acknowledged a write of this block, usefull in the rebalancing algorithm
|
||||
|
||||
Write strategy: have a single thread that does all write IO so that it is serialized (or have several threads that manage independent parts of the hash space). When writing a blob, write it to a temporary file, close, then rename so that a concurrent read gets a consistent result (either not found or found with whole content).
|
||||
|
||||
Read strategy: the only read operation is get(hash) that returns either the data or not found (can do a corruption check as well and return corrupted state if it is the case). Can be done concurrently with writes.
|
||||
|
||||
**Internal API:**
|
||||
|
||||
- get(block hash) -> ok+data/not found/corrupted
|
||||
- put(block hash & data, version uuid + offset) -> ok/error
|
||||
- put with no data(block hash, version uuid + offset) -> ok/not found plz send data/error
|
||||
- delete(block hash, version uuid + offset) -> ok/error
|
||||
|
||||
GC: when last ref is deleted, delete block.
|
||||
Long GC procedure: check in Cassandra that version UUIDs still exist and references this block.
|
||||
|
||||
Rebalancing: takes as argument the list of newly added nodes.
|
||||
|
||||
- List all blocks that we have. For each block:
|
||||
- If it hits a newly introduced node, send it to them.
|
||||
Use put with no data first to check if it has to be sent to them already or not.
|
||||
Use a random listing order to avoid race conditions (they do no harm but we might have two nodes sending the same thing at the same time thus wasting time).
|
||||
- If it doesn't hit us anymore, delete it and its reference list.
|
||||
|
||||
Only one balancing can be running at a same time. It can be restarted at the beginning with new parameters.
|
||||
|
||||
#### Membership management
|
||||
|
||||
Two sets of nodes:
|
||||
|
||||
- set of nodes from which a ping was recently received, with status: number of stored blocks, request counters, error counters, GC%, rebalancing%
|
||||
(eviction from this set after say 30 seconds without ping)
|
||||
- set of nodes that are part of the system, explicitly modified by the operator using the web UI (persisted to disk),
|
||||
is a CRDT using a version number for the value of the whole set
|
||||
|
||||
Thus, three states for nodes:
|
||||
|
||||
- healthy: in both sets
|
||||
- missing: not pingable but part of desired cluster
|
||||
- unused/draining: currently present but not part of the desired cluster, empty = if contains nothing, draining = if still contains some blocks
|
||||
|
||||
Membership messages between nodes:
|
||||
|
||||
- ping with current state + hash of current membership info -> reply with same info
|
||||
- send&get back membership info (the ids of nodes that are in the two sets): used when no local membership change in a long time and membership info hash discrepancy detected with first message (passive membership fixing with full CRDT gossip)
|
||||
- inform of newly pingable node(s) -> no result, when receive new info repeat to all (reliable broadcast)
|
||||
- inform of operator membership change -> no result, when receive new info repeat to all (reliable broadcast)
|
||||
|
||||
Ring: generated from the desired set of nodes, however when doing read/writes on the ring, skip nodes that are known to be not pingable.
|
||||
The tokens are generated in a deterministic fashion from node IDs (hash of node id + token number from 1 to K).
|
||||
Number K of tokens per node: decided by the operator & stored in the operator's list of nodes CRDT. Default value proposal: with node status information also broadcast disk total size and free space, and propose a default number of tokens equal to 80%Free space / 10Gb. (this is all user interface)
|
||||
|
||||
|
||||
#### Constants
|
||||
|
||||
- Block size: around 1MB ? --> Exoscale use 16MB chunks
|
||||
- Number of tokens in the hash ring: one every 10Gb of allocated storage
|
||||
- Threshold for storing data directly in Cassandra objects table: 1kb bytes (maybe up to 4kb?)
|
||||
- Ping timeout (time after which a node is registered as unresponsive/missing): 30 seconds
|
||||
- Ping interval: 10 seconds
|
||||
- ??
|
||||
|
||||
#### Links
|
||||
|
||||
- CDC: <https://www.usenix.org/system/files/conference/atc16/atc16-paper-xia.pdf>
|
||||
- Erasure coding: <http://web.eecs.utk.edu/~jplank/plank/papers/CS-08-627.html>
|
||||
- [Openstack Storage Concepts](https://docs.openstack.org/arch-design/design-storage/design-storage-concepts.html)
|
||||
- [RADOS](https://ceph.com/wp-content/uploads/2016/08/weil-rados-pdsw07.pdf)
|
||||
@@ -1,158 +1,95 @@
|
||||
**WARNING: this documentation is more a "design draft", which was written before Garage's actual implementation. The general principle is similar but details have not yet been updated.**
|
||||
# Internals
|
||||
|
||||
#### Modules
|
||||
## Overview
|
||||
|
||||
- `membership/`: configuration, membership management (gossip of node's presence and status), ring generation --> what about Serf (used by Consul/Nomad) : https://www.serf.io/? Seems a huge library with many features so maybe overkill/hard to integrate
|
||||
- `metadata/`: metadata management
|
||||
- `blocks/`: block management, writing, GC and rebalancing
|
||||
- `internal/`: server to server communication (HTTP server and client that reuses connections, TLS if we want, etc)
|
||||
- `api/`: S3 API
|
||||
- `web/`: web management interface
|
||||
TODO: write this section
|
||||
|
||||
#### Metadata tables
|
||||
- The Dynamo ring
|
||||
|
||||
**Objects:**
|
||||
- CRDTs
|
||||
|
||||
- *Hash key:* Bucket name (string)
|
||||
- *Sort key:* Object key (string)
|
||||
- *Sort key:* Version timestamp (int)
|
||||
- *Sort key:* Version UUID (string)
|
||||
- Complete: bool
|
||||
- Inline: bool, true for objects < threshold (say 1024)
|
||||
- Object size (int)
|
||||
- Mime type (string)
|
||||
- Data for inlined objects (blob)
|
||||
- Hash of first block otherwise (string)
|
||||
- Consistency model of Garage tables
|
||||
|
||||
*Having only a hash key on the bucket name will lead to storing all file entries of this table for a specific bucket on a single node. At the same time, it is the only way I see to rapidly being able to list all bucket entries...*
|
||||
|
||||
**Blocks:**
|
||||
|
||||
- *Hash key:* Version UUID (string)
|
||||
- *Sort key:* Offset of block in total file (int)
|
||||
- Hash of data block (string)
|
||||
|
||||
A version is defined by the existence of at least one entry in the blocks table for a certain version UUID.
|
||||
We must keep the following invariant: if a version exists in the blocks table, it has to be referenced in the objects table.
|
||||
We explicitly manage concurrent versions of an object: the version timestamp and version UUID columns are index columns, thus we may have several concurrent versions of an object.
|
||||
Important: before deleting an older version from the objects table, we must make sure that we did a successfull delete of the blocks of that version from the blocks table.
|
||||
|
||||
Thus, the workflow for reading an object is as follows:
|
||||
|
||||
1. Check permissions (LDAP)
|
||||
2. Read entry in object table. If data is inline, we have its data, stop here.
|
||||
-> if several versions, take newest one and launch deletion of old ones in background
|
||||
3. Read first block from cluster. If size <= 1 block, stop here.
|
||||
4. Simultaneously with previous step, if size > 1 block: query the Blocks table for the IDs of the next blocks
|
||||
5. Read subsequent blocks from cluster
|
||||
|
||||
Workflow for PUT:
|
||||
|
||||
1. Check write permission (LDAP)
|
||||
2. Select a new version UUID
|
||||
3. Write a preliminary entry for the new version in the objects table with complete = false
|
||||
4. Send blocks to cluster and write entries in the blocks table
|
||||
5. Update the version with complete = true and all of the accurate information (size, etc)
|
||||
6. Return success to the user
|
||||
7. Launch a background job to check and delete older versions
|
||||
|
||||
Workflow for DELETE:
|
||||
|
||||
1. Check write permission (LDAP)
|
||||
2. Get current version (or versions) in object table
|
||||
3. Do the deletion of those versions NOT IN A BACKGROUND JOB THIS TIME
|
||||
4. Return succes to the user if we were able to delete blocks from the blocks table and entries from the object table
|
||||
|
||||
To delete a version:
|
||||
|
||||
1. List the blocks from Cassandra
|
||||
2. For each block, delete it from cluster. Don't care if some deletions fail, we can do GC.
|
||||
3. Delete all of the blocks from the blocks table
|
||||
4. Finally, delete the version from the objects table
|
||||
|
||||
Known issue: if someone is reading from a version that we want to delete and the object is big, the read might be interrupted. I think it is ok to leave it like this, we just cut the connection if data disappears during a read.
|
||||
|
||||
("Soit P un problème, on s'en fout est une solution à ce problème")
|
||||
|
||||
#### Block storage on disk
|
||||
|
||||
**Blocks themselves:**
|
||||
|
||||
- file path = /blobs/(first 3 hex digits of hash)/(rest of hash)
|
||||
|
||||
**Reverse index for GC & other block-level metadata:**
|
||||
|
||||
- file path = /meta/(first 3 hex digits of hash)/(rest of hash)
|
||||
- map block hash -> set of version UUIDs where it is referenced
|
||||
|
||||
Usefull metadata:
|
||||
|
||||
- list of versions that reference this block in the Casandra table, so that we can do GC by checking in Cassandra that the lines still exist
|
||||
- list of other nodes that we know have acknowledged a write of this block, usefull in the rebalancing algorithm
|
||||
|
||||
Write strategy: have a single thread that does all write IO so that it is serialized (or have several threads that manage independent parts of the hash space). When writing a blob, write it to a temporary file, close, then rename so that a concurrent read gets a consistent result (either not found or found with whole content).
|
||||
|
||||
Read strategy: the only read operation is get(hash) that returns either the data or not found (can do a corruption check as well and return corrupted state if it is the case). Can be done concurrently with writes.
|
||||
|
||||
**Internal API:**
|
||||
|
||||
- get(block hash) -> ok+data/not found/corrupted
|
||||
- put(block hash & data, version uuid + offset) -> ok/error
|
||||
- put with no data(block hash, version uuid + offset) -> ok/not found plz send data/error
|
||||
- delete(block hash, version uuid + offset) -> ok/error
|
||||
|
||||
GC: when last ref is deleted, delete block.
|
||||
Long GC procedure: check in Cassandra that version UUIDs still exist and references this block.
|
||||
|
||||
Rebalancing: takes as argument the list of newly added nodes.
|
||||
|
||||
- List all blocks that we have. For each block:
|
||||
- If it hits a newly introduced node, send it to them.
|
||||
Use put with no data first to check if it has to be sent to them already or not.
|
||||
Use a random listing order to avoid race conditions (they do no harm but we might have two nodes sending the same thing at the same time thus wasting time).
|
||||
- If it doesn't hit us anymore, delete it and its reference list.
|
||||
|
||||
Only one balancing can be running at a same time. It can be restarted at the beginning with new parameters.
|
||||
|
||||
#### Membership management
|
||||
|
||||
Two sets of nodes:
|
||||
|
||||
- set of nodes from which a ping was recently received, with status: number of stored blocks, request counters, error counters, GC%, rebalancing%
|
||||
(eviction from this set after say 30 seconds without ping)
|
||||
- set of nodes that are part of the system, explicitly modified by the operator using the web UI (persisted to disk),
|
||||
is a CRDT using a version number for the value of the whole set
|
||||
|
||||
Thus, three states for nodes:
|
||||
|
||||
- healthy: in both sets
|
||||
- missing: not pingable but part of desired cluster
|
||||
- unused/draining: currently present but not part of the desired cluster, empty = if contains nothing, draining = if still contains some blocks
|
||||
|
||||
Membership messages between nodes:
|
||||
|
||||
- ping with current state + hash of current membership info -> reply with same info
|
||||
- send&get back membership info (the ids of nodes that are in the two sets): used when no local membership change in a long time and membership info hash discrepancy detected with first message (passive membership fixing with full CRDT gossip)
|
||||
- inform of newly pingable node(s) -> no result, when receive new info repeat to all (reliable broadcast)
|
||||
- inform of operator membership change -> no result, when receive new info repeat to all (reliable broadcast)
|
||||
|
||||
Ring: generated from the desired set of nodes, however when doing read/writes on the ring, skip nodes that are known to be not pingable.
|
||||
The tokens are generated in a deterministic fashion from node IDs (hash of node id + token number from 1 to K).
|
||||
Number K of tokens per node: decided by the operator & stored in the operator's list of nodes CRDT. Default value proposal: with node status information also broadcast disk total size and free space, and propose a default number of tokens equal to 80%Free space / 10Gb. (this is all user interface)
|
||||
See this presentation (in French) for some first information:
|
||||
<https://git.deuxfleurs.fr/Deuxfleurs/garage/src/branch/main/doc/talks/2020-12-02_wide-team/talk.pdf>
|
||||
|
||||
|
||||
#### Constants
|
||||
## Garbage collection
|
||||
|
||||
- Block size: around 1MB ? --> Exoscale use 16MB chunks
|
||||
- Number of tokens in the hash ring: one every 10Gb of allocated storage
|
||||
- Threshold for storing data directly in Cassandra objects table: 1kb bytes (maybe up to 4kb?)
|
||||
- Ping timeout (time after which a node is registered as unresponsive/missing): 30 seconds
|
||||
- Ping interval: 10 seconds
|
||||
- ??
|
||||
A faulty garbage collection procedure has been the cause of
|
||||
[critical bug #39](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/39).
|
||||
This precise bug was fixed in the code, however there are potentially more
|
||||
general issues with the garbage collector being too eager and deleting things
|
||||
too early. This has been the subject of
|
||||
[PR #135](https://git.deuxfleurs.fr/Deuxfleurs/garage/pulls/135).
|
||||
This section summarizes the discussions on this topic.
|
||||
|
||||
#### Links
|
||||
Rationale: we want to ensure Garage's safety by making sure things don't get
|
||||
deleted from disk if they are still needed. Two aspects are involved in this.
|
||||
|
||||
### 1. Garbage collection of table entries (in `meta/` directory)
|
||||
|
||||
The `Entry` trait used for table entries (defined in `tables/schema.rs`)
|
||||
defines a function `is_tombstone()` that returns `true` if that entry
|
||||
represents an entry that is deleted in the table. CRDT semantics by default
|
||||
keep all tombstones, because they are necessary for reconciliation: if node A
|
||||
has a tombstone that supersedes a value `x`, and node B has value `x`, A has to
|
||||
keep the tombstone in memory so that the value `x` can be properly deleted at
|
||||
node `B`. Otherwise, due to the CRDT reconciliation rule, the value `x` from B
|
||||
would flow back to A and a deleted item would reappear in the system.
|
||||
|
||||
Here, we have some control on the nodes involved in storing Garage data.
|
||||
Therefore we have a garbage collector that is able to delete tombstones UNDER
|
||||
CERTAIN CONDITIONS. This garbage collector is implemented in `table/gc.rs`. To
|
||||
delete a tombstone, the following condition has to be met:
|
||||
|
||||
- All nodes responsible for storing this entry are aware of the existence of
|
||||
the tombstone, i.e. they cannot hold another version of the entry that is
|
||||
superseeded by the tombstone. This ensures that deleting the tombstone is
|
||||
safe and that no deleted value will come back in the system.
|
||||
|
||||
Garage makes use of Sled's atomic operations (such as compare-and-swap and
|
||||
transactions) to ensure that only tombstones that have been correctly
|
||||
propagated to other nodes are ever deleted from the local entry tree.
|
||||
|
||||
This GC is safe in the following sense: no non-tombstone data is ever deleted
|
||||
from Garage tables.
|
||||
|
||||
**However**, there is an issue with the way this interacts with data
|
||||
rebalancing in the case when a partition is moving between nodes. If a node has
|
||||
some data of a partition for which it is not responsible, it has to offload it.
|
||||
However that offload process takes some time. In that interval, the GC does not
|
||||
check with that node if it has the tombstone before deleting the tombstone, so
|
||||
perhaps it doesn't have it and when the offload finally happens, old data comes
|
||||
back in the system.
|
||||
|
||||
**PR 135 mostly fixes this** by implementing a 24-hour delay before anything is
|
||||
garbage collected in a table. This works under the assumption that rebalances
|
||||
that follow data shuffling terminate in less than 24 hours.
|
||||
|
||||
**However**, in distributed systems, it is generally considered a bad practice
|
||||
to make assumptions that information propagates in a certain time interval:
|
||||
this consists in making a synchrony assumption, meaning that we are basically
|
||||
assuming a computing model that has much stronger properties than otherwise. To
|
||||
maximize the applicability of Garage, we would like to remove this assumption,
|
||||
and implement a system where time does not play a role. To do this, we would
|
||||
need to find a way to safely disable the GC when data is being shuffled around,
|
||||
and safely detect that the shuffling has terminated and thus the GC can be
|
||||
resumed. This introduces some complexity to the protocol and hasn't been
|
||||
tackled yet.
|
||||
|
||||
### 2. Garbage collection of data blocks (in `data/` directory)
|
||||
|
||||
Blocks in the data directory are reference-counted. In Garage versions before
|
||||
PR #135, blocks could get deleted from local disk as soon as their reference
|
||||
counter reached zero. We had a mechanism to not trigger this immediately at the
|
||||
rc-reaches-zero event, but the cleanup could be triggered by other means (for
|
||||
example by a block repair operation...). PR #135 added a safety measure so that
|
||||
blocks never get deleted in a 10 minute interval following the time when the RC
|
||||
reaches zero. This is a measure to make impossible race conditions such as #39.
|
||||
We would have liked to use a larger delay (e.g. 24 hours), but in the case of a
|
||||
rebalance of data, this would have led to the disk utilization to explode
|
||||
during the rebalancing, only to shrink again after 24 hours. The 10-minute
|
||||
delay is a compromise that gives good security while not having this problem of
|
||||
disk space explosion on rebalance.
|
||||
|
||||
- CDC: <https://www.usenix.org/system/files/conference/atc16/atc16-paper-xia.pdf>
|
||||
- Erasure coding: <http://web.eecs.utk.edu/~jplank/plank/papers/CS-08-627.html>
|
||||
- [Openstack Storage Concepts](https://docs.openstack.org/arch-design/design-storage/design-storage-concepts.html)
|
||||
- [RADOS](https://ceph.com/wp-content/uploads/2016/08/weil-rados-pdsw07.pdf)
|
||||
|
||||
@@ -1,17 +1,145 @@
|
||||
# Setup your development environment
|
||||
|
||||
We propose the following quickstart to setup a full dev. environment as quickly as possible:
|
||||
Depending on your tastes, you can bootstrap your development environment in a traditional Rust way or through Nix.
|
||||
|
||||
1. Setup a rust/cargo environment. eg. `dnf install rust cargo`
|
||||
2. Install awscli v2 by following the guide [here](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html).
|
||||
3. Run `cargo build` to build the project
|
||||
4. Run `./script/dev-cluster.sh` to launch a test cluster (feel free to read the script)
|
||||
5. Run `./script/dev-configure.sh` to configure your test cluster with default values (same datacenter, 100 tokens)
|
||||
6. Run `./script/dev-bucket.sh` to create a bucket named `eprouvette` and an API key that will be stored in `/tmp/garage.s3`
|
||||
7. Run `source ./script/dev-env-aws.sh` to configure your CLI environment
|
||||
8. You can use `garage` to manage the cluster. Try `garage --help`.
|
||||
9. You can use the `awsgrg` alias to add, remove, and delete files. Try `awsgrg help`, `awsgrg cp /proc/cpuinfo s3://eprouvette/cpuinfo.txt`, or `awsgrg ls s3://eprouvette`. `awsgrg` is a wrapper on the `aws s3` command pre-configured with the previously generated API key (the one in `/tmp/garage.s3`) and localhost as the endpoint.
|
||||
## The Nix way
|
||||
|
||||
Now you should be ready to start hacking on garage!
|
||||
Nix is a generic package manager we use to precisely define our development environment.
|
||||
Instructions on how to install it are given on their [Download page](https://nixos.org/download.html).
|
||||
|
||||
Check that your installation is working by running the following commands:
|
||||
|
||||
```
|
||||
nix-shell --version
|
||||
nix-build --version
|
||||
nix-env --version
|
||||
```
|
||||
|
||||
Now, you can clone our git repository (run `nix-env -iA git` if you do not have git yet):
|
||||
|
||||
```bash
|
||||
git clone https://git.deuxfleurs.fr/Deuxfleurs/garage
|
||||
cd garage
|
||||
```
|
||||
|
||||
*Optionnaly, you can use our nix.conf file to speed up compilations:*
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /etc/nix
|
||||
sudo cp nix/nix.conf /etc/nix/nix.conf
|
||||
sudo killall nix-daemon
|
||||
```
|
||||
|
||||
Now you can enter our nix-shell, all the required packages will be downloaded but they will not pollute your environment outside of the shell:
|
||||
|
||||
```bash
|
||||
nix-shell
|
||||
```
|
||||
|
||||
You can use the traditionnal Rust development workflow:
|
||||
|
||||
```bash
|
||||
cargo build # compile the project
|
||||
cargo run # execute the project
|
||||
cargo test # run the tests
|
||||
cargo fmt # format the project, run it before any commit!
|
||||
cargo clippy # run the linter, run it before any commit!
|
||||
```
|
||||
|
||||
You can build the project with Nix by running:
|
||||
|
||||
```bash
|
||||
nix-build
|
||||
```
|
||||
|
||||
You can parallelize the build (if you use our nix.conf file, it is already automatically done).
|
||||
To use all your cores when building a derivation use `-j`, and to build multiple derivations at once use `--max-jobs`.
|
||||
The special value `auto` will be replaced by the number of cores of your computer.
|
||||
An example:
|
||||
|
||||
```bash
|
||||
nix-build -j $(nproc) --max-jobs auto
|
||||
```
|
||||
|
||||
Our build has multiple parameters you might want to set:
|
||||
- `release` build with release optimisations instead of debug
|
||||
- `target allows` for cross compilation
|
||||
- `compileMode` can be set to test or bench to build a unit test runner
|
||||
- `git_version` to inject the hash to display when running `garage stats`
|
||||
|
||||
An example:
|
||||
|
||||
```bash
|
||||
nix-build \
|
||||
--arg release true \
|
||||
--argstr target x86_64-unknown-linux-musl \
|
||||
--argstr compileMode build \
|
||||
--git_version $(git rev-parse HEAD)
|
||||
```
|
||||
|
||||
*The result is located in `result/bin`. You can pass arguments to cross compile: check `.drone.yml` for examples.*
|
||||
|
||||
If you modify a `Cargo.toml` or regenerate any `Cargo.lock`, you must run `cargo2nix`:
|
||||
|
||||
```
|
||||
cargo2nix -f
|
||||
```
|
||||
|
||||
Many tools like rclone, `mc` (minio-client), or `aws` (awscliv2) will be available in your environment and will be useful to test Garage.
|
||||
|
||||
**This is the recommended method.**
|
||||
|
||||
## The Rust way
|
||||
|
||||
You need a Rust distribution installed on your computer.
|
||||
The most simple way is to install it from [rustup](https://rustup.rs).
|
||||
Please avoid using your package manager to install Rust as some tools might be outdated or missing.
|
||||
|
||||
Now, check your Rust distribution works by running the following commands:
|
||||
|
||||
```bash
|
||||
rustc --version
|
||||
cargo --version
|
||||
rustfmt --version
|
||||
clippy-driver --version
|
||||
```
|
||||
|
||||
Now, you need to clone our git repository ([how to install git](https://git-scm.com/downloads)):
|
||||
|
||||
```bash
|
||||
git clone https://git.deuxfleurs.fr/Deuxfleurs/garage
|
||||
cd garage
|
||||
```
|
||||
|
||||
You can now use the following commands:
|
||||
|
||||
```bash
|
||||
cargo build # compile the project
|
||||
cargo run # execute the project
|
||||
cargo test # run the tests
|
||||
cargo fmt # format the project, run it before any commit!
|
||||
cargo clippy # run the linter, run it before any commit!
|
||||
```
|
||||
|
||||
This is specific to our project, but you will need one last tool, `cargo2nix`.
|
||||
To install it, run:
|
||||
|
||||
```bash
|
||||
cargo install --git https://github.com/superboum/cargo2nix --branch main cargo2nix
|
||||
```
|
||||
|
||||
You must use it every time you modify a `Cargo.toml` or regenerate a `Cargo.lock` file as follow:
|
||||
|
||||
```bash
|
||||
cargo build # Rebuild Cargo.lock if needed
|
||||
cargo2nix -f
|
||||
```
|
||||
|
||||
It will output a `Cargo.nix` file which is a specific `Cargo.lock` file dedicated to Nix that is required by our CI
|
||||
which means you must include it in your commits.
|
||||
|
||||
Later, to use our scripts and integration tests, you might need additional tools.
|
||||
These tools are listed at the end of the `shell.nix` package in the `nativeBuildInputs` part.
|
||||
It is up to you to find a way to install the ones you need on your computer.
|
||||
|
||||
**A global drawback of this method is that it is up to you to adapt your environment to the one defined in the Nix files.**
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# Miscellaneous Notes
|
||||
|
||||
## Quirks about cargo2nix/rust in Nix
|
||||
|
||||
If you use submodules in your crate (like `crdt` and `replication` in `garage_table`), you must list them in `default.nix`
|
||||
|
||||
The Windows target does not work. it might be solvable through [overrides](https://github.com/cargo2nix/cargo2nix/blob/master/overlay/overrides.nix). Indeed, we pass `x86_64-pc-windows-gnu` but mingw need `x86_64-w64-mingw32`
|
||||
|
||||
We have a simple [PR on cargo2nix](https://github.com/cargo2nix/cargo2nix/pull/201) that fixes critical bugs but the project does not seem very active currently. We must use [my patched version of cargo2nix](https://github.com/superboum/cargo2nix) to enable i686 and armv6l compilation. We might need to contribute to cargo2nix in the future.
|
||||
|
||||
|
||||
## Nix
|
||||
|
||||
Nix has no armv7 + musl toolchains but armv7l is backward compatible with armv6l.
|
||||
|
||||
Signing keys are generated with:
|
||||
|
||||
```
|
||||
nix-store --generate-binary-cache-key nix.web.deuxfleurs.fr cache-priv-key.pem cache-pub-key.pem
|
||||
```
|
||||
|
||||
We copy the secret key in our nix folder:
|
||||
|
||||
```
|
||||
cp cache-priv-key.pem /etc/nix/signing-key.sec
|
||||
```
|
||||
|
||||
Manually sign
|
||||
|
||||
We can sign the whole store with:
|
||||
|
||||
```
|
||||
nix sign-paths --all -k /etc/nix/signing-key.sec
|
||||
```
|
||||
|
||||
Or simply the current package and its dependencies with:
|
||||
|
||||
```
|
||||
nix sign-paths --recursive -k /etc/nix/signing-key.sec
|
||||
```
|
||||
|
||||
Setting a key in `nix.conf` will do the signature at build time automatically without additional commands, edit the `nix.conf` of your builder:
|
||||
|
||||
```toml
|
||||
secret-key-files = /etc/nix/signing-key.sec
|
||||
max-jobs = auto
|
||||
cores = 8
|
||||
```
|
||||
|
||||
Now you are ready to build your packages:
|
||||
|
||||
```bash
|
||||
cat > $HOME/.awsrc <<EOF
|
||||
export AWS_ACCESS_KEY_ID="xxx"
|
||||
export AWS_SECRET_ACCESS_KEY="xxx"
|
||||
EOF
|
||||
|
||||
# source each time you want to send on the cache
|
||||
source ~/.awsrc
|
||||
|
||||
# copy garage build dependencies (and not only the output)
|
||||
nix-build
|
||||
nix-store -qR --include-outputs $(nix-instantiate default.nix)
|
||||
| xargs nix copy --to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage'
|
||||
|
||||
# copy shell dependencies
|
||||
nix-build shell.nix -A inputDerivation
|
||||
nix copy $(nix-store -qR result/) --to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage'
|
||||
```
|
||||
|
||||
More example of nix-copy
|
||||
|
||||
```
|
||||
# nix-build produces a result/ symlink
|
||||
nix copy result/ --to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage'
|
||||
|
||||
# alternative ways to use nix copy
|
||||
nix copy nixpkgs.garage --to ...
|
||||
nix copy /nix/store/3rbb9qsc2w6xl5xccz5ncfhy33nzv3dp-crate-garage-0.3.0 --to ...
|
||||
```
|
||||
|
||||
|
||||
Clear the cache:
|
||||
|
||||
```bash
|
||||
mc rm --recursive --force garage/nix/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
A desirable `nix.conf` for a consumer:
|
||||
|
||||
```toml
|
||||
substituters = https://cache.nixos.org https://nix.web.deuxfleurs.fr
|
||||
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= nix.web.deuxfleurs.fr:eTGL6kvaQn6cDR/F9lDYUIP9nCVR/kkshYfLDJf1yKs=
|
||||
```
|
||||
|
||||
And now, whenever you run a command like:
|
||||
|
||||
```
|
||||
nix-shell
|
||||
nix-build
|
||||
```
|
||||
|
||||
Our cache will be checked.
|
||||
|
||||
### Some references about Nix
|
||||
|
||||
|
||||
- https://doc.rust-lang.org/nightly/rustc/platform-support.html
|
||||
- https://nix.dev/tutorials/cross-compilation
|
||||
- https://nixos.org/manual/nix/unstable/package-management/s3-substituter.html
|
||||
- https://fzakaria.com/2020/09/28/nix-copy-closure-your-nix-shell.html
|
||||
- http://www.lpenz.org/articles/nixchannel/index.html
|
||||
|
||||
|
||||
## Drone
|
||||
|
||||
Do not try to set a build as trusted from the interface or the CLI tool,
|
||||
your request would be ignored. Instead, directly edit the database (table `repos`, column `repo_trusted`).
|
||||
|
||||
Drone can do parallelism both at the step and the pipeline level. At the step level, parallelism is restricted to the same runner.
|
||||
|
||||
## Building Docker containers
|
||||
|
||||
We were:
|
||||
- Unable to use the official Docker plugin because
|
||||
- it requires to mount docker socket in the container but it is not recommended
|
||||
- you cant set the platform when building
|
||||
- Unable to use buildah because it needs `CLONE_USERNS` capability
|
||||
- Unable to use the kaniko plugin for Drone as we can't set the target platform
|
||||
- Unable to use the kaniko container provided by Google as we can't run arbitrary logic: we need to put our secret in .docker/config.json.
|
||||
|
||||
Finally we chose to build kaniko through nix and use it in a `nix-shell`.
|
||||
@@ -0,0 +1,195 @@
|
||||
# Release process
|
||||
|
||||
Before releasing a new version of Garage, our code pass through a succession of checks and transformations.
|
||||
We define them as our release process.
|
||||
|
||||
## Trigger and classify a release
|
||||
|
||||
While we run some tests on every commits, we do not make a release for all of them.
|
||||
|
||||
A release can be triggered manually by "promoting" a successful build.
|
||||
Otherwise, every weeks, a release build is triggered on the `main` branch.
|
||||
|
||||
If the build is from a tag following the regex: `v[0-9]+\.[0-9]+\.[0-9]+`, it will be listed as stable.
|
||||
If it is a tag but with a different format, it will be listed as Extra.
|
||||
Otherwise, if it is a commit, it will be listed as development.
|
||||
This logic is defined in `nix/build_index.nix`.
|
||||
|
||||
## Testing
|
||||
|
||||
For each commit, we first pass the code to a formatter (rustfmt) and a linter (clippy).
|
||||
Then we try to build it in debug mode and run both unit tests and our integration tests.
|
||||
|
||||
Additionnaly, when releasing, our integration tests are run on the release build for amd64 and i686.
|
||||
|
||||
## Generated Artifacts
|
||||
|
||||
We generate the following binary artifacts for now:
|
||||
- **architecture**: amd64, i686, aarch64, armv6
|
||||
- **os**: linux
|
||||
- **format**: static binary, docker container
|
||||
|
||||
Additionnaly we also build two web pages:
|
||||
- the documentation (this website)
|
||||
- [the release page](https://garagehq.deuxfleurs.fr/releases.html)
|
||||
|
||||
We publish the static binaries on our own garage cluster (you can access them through the releases page)
|
||||
and the docker containers on Docker Hub.
|
||||
|
||||
## Automation
|
||||
|
||||
We automated our release process with Nix and Drone to make it more reliable.
|
||||
Here we describe how we have done in case you want to debug or improve it.
|
||||
|
||||
### Caching build steps
|
||||
|
||||
To speed up the CI, we use the caching feature provided by Nix.
|
||||
|
||||
You can benefit from it by using our provided `nix.conf` as recommended or by simply adding the following lines to your file:
|
||||
|
||||
```toml
|
||||
substituters = https://cache.nixos.org https://nix.web.deuxfleurs.fr
|
||||
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= nix.web.deuxfleurs.fr:eTGL6kvaQn6cDR/F9lDYUIP9nCVR/kkshYfLDJf1yKs=
|
||||
```
|
||||
|
||||
Sending to the cache is done through `nix copy`, for example:
|
||||
|
||||
```bash
|
||||
nix copy --to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage&secret-key=/etc/nix/signing-key.sec' result
|
||||
```
|
||||
|
||||
*Note that you need the signing key. In our case, it is stored as a secret in Drone.*
|
||||
|
||||
The previous command will only send the built packet and not its dependencies.
|
||||
To send its dependency, a tool named `nix-copy-closure` has been created but it is not compatible with the S3 protocol.
|
||||
|
||||
Instead, you can use the following commands to list all the runtime dependencies:
|
||||
|
||||
```bash
|
||||
nix copy \
|
||||
--to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage&secret-key=/etc/nix/signing-key.sec' \
|
||||
$(nix-store -qR result/)
|
||||
```
|
||||
|
||||
*We could also write this expression with xargs but this tool is not available in our container.*
|
||||
|
||||
But in certain cases, we want to cache compile time dependencies also.
|
||||
For example, the Nix project does not provide binaries for cross compiling to i686 and thus we need to compile gcc on our own.
|
||||
We do not want to compile gcc each time, so even if it is a compile time dependency, we want to cache it.
|
||||
|
||||
This time, the command is a bit more involved:
|
||||
|
||||
```bash
|
||||
nix copy --to \
|
||||
's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage&secret-key=/etc/nix/signing-key.sec' \
|
||||
$(nix-store -qR --include-outputs \
|
||||
$(nix-instantiate))
|
||||
```
|
||||
|
||||
This is the command we use in our CI as we expect the final binary to change, so we mainly focus on
|
||||
caching our development dependencies.
|
||||
|
||||
*Currently there is no automatic garbage collection of the cache: we should monitor its growth.
|
||||
Hopefully, we can erase it totally without breaking any build, the next build will only be slower.*
|
||||
|
||||
In practise, we concluded that we do not want to cache all the compilation dependencies.
|
||||
Instead, we want to cache the toolchain we use to build Garage each time we change it.
|
||||
So we removed from Drone any automatic update of the cache and instead handle them manually with:
|
||||
|
||||
```
|
||||
source ~/.awsrc
|
||||
nix-shell --run 'refresh_toolchain'
|
||||
```
|
||||
|
||||
Internally, it will run `nix-build` on `nix/toolchain.nix` and send the output plus its depedencies to the cache.
|
||||
|
||||
To erase the cache:
|
||||
|
||||
```
|
||||
mc rm --recursive --force 'garage/nix/'
|
||||
```
|
||||
|
||||
### Publishing Garage
|
||||
|
||||
We defined our publishing logic in Nix, mostly as shell hooks.
|
||||
You can inspect them in `shell.nix` to see exactly how.
|
||||
Here, we will give a quick explanation on how to use them to manually publish a release.
|
||||
|
||||
Supposing you just have built garage as follow:
|
||||
|
||||
```bash
|
||||
nix-build --arg release true
|
||||
```
|
||||
|
||||
To publish a static binary in `result/bin` on garagehq, run:
|
||||
|
||||
```bash
|
||||
export AWS_ACCESS_KEY_ID=xxx
|
||||
export AWS_SECRET_ACCESS_KEY=xxx
|
||||
export DRONE_TAG=handcrafted-1.0.0 # or DRONE_COMMIT
|
||||
export TARGET=x86_64-unknown-linux-musl
|
||||
|
||||
nix-shell --run to_s3
|
||||
```
|
||||
|
||||
To create and publish a docker container, run:
|
||||
|
||||
```bash
|
||||
export DOCKER_AUTH='{ "auths": { "https://index.docker.io/v1/": { "auth": "xxxx" }}}'
|
||||
export DOCKER_PLATFORM='linux/amd64' # check GOARCH and GOOS from golang.org
|
||||
export CONTAINER_NAME='me/amd64_garage'
|
||||
export CONTAINER_TAG='handcrafted-1.0.0'
|
||||
|
||||
nix-shell --run to_docker
|
||||
```
|
||||
|
||||
To rebuild the release page, run:
|
||||
```bash
|
||||
export AWS_ACCESS_KEY_ID=xxx
|
||||
export AWS_SECRET_ACCESS_KEY=xxx
|
||||
|
||||
nix-shell --run refresh_index
|
||||
```
|
||||
|
||||
If you want to compile for different architectures, you will need to repeat all these commands for each architecture.
|
||||
|
||||
**In practise, and except for debugging, you will never directly run these commands. Release is handled by drone**
|
||||
|
||||
### Drone
|
||||
|
||||
Our instance is available at [https://drone.deuxfleurs.fr](https://drone.deuxfleurs.fr).
|
||||
You need an account on [https://git.deuxfleurs.fr](https://git.deuxfleurs.fr) to use it.
|
||||
|
||||
**Drone CLI** - Drone has a CLI tool to interact with.
|
||||
It can be downloaded from its Github [release page](https://github.com/drone/drone-cli/releases).
|
||||
|
||||
To communicate with our instance, you must setup some environment variables.
|
||||
You can get them from your [Account Settings](https://drone.deuxfleurs.fr/account).
|
||||
|
||||
To make drone easier to use, you could create a `~/.dronerc` that you could source each time you want to use it.
|
||||
|
||||
```
|
||||
export DRONE_SERVER=https://drone.deuxfleurs.fr
|
||||
export DRONE_TOKEN=xxx
|
||||
drone info
|
||||
```
|
||||
|
||||
The CLI tool is very self-discoverable, just append `--help` to each subcommands.
|
||||
Start with:
|
||||
|
||||
```bash
|
||||
drone --help
|
||||
```
|
||||
|
||||
**.drone.yml** - The builds steps are defined in `.drone.yml`.
|
||||
You can not edit this file without resigning it.
|
||||
|
||||
To sign it, you must be a maintainer and then run:
|
||||
|
||||
```bash
|
||||
drone sign --save Deuxfleurs/garage
|
||||
```
|
||||
|
||||
Looking at the file, you will see that most of the commands are `nix-shell` and `nix-build` commands with various parameters.
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# Development scripts
|
||||
|
||||
We maintain a `script/` folder that contains some useful script to ease testing on Garage.
|
||||
|
||||
A fully integrated script, `test-smoke.sh`, runs some basic tests on various tools such as minio client, awscli and rclone.
|
||||
To run it, enter a `nix-shell` (or install all required tools) and simply run:
|
||||
|
||||
```bash
|
||||
nix-build # or cargo build
|
||||
./script/test-smoke.sh
|
||||
```
|
||||
|
||||
If something fails, you can find useful logs in `/tmp/garage.log`.
|
||||
You can inspect the generated configuration and local data created by inspecting your `/tmp` directory:
|
||||
the script creates files and folder prefixed with the name "garage".
|
||||
|
||||
## Bootstrapping a test cluster
|
||||
|
||||
Under the hood `test-smoke.sh` uses multiple helpers scripts you can also run in case you want to manually test Garage.
|
||||
In this section, we introduce 3 scripts to quickly bootstrap a full test cluster with 3 instances.
|
||||
|
||||
### 1. Start each daemon
|
||||
|
||||
```bash
|
||||
./script/dev-cluster.sh
|
||||
```
|
||||
|
||||
This script spawns 3 Garage instances with 3 configuration files.
|
||||
You can inspect the detailed configuration, including ports, by inspecting `/tmp/config.1` (change 1 by the instance number you want).
|
||||
|
||||
This script also spawns a simple HTTPS reverse proxy through `socat` for the S3 endpoint that listens on port `4443`.
|
||||
Some libraries might require a TLS endpoint to work, refer to our issue [#64](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/64) for more detailed information on this subject.
|
||||
|
||||
This script covers the [Launching the garage server](/quick_start/index.html#launching-the-garage-server) section of our Quick start page.
|
||||
|
||||
### 2. Make them join the cluster
|
||||
|
||||
```bash
|
||||
./script/dev-configure.sh
|
||||
```
|
||||
|
||||
This script will configure each instance by assigning them a zone (`dc1`) and a weight (`1`).
|
||||
|
||||
This script covers the [Configuring your Garage node](/quick_start/index.html#configuring-your-garage-node) section of our Quick start page.
|
||||
|
||||
### 3. Create a key and a bucket
|
||||
|
||||
```bash
|
||||
./script/dev-bucket.sh
|
||||
```
|
||||
|
||||
This script will create a bucket named `eprouvette` with a key having read and write rights on this bucket.
|
||||
The key is stored in a filed named `/tmp/garage.s3` and can be used by the following tools to pre-configure them.
|
||||
|
||||
This script covers the [Creating buckets and keys](/quick_start/index.html#creating-buckets-and-keys) section of our Quick start page.
|
||||
|
||||
## Handlers for generic tools
|
||||
|
||||
We provide wrappers for some CLI tools that configure themselves for your development cluster.
|
||||
They are meant to save you some configuration time as to use them, you are only required to source the right file.
|
||||
|
||||
### awscli
|
||||
|
||||
```bash
|
||||
source ./script/dev-env-aws.sh
|
||||
|
||||
# some examples
|
||||
aws s3 ls s3://eprouvette
|
||||
aws s3 cp /proc/cpuinfo s3://eprouvette/cpuinfo.txt
|
||||
```
|
||||
|
||||
### minio-client
|
||||
|
||||
|
||||
```bash
|
||||
source ./script/dev-env-mc.sh
|
||||
|
||||
# some examples
|
||||
mc ls garage/
|
||||
mc cp /proc/cpuinfo garage/eprouvette/cpuinfo.txt
|
||||
```
|
||||
|
||||
### rclone
|
||||
|
||||
```bash
|
||||
source ./script/dev-env-rclone.sh
|
||||
|
||||
# some examples
|
||||
rclone lsd garage:
|
||||
rclone copy /proc/cpuinfo garage:eprouvette/cpuinfo.txt
|
||||
```
|
||||
|
||||
### s3cmd
|
||||
|
||||
```bash
|
||||
source ./script/dev-env-s3cmd.sh
|
||||
|
||||
# some examples
|
||||
s3cmd ls
|
||||
s3cmd put /proc/cpuinfo s3://eprouvette/cpuinfo.txt
|
||||
```
|
||||
|
||||
### duck
|
||||
|
||||
*Warning! Duck is not yet provided by nix-shell.*
|
||||
|
||||
```bash
|
||||
source ./script/dev-env-duck.sh
|
||||
|
||||
# some examples
|
||||
duck --list garage:/
|
||||
duck --upload garage:/eprouvette/ /proc/cpuinfo
|
||||
```
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
+18
-2
@@ -5,7 +5,8 @@
|
||||
</p>
|
||||
|
||||
<p align="center" style="text-align:center;">
|
||||
[ <a href="https://git.deuxfleurs.fr/Deuxfleurs/garage">Git repository</a>
|
||||
[ <a href="https://garagehq.deuxfleurs.fr/_releases.html">Download</a>
|
||||
| <a href="https://git.deuxfleurs.fr/Deuxfleurs/garage">Git repository</a>
|
||||
| <a href="https://matrix.to/#/%23garage:deuxfleurs.fr">Matrix channel</a>
|
||||
| <a href="https://drone.deuxfleurs.fr/Deuxfleurs/garage">Drone CI</a>
|
||||
]
|
||||
@@ -70,7 +71,7 @@ We also do not classify Swift as *Simple*.
|
||||
**[Ceph](https://ceph.io/ceph-storage/object-storage/):**
|
||||
This review holds for the whole Ceph stack, including the RADOS paper, Ceph Object Storage module, the RADOS Gateway, etc.
|
||||
At its core, Ceph has been designed to provide *POSIX/Filesystem compatibility* which requires strong consistency, which in turn
|
||||
makes Ceph latency-sensitive and fails our *Internet enabled* goal.
|
||||
makes Ceph latency-sensitive and fails our *Internet enabled* goal.
|
||||
Due to its industry oriented design, Ceph is also far from being *Simple* to operate and from being *Self-contained & lightweight* which makes it hard to integrate it in an hyperconverged infrastructure.
|
||||
In a certain way, Ceph and MinIO are closer together than they are from Garage or OpenStack Swift.
|
||||
|
||||
@@ -111,3 +112,18 @@ Our code repository and issue tracker, which is the place where you should repor
|
||||
|
||||
Garage's source code, is released under the [AGPL v3 License](https://www.gnu.org/licenses/agpl-3.0.en.html).
|
||||
Please note that if you patch Garage and then use it to provide any service over a network, you must share your code!
|
||||
|
||||
# Funding
|
||||
|
||||
The Deuxfleurs association has received a grant from [NGI POINTER](https://pointer.ngi.eu/), to fund 3 people working on Garage full-time for a year: from October 2021 to September 2022.
|
||||
|
||||
<div style="display: flex; justify-content: space-around">
|
||||
<a href="https://pointer.ngi.eu/">
|
||||
<img style="height:100px" src="img/ngi-logo.png" alt="NGI Pointer logo">
|
||||
</a>
|
||||
<a href="https://ec.europa.eu/programmes/horizon2020/what-horizon-2020">
|
||||
<img style="height:100px" src="img/eu-flag-logo.png" alt="EU flag logo">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
_This project has received funding from the European Union’s Horizon 2020 research and innovation programme within the framework of the NGI-POINTER Project funded under grant agreement N° 871528._
|
||||
|
||||
@@ -10,8 +10,6 @@ Following this guide is recommended before moving on to
|
||||
|
||||
Note that this kind of deployment should not be used in production, as it provides
|
||||
no redundancy for your data!
|
||||
We will also skip intra-cluster TLS configuration, meaning that if you add nodes
|
||||
to your cluster, communication between them will not be secure.
|
||||
|
||||
## Get a binary
|
||||
|
||||
@@ -30,7 +28,10 @@ you can [build Garage from source](../cookbook/from_source.md).
|
||||
## Writing a first configuration file
|
||||
|
||||
This first configuration file should allow you to get started easily with the simplest
|
||||
possible Garage deployment:
|
||||
possible Garage deployment.
|
||||
**Save it as `/etc/garage.toml`.**
|
||||
You can also store it somewhere else, but you will have to specify `-c path/to/garage.toml`
|
||||
at each invocation of the `garage` binary (for example: `garage -c ./garage.toml server`, `garage -c ./garage.toml status`).
|
||||
|
||||
```toml
|
||||
metadata_dir = "/tmp/meta"
|
||||
@@ -39,10 +40,10 @@ data_dir = "/tmp/data"
|
||||
replication_mode = "none"
|
||||
|
||||
rpc_bind_addr = "[::]:3901"
|
||||
rpc_public_addr = "127.0.0.1:3901"
|
||||
rpc_secret = "1799bccfd7411eddcf9ebd316bc1f5287ad12a68094e1c6ac6abde7e6feae1ec"
|
||||
|
||||
bootstrap_peers = [
|
||||
"127.0.0.1:3901",
|
||||
]
|
||||
bootstrap_peers = []
|
||||
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
@@ -54,7 +55,10 @@ root_domain = ".web.garage"
|
||||
index = "index.html"
|
||||
```
|
||||
|
||||
Save your configuration file as `garage.toml`.
|
||||
The `rpc_secret` value provided above is just an example. It will work, but in
|
||||
order to secure your cluster you will need to use another one. You can generate
|
||||
such a value with `openssl rand -hex 32`.
|
||||
|
||||
|
||||
As you can see in the `metadata_dir` and `data_dir` parameters, we are saving Garage's data
|
||||
in `/tmp` which gets erased when your system reboots. This means that data stored on this
|
||||
@@ -67,15 +71,15 @@ your data to be persisted properly.
|
||||
Use the following command to launch the Garage server with our configuration file:
|
||||
|
||||
```
|
||||
RUST_LOG=garage=info garage server -c garage.toml
|
||||
RUST_LOG=garage=info garage server
|
||||
```
|
||||
|
||||
You can tune Garage's verbosity as follows (from less verbose to more verbose):
|
||||
|
||||
```
|
||||
RUST_LOG=garage=info garage server -c garage.toml
|
||||
RUST_LOG=garage=debug garage server -c garage.toml
|
||||
RUST_LOG=garage=trace garage server -c garage.toml
|
||||
RUST_LOG=garage=info garage server
|
||||
RUST_LOG=garage=debug garage server
|
||||
RUST_LOG=garage=trace garage server
|
||||
```
|
||||
|
||||
Log level `info` is recommended for most use cases.
|
||||
@@ -85,11 +89,12 @@ Log level `debug` can help you check why your S3 API calls are not working.
|
||||
## Checking that Garage runs correctly
|
||||
|
||||
The `garage` utility is also used as a CLI tool to configure your Garage deployment.
|
||||
It tries to connect to a Garage server through the RPC protocol, by default looking
|
||||
for a Garage server at `localhost:3901`.
|
||||
It uses values from the TOML configuration file to find the Garage daemon running on the
|
||||
local node, therefore if your configuration file is not at `/etc/garage.toml` you will
|
||||
again have to specify `-c path/to/garage.toml`.
|
||||
|
||||
Since our deployment already binds to port 3901, the following command should be sufficient
|
||||
to show Garage's status:
|
||||
If the `garage` CLI is able to correctly detect the parameters of your local Garage node,
|
||||
the following command should be enough to show the status of your cluster:
|
||||
|
||||
```
|
||||
garage status
|
||||
@@ -98,8 +103,9 @@ garage status
|
||||
This should show something like this:
|
||||
|
||||
```
|
||||
Healthy nodes:
|
||||
2a638ed6c775b69a… linuxbox 127.0.0.1:3901 UNCONFIGURED/REMOVED
|
||||
==== HEALTHY NODES ====
|
||||
ID Hostname Address Tag Zone Capacity
|
||||
563e1ac825ee3323… linuxbox 127.0.0.1:3901 NO ROLE ASSIGNED
|
||||
```
|
||||
|
||||
## Configuring your Garage node
|
||||
@@ -117,7 +123,7 @@ garage node configure -z dc1 -c 1 <node_id>
|
||||
|
||||
where `<node_id>` corresponds to the identifier of the node shown by `garage status` (first column).
|
||||
You can enter simply a prefix of that identifier.
|
||||
For instance here you could write just `garage node configure -z dc1 -c 1 2a63`.
|
||||
For instance here you could write just `garage node configure -z dc1 -c 1 563e`.
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -10,31 +10,26 @@ block_size = 1048576
|
||||
|
||||
replication_mode = "3"
|
||||
|
||||
rpc_secret = "4425f5c26c5e11581d3223904324dcb5b5d5dfb14e5e7f35e38c595424f5f1e6"
|
||||
rpc_bind_addr = "[::]:3901"
|
||||
rpc_public_addr = "[fc00:1::1]:3901"
|
||||
|
||||
bootstrap_peers = [
|
||||
"[fc00:1::1]:3901",
|
||||
"[fc00:1::2]:3901",
|
||||
"[fc00:B::1]:3901",
|
||||
"[fc00:F::1]:3901",
|
||||
"563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d@[fc00:1::1]:3901",
|
||||
"86f0f26ae4afbd59aaf9cfb059eefac844951efd5b8caeec0d53f4ed6c85f332[fc00:1::2]:3901",
|
||||
"681456ab91350f92242e80a531a3ec9392cb7c974f72640112f90a600d7921a4@[fc00:B::1]:3901",
|
||||
"212fd62eeaca72c122b45a7f4fa0f55e012aa5e24ac384a72a3016413fa724ff@[fc00:F::1]:3901",
|
||||
]
|
||||
|
||||
consul_host = "consul.service"
|
||||
consul_service_name = "garage-daemon"
|
||||
|
||||
max_concurrent_rpc_requests = 12
|
||||
|
||||
sled_cache_capacity = 134217728
|
||||
sled_flush_every_ms = 2000
|
||||
|
||||
[rpc_tls]
|
||||
ca_cert = "/etc/garage/pki/garage-ca.crt"
|
||||
node_cert = "/etc/garage/pki/garage.crt"
|
||||
node_key = "/etc/garage/pki/garage.key"
|
||||
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
api_bind_addr = "[::]:3900"
|
||||
s3_region = "garage"
|
||||
|
||||
[s3_web]
|
||||
bind_addr = "[::]:3902"
|
||||
@@ -63,10 +58,15 @@ when [configuring it](../getting_started/05_cluster.md).
|
||||
|
||||
#### `block_size`
|
||||
|
||||
Garage splits stored objects in consecutive chunks of size `block_size` (except the last
|
||||
one which might be standard). The default size is 1MB and should work in most cases.
|
||||
If you are interested in tuning this, feel free to do so (and remember to report your
|
||||
findings to us!)
|
||||
Garage splits stored objects in consecutive chunks of size `block_size`
|
||||
(except the last one which might be smaller). The default size is 1MB and
|
||||
should work in most cases. If you are interested in tuning this, feel free
|
||||
to do so (and remember to report your findings to us!). If this value is
|
||||
changed for a running Garage installation, only files newly uploaded will be
|
||||
affected. Previously uploaded files will remain available. This however
|
||||
means that chunks from existing files will not be deduplicated with chunks
|
||||
from newly uploaded files, meaning you might use more storage space that is
|
||||
optimally possible.
|
||||
|
||||
#### `replication_mode`
|
||||
|
||||
@@ -97,6 +97,14 @@ Never run a Garage cluster where that is not the case.**
|
||||
Changing the `replication_mode` of a cluster might work (make sure to shut down all nodes
|
||||
and changing it everywhere at the time), but is not officially supported.
|
||||
|
||||
#### `rpc_secret`
|
||||
|
||||
Garage uses a secret key that is shared between all nodes of the cluster
|
||||
in order to identify these nodes and allow them to communicate together.
|
||||
This key should be specified here in the form of a 32-byte hex-encoded
|
||||
random string. Such a string can be generated with a command
|
||||
such as `openssl rand -hex 32`.
|
||||
|
||||
#### `rpc_bind_addr`
|
||||
|
||||
The address and port on which to bind for inter-cluster communcations
|
||||
@@ -106,10 +114,28 @@ the node, even in the case of a NAT: the NAT should be configured to forward the
|
||||
port number to the same internal port nubmer. This means that if you have several nodes running
|
||||
behind a NAT, they should each use a different RPC port number.
|
||||
|
||||
#### `rpc_public_addr`
|
||||
|
||||
The address and port that other nodes need to use to contact this node for
|
||||
RPC calls. **This parameter is optional but recommended.** In case you have
|
||||
a NAT that binds the RPC port to a port that is different on your public IP,
|
||||
this field might help making it work.
|
||||
|
||||
#### `bootstrap_peers`
|
||||
|
||||
A list of IPs and ports on which to contact other Garage peers of this cluster.
|
||||
This should correspond to the RPC ports set up with `rpc_bind_addr`.
|
||||
A list of peer identifiers on which to contact other Garage peers of this cluster.
|
||||
These peer identifiers have the following syntax:
|
||||
|
||||
```
|
||||
<node public key>@<node public IP or hostname>:<port>
|
||||
```
|
||||
|
||||
In the case where `rpc_public_addr` is correctly specified in the
|
||||
configuration file, the full identifier of a node including IP and port can
|
||||
be obtained by running `garage node-id` and then included directly in the
|
||||
`bootstrap_peers` list of other nodes. Otherwise, only the node's public
|
||||
key will be returned by `garage node-id` and you will have to add the IP
|
||||
yourself.
|
||||
|
||||
#### `consul_host` and `consul_service_name`
|
||||
|
||||
@@ -121,12 +147,6 @@ The `consul_host` parameter should be set to the hostname of the Consul server,
|
||||
and `consul_service_name` should be set to the service name under which Garage's
|
||||
RPC ports are announced.
|
||||
|
||||
#### `max_concurrent_rpc_requests`
|
||||
|
||||
Garage implements rate limiting for RPC requests: no more than
|
||||
`max_concurrent_rpc_requests` concurrent outbound RPC requests will be made
|
||||
by a Garage node (additionnal requests will be put in a waiting queue).
|
||||
|
||||
#### `sled_cache_capacity`
|
||||
|
||||
This parameter can be used to tune the capacity of the cache used by
|
||||
@@ -143,21 +163,6 @@ of a power outage (though this should not matter much as data is replicated on o
|
||||
nodes). The default value, 2000ms, should be appropriate for most use cases.
|
||||
|
||||
|
||||
## The `[rpc_tls]` section
|
||||
|
||||
This section should be used to configure the TLS certificates used to encrypt
|
||||
intra-cluster traffic (RPC traffic). The following parameters should be set:
|
||||
|
||||
- `ca_cert`: the certificate of the CA that is allowed to sign individual node certificates
|
||||
- `node_cert`: the node certificate for the current node
|
||||
- `node_key`: the key associated with the node certificate
|
||||
|
||||
Note tha several nodes may use the same node certificate, as long as it is signed
|
||||
by the CA.
|
||||
|
||||
If this section is absent, TLS is not used to encrypt intra-cluster traffic.
|
||||
|
||||
|
||||
## The `[s3_api]` section
|
||||
|
||||
#### `api_bind_addr`
|
||||
|
||||
@@ -23,76 +23,35 @@ Not implemented:
|
||||
|
||||
All APIs that are not mentionned are not implemented and will return a 400 bad request.
|
||||
|
||||
#### AbortMultipartUpload
|
||||
| Endpoint | Status |
|
||||
|------------------------------|----------------------------------|
|
||||
| AbortMultipartUpload | Implemented |
|
||||
| CompleteMultipartUpload | Implemented |
|
||||
| CopyObject | Implemented |
|
||||
| CreateBucket | Unsupported, stub (see below) |
|
||||
| CreateMultipartUpload | Implemented |
|
||||
| DeleteBucket | Unsupported (see below) |
|
||||
| DeleteObject | Implemented |
|
||||
| DeleteObjects | Implemented |
|
||||
| GetBucketLocation | Implemented |
|
||||
| GetBucketVersioning | Stub (see below) |
|
||||
| GetObject | Implemented |
|
||||
| HeadBucket | Implemented |
|
||||
| HeadObject | Implemented |
|
||||
| ListBuckets | Implemented |
|
||||
| ListObjects | Implemented, bugs? (see below) |
|
||||
| ListObjectsV2 | Implemented |
|
||||
| PutObject | Implemented |
|
||||
| UploadPart | Implemented |
|
||||
|
||||
Implemented.
|
||||
|
||||
#### CompleteMultipartUpload
|
||||
|
||||
Implemented badly. Garage will not check that all the parts stored correspond to the list given by the client in the request body. This means that the multipart upload might be completed with an invalid size. This is a bug and will be fixed.
|
||||
- **CreateBucket:** Garage does not yet accept creating buckets or giving access using API calls, it has to be done using the CLI tools. CreateBucket will return a 200 if the bucket exists and user has write access, and a 403 Forbidden in all other cases.
|
||||
|
||||
#### CopyObject
|
||||
- **DeleteBucket:** Garage does not yet accept deleting buckets using API calls, it has to be done using the CLI tools. This request will return a 403 Forbidden.
|
||||
|
||||
Implemented.
|
||||
|
||||
#### CreateBucket
|
||||
|
||||
Garage does not accept creating buckets or giving access using API calls, it has to be done using the CLI tools. CreateBucket will return a 200 if the bucket exists and user has write access, and a 403 Forbidden in all other cases.
|
||||
|
||||
#### CreateMultipartUpload
|
||||
|
||||
Implemented.
|
||||
|
||||
#### DeleteBucket
|
||||
|
||||
Garage does not accept deleting buckets using API calls, it has to be done using the CLI tools. This request will return a 403 Forbidden.
|
||||
|
||||
#### DeleteObject
|
||||
|
||||
Implemented.
|
||||
|
||||
#### DeleteObjects
|
||||
|
||||
Implemented.
|
||||
|
||||
#### GetBucketLocation
|
||||
|
||||
Implemented.
|
||||
|
||||
#### GetBucketVersioning
|
||||
|
||||
Stub implementation (Garage does not yet support versionning so this always returns
|
||||
- **GetBucketVersioning:** Stub implementation (Garage does not yet support versionning so this always returns
|
||||
"versionning not enabled").
|
||||
|
||||
#### GetObject
|
||||
|
||||
Implemented.
|
||||
|
||||
#### HeadBucket
|
||||
|
||||
Implemented.
|
||||
|
||||
#### HeadObject
|
||||
|
||||
Implemented.
|
||||
|
||||
#### ListBuckets
|
||||
|
||||
Implemented.
|
||||
|
||||
#### ListObjects
|
||||
|
||||
Implemented, but there isn't a very good specification of what `encoding-type=url` covers so there might be some encoding bugs. In our implementation the url-encoded fields are in the same in ListObjects as they are in ListObjectsV2.
|
||||
|
||||
#### ListObjectsV2
|
||||
|
||||
Implemented.
|
||||
|
||||
#### PutObject
|
||||
|
||||
Implemented.
|
||||
|
||||
#### UploadPart
|
||||
|
||||
Implemented.
|
||||
- **ListObjects:** Implemented, but there isn't a very good specification of what `encoding-type=url` covers so there might be some encoding bugs. In our implementation the url-encoded fields are in the same in ListObjects as they are in ListObjectsV2.
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Migrating from 0.3 to 0.4
|
||||
|
||||
**Migrating from 0.3 to 0.4 is unsupported. This document is only intended to
|
||||
document the process internally for the Deuxfleurs cluster where we have to do
|
||||
it. Do not try it yourself, you will lose your data and we will not help you.**
|
||||
|
||||
**Migrating from 0.2 to 0.4 will break everything for sure. Never try it.**
|
||||
|
||||
The internal data format of Garage hasn't changed much between 0.3 and 0.4.
|
||||
The Sled database is still the same, and the data directory as well.
|
||||
|
||||
The following has changed, all in the meta directory:
|
||||
|
||||
- `node_id` in 0.3 contains the identifier of the current node. In 0.4, this
|
||||
file does nothing and should be deleted. It is replaced by `node_key` (the
|
||||
secret key) and `node_key.pub` (the associated public key). A node's
|
||||
identifier on the ring is its public key.
|
||||
|
||||
- `peer_info` in 0.3 contains the list of peers saved automatically by Garage.
|
||||
The format has changed and it is now stored in `peer_list` (`peer_info`
|
||||
should be deleted).
|
||||
|
||||
When migrating, all node identifiers will change. This also means that the
|
||||
affectation of data partitions on the ring will change, and lots of data will
|
||||
have to be rebalanced.
|
||||
|
||||
- If your cluster has only 3 nodes, all nodes store everything, therefore nothing has to be rebalanced.
|
||||
|
||||
- If your cluster has only 4 nodes, for any partition there will always be at
|
||||
least 2 nodes that stored data before that still store it after. Therefore
|
||||
the migration should in theory be transparent and Garage should continue to
|
||||
work during the rebalance.
|
||||
|
||||
- If your cluster has 5 or more nodes, data will disappear during the
|
||||
migration. Do not migrate (fortunately we don't have this scenario at
|
||||
Deuxfleurs), or if you do, make Garage unavailable until things stabilize
|
||||
(disable web and api access).
|
||||
|
||||
|
||||
The migration steps are as follows:
|
||||
|
||||
1. Prepare a new configuration file for 0.4. For each node, point to the same
|
||||
meta and data directories as Garage 0.3. Basically, the things that change
|
||||
are the following:
|
||||
|
||||
- No more `rpc_tls` section
|
||||
- You have to generate a shared `rpc_secret` and put it in all config files
|
||||
- `bootstrap_peers` has a different syntax as it has to contain node keys.
|
||||
Leave it empty and use `garage node-id` and `garage node connect` instead (new features of 0.4)
|
||||
- put the publicly accessible RPC address of your node in `rpc_public_addr` if possible (its optional but recommended)
|
||||
- If you are using Consul, change the `consul_service_name` to NOT be the name advertised by Nomad.
|
||||
Now Garage is responsible for advertising its own service itself.
|
||||
|
||||
2. Disable api and web access for some time (Garage does not support disabling
|
||||
these endpoints but you can change the port number or stop your reverse
|
||||
proxy for instance).
|
||||
|
||||
3. Do `garage repair -a --yes tables` and `garage repair -a --yes blocks`,
|
||||
check the logs and check that all data seems to be synced correctly between
|
||||
nodes.
|
||||
|
||||
4. Save somewhere the output of `garage status`. We will need this to remember
|
||||
how to reconfigure nodes in 0.4.
|
||||
|
||||
5. Turn off Garage 0.3
|
||||
|
||||
6. Backup metadata folders if you can (i.e. if you have space to do it
|
||||
somewhere). Backuping data folders could also be usefull but that's much
|
||||
harder to do. If your filesystem supports snapshots, this could be a good
|
||||
time to use them.
|
||||
|
||||
7. Turn on Garage 0.4
|
||||
|
||||
8. At this point, running `garage status` should indicate that all nodes of the
|
||||
previous cluster are "unavailable". The nodes have new identifiers that
|
||||
should appear in healthy nodes once they can talk to one another (use
|
||||
`garage node connect` if necessary`). They should have NO ROLE ASSIGNED at
|
||||
the moment.
|
||||
|
||||
9. Prepare a script with several `garage node configure` commands that replace
|
||||
each of the v0.3 node ID with the corresponding v0.4 node ID, with the same
|
||||
zone/tag/capacity. For example if your node `drosera` had identifier `c24e`
|
||||
before and now has identifier `789a`, and it was configured with capacity
|
||||
`2` in zone `dc1`, put the following command in your script:
|
||||
|
||||
```bash
|
||||
garage node configure 789a -z dc1 -c 2 -t drosera --replace c24e
|
||||
```
|
||||
|
||||
10. Run your reconfiguration script. Check that the new output of `garage
|
||||
status` contains the correct node IDs with the correct values for capacity
|
||||
and zone. Old nodes should no longer be mentioned.
|
||||
|
||||
11. If your cluster has 4 nodes or less, and you are feeling adventurous, you
|
||||
can reenable Web and API access now. Things will probably work.
|
||||
|
||||
12. Garage might already be resyncing stuff. Issue a `garage repair -a --yes
|
||||
tables` and `garage repair -a --yes blocks` to force it to do so.
|
||||
|
||||
13. Wait for resyncing activity to stop in the logs. Do steps 12 and 13 two or
|
||||
three times, until you see that when you issue the repair commands, nothing
|
||||
gets resynced any longer.
|
||||
|
||||
14. Your upgraded cluster should be in a working state. Re-enable API and Web
|
||||
access and check that everything went well.
|
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 74 KiB |
@@ -0,0 +1,12 @@
|
||||
*
|
||||
|
||||
!img
|
||||
|
||||
!.gitignore
|
||||
!*.svg
|
||||
!*.png
|
||||
!*.jpg
|
||||
!*.tex
|
||||
!Makefile
|
||||
!.gitignore
|
||||
!talk.pdf
|
||||
@@ -0,0 +1,3 @@
|
||||
talk.pdf: talk.tex
|
||||
pdflatex talk.tex
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,147 @@
|
||||
%\nonstopmode
|
||||
\documentclass[aspectratio=169]{beamer}
|
||||
\usepackage[utf8]{inputenc}
|
||||
% \usepackage[frenchb]{babel}
|
||||
\usepackage{amsmath}
|
||||
\usepackage{mathtools}
|
||||
\usepackage{breqn}
|
||||
\usepackage{multirow}
|
||||
\usetheme{boxes}
|
||||
\usepackage{graphicx}
|
||||
%\useoutertheme[footline=authortitle,subsection=false]{miniframes}
|
||||
|
||||
\beamertemplatenavigationsymbolsempty
|
||||
|
||||
\usepackage{tabu}
|
||||
\usepackage{multicol}
|
||||
\usepackage{vwcol}
|
||||
\usepackage{stmaryrd}
|
||||
\usepackage{graphicx}
|
||||
|
||||
\usepackage[normalem]{ulem}
|
||||
|
||||
\title{Presentation of the Garage project}
|
||||
\subtitle{NGI pointer kickoff meeting}
|
||||
\author{Deuxfleurs Association}
|
||||
\date{2021-09-13}
|
||||
|
||||
\begin{document}
|
||||
|
||||
\begin{frame}
|
||||
\centering
|
||||
\includegraphics[width=.3\linewidth]{../../sticker/Garage.pdf}
|
||||
\vspace{1em}
|
||||
|
||||
{\large\bf Deuxfleurs Association}
|
||||
\vspace{1em}
|
||||
|
||||
\url{https://deuxfleurs.fr/}
|
||||
|
||||
\url{https://garagehq.deuxfleurs.fr/}
|
||||
|
||||
Matrix channel: \texttt{\#garage:deuxfleurs.fr}
|
||||
\end{frame}
|
||||
|
||||
\begin{frame}
|
||||
\frametitle{Our objective at Deuxfleurs}
|
||||
|
||||
\begin{center}
|
||||
\textbf{Promote self-hosting and small-scale hosting\\
|
||||
as an alternative to large cloud providers}
|
||||
\end{center}
|
||||
\vspace{2em}
|
||||
\visible<2->{
|
||||
Why is it hard?
|
||||
}
|
||||
\visible<3->{
|
||||
\vspace{2em}
|
||||
\begin{center}
|
||||
\textbf{\underline{Resilience}}\\
|
||||
{\footnotesize (we want good uptime/availability with low supervision)}
|
||||
\end{center}
|
||||
}
|
||||
\end{frame}
|
||||
|
||||
\begin{frame}
|
||||
\frametitle{How to be resilient (the hard way)}
|
||||
|
||||
Entreprise-grade systems typically employ:
|
||||
\vspace{1em}
|
||||
\begin{itemize}
|
||||
\item Redundant Internet connections
|
||||
\item Redundant electricity
|
||||
\item UPSes
|
||||
\item RAID
|
||||
\item ...
|
||||
\end{itemize}
|
||||
\vspace{1em}
|
||||
$\to$ it's costly and only worth it at DC scale
|
||||
\end{frame}
|
||||
|
||||
\begin{frame}
|
||||
\frametitle{How to be resilient (the \underline{\textbf{cheap}} way)}
|
||||
|
||||
Instead, we use:
|
||||
\vspace{1em}
|
||||
\begin{itemize}
|
||||
\item Commodity hardware (e.g. old desktop PCs)
|
||||
\vspace{.5em}
|
||||
\item<2-> Commodity Internet (e.g. FTTB, FTTH) and electricity
|
||||
\vspace{.5em}
|
||||
\item<3-> \textbf{Geographical redundancy} (multi-site replication)
|
||||
\vspace{.5em}
|
||||
\item<4-> \textbf{Fault-tolerant distributed algorithms}
|
||||
\end{itemize}
|
||||
\vspace{1em}
|
||||
\visible<5->{
|
||||
\centering
|
||||
\underline{\textbf{This is how we build Garage.}}
|
||||
}
|
||||
\end{frame}
|
||||
|
||||
\begin{frame}
|
||||
\frametitle{But what is Garage, exactly?}
|
||||
\textbf{Garage is a self-hosted drop-in replacement for the Amazon S3 object store}\\
|
||||
\vspace{.5em}
|
||||
that implements resilience through geographical redundancy on commodity hardware
|
||||
|
||||
\vspace{1em}
|
||||
\visible<2->{
|
||||
\begin{center}
|
||||
Current status: technical preview\\
|
||||
Our goal: release a stable v1.0
|
||||
\end{center}
|
||||
}
|
||||
|
||||
\vspace{1em}
|
||||
\visible<3->{
|
||||
\textbf{Comming up next: an e-mail IMAP inbox based on the same principles}
|
||||
}
|
||||
|
||||
\vspace{1em}
|
||||
\visible<4->{
|
||||
\begin{center}
|
||||
Current status: just an idea\\
|
||||
Our goal: at least a PoC, maybe more
|
||||
\end{center}
|
||||
}
|
||||
\end{frame}
|
||||
|
||||
\begin{frame}
|
||||
\centering
|
||||
\includegraphics[width=.3\linewidth]{../../sticker/Garage.pdf}
|
||||
\vspace{1em}
|
||||
|
||||
{\large\bf Deuxfleurs Association}
|
||||
\vspace{1em}
|
||||
|
||||
\url{https://deuxfleurs.fr/}
|
||||
|
||||
\url{https://garagehq.deuxfleurs.fr/}
|
||||
|
||||
Matrix channel: \texttt{\#garage:deuxfleurs.fr}
|
||||
\end{frame}
|
||||
|
||||
\end{document}
|
||||
|
||||
%% vim: set ts=4 sw=4 tw=0 noet spelllang=fr :
|
||||
@@ -1,20 +0,0 @@
|
||||
#!/bin/sh
|
||||
|
||||
BIN=target/release/garage
|
||||
DOCKER=lxpz/garage_amd64
|
||||
|
||||
TAG=$1
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: $0 <tag>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RUSTFLAGS="-C link-arg=-fuse-ld=lld -C target-cpu=x86-64 -C target-feature=+sse2" cargo build --release --no-default-features
|
||||
cp $BIN $BIN.stripped
|
||||
strip $BIN.stripped
|
||||
|
||||
docker pull archlinux:latest
|
||||
docker build -t $DOCKER:$TAG .
|
||||
docker push $DOCKER:$TAG
|
||||
docker tag $DOCKER:$TAG $DOCKER:latest
|
||||
docker push $DOCKER:latest
|
||||
@@ -0,0 +1,146 @@
|
||||
{
|
||||
path ? "/../aws-list.txt",
|
||||
}:
|
||||
|
||||
with import ./common.nix;
|
||||
let
|
||||
pkgs = import pkgsSrc {};
|
||||
lib = pkgs.lib;
|
||||
|
||||
/* Converts a key list and a value list to a set
|
||||
|
||||
Example:
|
||||
listToSet [ "name" "version" ] [ "latex" "3.14" ]
|
||||
=> { name = "latex"; version = "3.14"; }
|
||||
*/
|
||||
listToSet = keys: values:
|
||||
builtins.listToAttrs
|
||||
(lib.zipListsWith
|
||||
(a: b: { name = a; value = b; })
|
||||
keys
|
||||
values);
|
||||
|
||||
/* Says if datetime a is more recent than datetime b
|
||||
|
||||
Example:
|
||||
cmpDate { date = "2021-09-10"; time = "22:12:15"; } { date = "2021-02-03"; time = "23:54:12"; }
|
||||
=> true
|
||||
*/
|
||||
cmpDate = a: b:
|
||||
let da = (builtins.head a.builds).date;
|
||||
db = (builtins.head b.builds).date;
|
||||
in
|
||||
if da == db then (builtins.head a.builds).time > (builtins.head b.builds).time
|
||||
else da > db;
|
||||
|
||||
/* Pretty platforms */
|
||||
prettyPlatform = name:
|
||||
if name == "aarch64-unknown-linux-musl" then "linux/arm64"
|
||||
else if name == "armv6l-unknown-linux-musleabihf" then "linux/arm"
|
||||
else if name == "x86_64-unknown-linux-musl" then "linux/amd64"
|
||||
else if name == "i686-unknown-linux-musl" then "linux/386"
|
||||
else name;
|
||||
|
||||
/* Parsing */
|
||||
list = builtins.readFile (./. + path);
|
||||
entries = lib.splitString "\n" list;
|
||||
|
||||
elems = builtins.filter
|
||||
(e: (builtins.length e) == 4)
|
||||
(map
|
||||
(x: builtins.filter (e: e != "") (lib.splitString " " x))
|
||||
entries);
|
||||
|
||||
keys = ["date" "time" "size" "path"];
|
||||
parsed = map (entry: listToSet keys entry) elems;
|
||||
|
||||
subkeys = ["root" "version" "platform" "binary" ];
|
||||
builds = map (entry: entry // listToSet subkeys (lib.splitString "/" entry.path)) parsed;
|
||||
|
||||
/* Aggregation */
|
||||
builds_per_version = lib.foldl (acc: v: acc // { ${v.version} = if builtins.hasAttr v.version acc then acc.${v.version} ++ [ v ] else [ v ]; }) {} builds;
|
||||
|
||||
versions = builtins.attrNames builds_per_version;
|
||||
versions_release = builtins.filter (x: builtins.match "v[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?" x != null) versions;
|
||||
versions_commit = builtins.filter (x: builtins.match "[0-9a-f]{40}" x != null) versions;
|
||||
versions_extra = lib.subtractLists (versions_release ++ versions_commit) versions;
|
||||
|
||||
sorted_builds = [
|
||||
{
|
||||
name = "Release";
|
||||
hide = false;
|
||||
type = "tag";
|
||||
description = "Release builds are the official builds, they are tailored for productions and are the most tested.";
|
||||
builds = builtins.sort (a: b: a.version > b.version) (map (x: { version = x; builds = builtins.getAttr x builds_per_version; }) versions_release);
|
||||
}
|
||||
{
|
||||
name = "Extra";
|
||||
hide = true;
|
||||
type = "tag";
|
||||
description = "Extra builds are built on demand to test a specific feature or a specific need.";
|
||||
builds = builtins.sort cmpDate (map (x: { version = x; builds = builtins.getAttr x builds_per_version; }) versions_extra);
|
||||
}
|
||||
{
|
||||
name = "Development";
|
||||
hide = true;
|
||||
type = "commit";
|
||||
description = "Development builds are built periodically. Use them if you want to test a specific feature that is not yet released.";
|
||||
builds = builtins.sort cmpDate (map (x: { version = x; builds = builtins.getAttr x builds_per_version; }) versions_commit);
|
||||
}
|
||||
];
|
||||
|
||||
in
|
||||
pkgs.writeText "index.html" ''
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>Garage releases</title>
|
||||
<style>
|
||||
html, body { margin:0; padding: 0 }
|
||||
body { font-family: 'Helvetica', Sans; }
|
||||
section { margin: 1rem; }
|
||||
ul { padding:0; margin: 0.2rem }
|
||||
li {
|
||||
border-radius: 0.2rem;
|
||||
display: inline;
|
||||
border: 2px #0b5d83 solid;
|
||||
padding: 0.5rem;
|
||||
line-height: 3rem;
|
||||
color: #0b5d83;
|
||||
}
|
||||
li:hover { background-color: #0b5d83; color: #fff; }
|
||||
li a, li a:hover { color: inherit; text-decoration: none }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${ builtins.toString (lib.forEach sorted_builds (r: ''
|
||||
<section>
|
||||
<h2>${r.name} builds</h2>
|
||||
|
||||
<p>${r.description}</p>
|
||||
|
||||
${if r.hide then "<details><summary>Show ${r.name} builds</summary>" else ""}
|
||||
${ builtins.toString (lib.forEach r.builds (x: ''
|
||||
<h3> ${x.version} (${(builtins.head x.builds).date}) </h3>
|
||||
<p>See this build on</p>
|
||||
<p> Binaries:
|
||||
<ul>
|
||||
${ builtins.toString (lib.forEach x.builds (b: ''
|
||||
<li><a href="/${b.path}">${prettyPlatform b.platform}</a></li>
|
||||
''))}
|
||||
</ul></p>
|
||||
<p> Sources:
|
||||
<ul>
|
||||
<li><a href="https://git.deuxfleurs.fr/Deuxfleurs/garage/src/${r.type}/${x.version}">gitea</a></li>
|
||||
<li><a href="https://git.deuxfleurs.fr/Deuxfleurs/garage/archive/${x.version}.zip">.zip</a></li>
|
||||
<li><a href="https://git.deuxfleurs.fr/Deuxfleurs/garage/archive/${x.version}.tar.gz">.tar.gz</a></li>
|
||||
</ul></p>
|
||||
'')) }
|
||||
${ if builtins.length r.builds == 0 then "<em>There is no build for this category</em>" else "" }
|
||||
${if r.hide then "</details>" else ""}
|
||||
</section>
|
||||
''))}
|
||||
</body>
|
||||
</html>
|
||||
''
|
||||
@@ -0,0 +1,21 @@
|
||||
rec {
|
||||
/*
|
||||
* Fixed dependencies
|
||||
*/
|
||||
pkgsSrc = fetchTarball {
|
||||
# As of 2021-10-04
|
||||
url ="https://github.com/NixOS/nixpkgs/archive/b27d18a412b071f5d7991d1648cfe78ee7afe68a.tar.gz";
|
||||
sha256 = "1xy9zpypqfxs5gcq5dcla4bfkhxmh5nzn9dyqkr03lqycm9wg5cr";
|
||||
};
|
||||
cargo2nixSrc = fetchGit {
|
||||
# As of 2021-10-06
|
||||
url = "https://github.com/superboum/cargo2nix";
|
||||
rev = "1364752cd784764db2ef5b1e1248727cebfae2ce";
|
||||
};
|
||||
|
||||
/*
|
||||
* Shared objects
|
||||
*/
|
||||
cargo2nix = import cargo2nixSrc;
|
||||
cargo2nixOverlay = import "${cargo2nixSrc}/overlay";
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
pkgs:
|
||||
pkgs.buildGoModule rec {
|
||||
pname = "kaniko";
|
||||
version = "1.6.0";
|
||||
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "GoogleContainerTools";
|
||||
repo = "kaniko";
|
||||
rev = "v${version}";
|
||||
sha256 = "1fnclr556avxay6pvgw5ya3xbxfnf2gv4njq2hr4fd6fcjyslq5h";
|
||||
};
|
||||
|
||||
vendorSha256 = null;
|
||||
|
||||
checkPhase = "true";
|
||||
|
||||
meta = with pkgs.lib; {
|
||||
description = "kaniko is a tool to build container images from a Dockerfile, inside a container or Kubernetes cluster.";
|
||||
homepage = "https://github.com/GoogleContainerTools/kaniko";
|
||||
license = licenses.asl20;
|
||||
platforms = platforms.linux;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
substituters = https://cache.nixos.org https://nix.web.deuxfleurs.fr
|
||||
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= nix.web.deuxfleurs.fr:eTGL6kvaQn6cDR/F9lDYUIP9nCVR/kkshYfLDJf1yKs=
|
||||
max-jobs = auto
|
||||
cores = 4
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
system ? builtins.currentSystem,
|
||||
}:
|
||||
|
||||
with import ./common.nix;
|
||||
|
||||
let
|
||||
platforms = [
|
||||
"x86_64-unknown-linux-musl"
|
||||
"i686-unknown-linux-musl"
|
||||
"aarch64-unknown-linux-musl"
|
||||
"armv6l-unknown-linux-musleabihf"
|
||||
];
|
||||
pkgsList = builtins.map (target: import pkgsSrc {
|
||||
inherit system;
|
||||
crossSystem = { config = target; };
|
||||
}) platforms;
|
||||
pkgsHost = import pkgsSrc {};
|
||||
lib = pkgsHost.lib;
|
||||
kaniko = (import ./kaniko.nix) pkgsHost;
|
||||
in
|
||||
lib.flatten (builtins.map (pkgs: [
|
||||
pkgs.rustPlatform.rust.rustc
|
||||
pkgs.rustPlatform.rust.cargo
|
||||
pkgs.buildPackages.stdenv.cc
|
||||
]) pkgsList) ++ [
|
||||
kaniko
|
||||
]
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
FROM rust:buster
|
||||
RUN apt-get update && \
|
||||
apt-get install --yes libsodium-dev awscli python-pip wget rclone openssl socat && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
RUN wget https://dl.min.io/client/mc/release/linux-amd64/mc -O /usr/local/bin/mc && chmod +x /usr/local/bin/mc
|
||||
RUN rustup component add rustfmt clippy
|
||||
RUN pip install s3cmd
|
||||
@@ -1,8 +0,0 @@
|
||||
DOCKER=lxpz/garage_builder_amd64
|
||||
|
||||
docker:
|
||||
docker build -t $(DOCKER):$(TAG) .
|
||||
docker push $(DOCKER):$(TAG)
|
||||
docker tag $(DOCKER):$(TAG) $(DOCKER):latest
|
||||
docker push $(DOCKER):latest
|
||||
|
||||
@@ -6,13 +6,14 @@ SCRIPT_FOLDER="`dirname \"$0\"`"
|
||||
REPO_FOLDER="${SCRIPT_FOLDER}/../"
|
||||
GARAGE_DEBUG="${REPO_FOLDER}/target/debug/"
|
||||
GARAGE_RELEASE="${REPO_FOLDER}/target/release/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:$PATH"
|
||||
NIX_RELEASE="${REPO_FOLDER}/result/bin/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:${NIX_RELEASE}:$PATH"
|
||||
|
||||
garage bucket create eprouvette
|
||||
KEY_INFO=`garage key new --name opérateur`
|
||||
garage -c /tmp/config.1.toml bucket create eprouvette
|
||||
KEY_INFO=$(garage -c /tmp/config.1.toml key new --name opérateur)
|
||||
ACCESS_KEY=`echo $KEY_INFO|grep -Po 'GK[a-f0-9]+'`
|
||||
SECRET_KEY=`echo $KEY_INFO|grep -Po 'Secret key: [a-f0-9]+'|grep -Po '[a-f0-9]+$'`
|
||||
garage bucket allow eprouvette --read --write --key $ACCESS_KEY
|
||||
garage -c /tmp/config.1.toml bucket allow eprouvette --read --write --key $ACCESS_KEY
|
||||
echo "$ACCESS_KEY $SECRET_KEY" > /tmp/garage.s3
|
||||
|
||||
echo "Bucket s3://eprouvette created. Credentials stored in /tmp/garage.s3."
|
||||
|
||||
+28
-9
@@ -6,7 +6,8 @@ SCRIPT_FOLDER="`dirname \"$0\"`"
|
||||
REPO_FOLDER="${SCRIPT_FOLDER}/../"
|
||||
GARAGE_DEBUG="${REPO_FOLDER}/target/debug/"
|
||||
GARAGE_RELEASE="${REPO_FOLDER}/target/release/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:$PATH"
|
||||
NIX_RELEASE="${REPO_FOLDER}/result/bin/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:${NIX_RELEASE}:$PATH"
|
||||
FANCYCOLORS=("41m" "42m" "44m" "45m" "100m" "104m")
|
||||
|
||||
export RUST_BACKTRACE=1
|
||||
@@ -16,6 +17,10 @@ MAIN_LABEL="\e[${FANCYCOLORS[0]}[main]\e[49m"
|
||||
WHICH_GARAGE=$(which garage || exit 1)
|
||||
echo -en "${MAIN_LABEL} Found garage at: ${WHICH_GARAGE}\n"
|
||||
|
||||
NETWORK_SECRET="$(openssl rand -hex 32)"
|
||||
|
||||
|
||||
# <<<<<<<<< BEGIN FOR LOOP ON NODES
|
||||
for count in $(seq 1 3); do
|
||||
CONF_PATH="/tmp/config.$count.toml"
|
||||
LABEL="\e[${FANCYCOLORS[$count]}[$count]\e[49m"
|
||||
@@ -25,13 +30,10 @@ block_size = 1048576 # objects are split in blocks of maximum this number of b
|
||||
metadata_dir = "/tmp/garage-meta-$count"
|
||||
data_dir = "/tmp/garage-data-$count"
|
||||
rpc_bind_addr = "0.0.0.0:$((3900+$count))" # the port other Garage nodes will use to talk to this node
|
||||
bootstrap_peers = [
|
||||
"127.0.0.1:3901",
|
||||
"127.0.0.1:3902",
|
||||
"127.0.0.1:3903"
|
||||
]
|
||||
max_concurrent_rpc_requests = 12
|
||||
rpc_public_addr = "127.0.0.1:$((3900+$count))"
|
||||
bootstrap_peers = []
|
||||
replication_mode = "3"
|
||||
rpc_secret = "$NETWORK_SECRET"
|
||||
|
||||
[s3_api]
|
||||
api_bind_addr = "0.0.0.0:$((3910+$count))" # the S3 API port, HTTP without TLS. Add a reverse proxy for the TLS part.
|
||||
@@ -60,13 +62,30 @@ if [ -z "$SKIP_HTTPS" ]; then
|
||||
socat openssl-listen:4443,reuseaddr,fork,cert=/tmp/garagessl/test.pem,verify=0 tcp4-connect:localhost:3911 &
|
||||
fi
|
||||
|
||||
(garage server -c /tmp/config.$count.toml 2>&1|while read r; do echo -en "$LABEL $r\n"; done) &
|
||||
(garage -c /tmp/config.$count.toml server 2>&1|while read r; do echo -en "$LABEL $r\n"; done) &
|
||||
done
|
||||
# >>>>>>>>>>>>>>>> END FOR LOOP ON NODES
|
||||
|
||||
sleep 3
|
||||
# Establish connections between nodes
|
||||
for count in $(seq 1 3); do
|
||||
NODE=$(garage -c /tmp/config.$count.toml node-id -q)
|
||||
for count2 in $(seq 1 3); do
|
||||
garage -c /tmp/config.$count2.toml node connect $NODE
|
||||
done
|
||||
done
|
||||
|
||||
until garage status 2>&1|grep -q Healthy ; do
|
||||
RETRY=120
|
||||
until garage -c /tmp/config.1.toml status 2>&1|grep -q HEALTHY ; do
|
||||
(( RETRY-- ))
|
||||
if (( RETRY <= 0 )); then
|
||||
echo -en "${MAIN_LABEL} Garage did not start"
|
||||
exit 1
|
||||
fi
|
||||
echo -en "${MAIN_LABEL} cluster starting...\n"
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo -en "${MAIN_LABEL} cluster started\n"
|
||||
|
||||
wait
|
||||
|
||||
+12
-5
@@ -6,18 +6,25 @@ SCRIPT_FOLDER="`dirname \"$0\"`"
|
||||
REPO_FOLDER="${SCRIPT_FOLDER}/../"
|
||||
GARAGE_DEBUG="${REPO_FOLDER}/target/debug/"
|
||||
GARAGE_RELEASE="${REPO_FOLDER}/target/release/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:$PATH"
|
||||
NIX_RELEASE="${REPO_FOLDER}/result/bin/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:${NIX_RELEASE}:$PATH"
|
||||
|
||||
sleep 5
|
||||
until garage status 2>&1|grep -q Healthy ; do
|
||||
RETRY=120
|
||||
until garage -c /tmp/config.1.toml status 2>&1|grep -q HEALTHY ; do
|
||||
(( RETRY-- ))
|
||||
if (( RETRY <= 0 )); then
|
||||
echo "garage did not start in time, failing."
|
||||
exit 1
|
||||
fi
|
||||
echo "cluster starting..."
|
||||
sleep 1
|
||||
done
|
||||
|
||||
garage status \
|
||||
| grep UNCONFIGURED \
|
||||
garage -c /tmp/config.1.toml status \
|
||||
| grep 'NO ROLE' \
|
||||
| grep -Po '^[0-9a-f]+' \
|
||||
| while read id; do
|
||||
garage node configure -z dc1 -c 1 $id
|
||||
garage -c /tmp/config.1.toml node configure -z dc1 -c 1 $id
|
||||
done
|
||||
|
||||
|
||||
+11
-10
@@ -8,22 +8,23 @@ SCRIPT_FOLDER="`dirname \"$0\"`"
|
||||
REPO_FOLDER="${SCRIPT_FOLDER}/../"
|
||||
GARAGE_DEBUG="${REPO_FOLDER}/target/debug/"
|
||||
GARAGE_RELEASE="${REPO_FOLDER}/target/release/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:$PATH"
|
||||
NIX_RELEASE="${REPO_FOLDER}/result/bin/"
|
||||
PATH="${GARAGE_DEBUG}:${GARAGE_RELEASE}:${NIX_RELEASE}:$PATH"
|
||||
|
||||
# @FIXME Duck is not ready for testing, we have a bug
|
||||
SKIP_DUCK=1
|
||||
|
||||
echo "⏳ Setup"
|
||||
cargo build
|
||||
${SCRIPT_FOLDER}/dev-clean.sh
|
||||
${SCRIPT_FOLDER}/dev-cluster.sh > /tmp/garage.log 2>&1 &
|
||||
sleep 6
|
||||
${SCRIPT_FOLDER}/dev-configure.sh
|
||||
${SCRIPT_FOLDER}/dev-bucket.sh
|
||||
|
||||
which garage
|
||||
garage status
|
||||
garage key list
|
||||
garage bucket list
|
||||
garage -c /tmp/config.1.toml status
|
||||
garage -c /tmp/config.1.toml key list
|
||||
garage -c /tmp/config.1.toml bucket list
|
||||
|
||||
dd if=/dev/urandom of=/tmp/garage.1.rnd bs=1k count=2 # No multipart, inline storage (< INLINE_THRESHOLD = 3072 bytes)
|
||||
dd if=/dev/urandom of=/tmp/garage.2.rnd bs=1M count=5 # No multipart but file will be chunked
|
||||
@@ -116,9 +117,9 @@ if [ -z "$SKIP_AWS" ]; then
|
||||
echo "<h1>hello world</h1>" > /tmp/garage-index.html
|
||||
aws s3 cp /tmp/garage-index.html s3://eprouvette/index.html
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3923/ ` == 404 ]
|
||||
garage bucket website --allow eprouvette
|
||||
garage -c /tmp/config.1.toml bucket website --allow eprouvette
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3923/ ` == 200 ]
|
||||
garage bucket website --deny eprouvette
|
||||
garage -c /tmp/config.1.toml bucket website --deny eprouvette
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3923/ ` == 404 ]
|
||||
aws s3 rm s3://eprouvette/index.html
|
||||
rm /tmp/garage-index.html
|
||||
@@ -127,8 +128,8 @@ fi
|
||||
echo "🏁 Teardown"
|
||||
AWS_ACCESS_KEY_ID=`cat /tmp/garage.s3 |cut -d' ' -f1`
|
||||
AWS_SECRET_ACCESS_KEY=`cat /tmp/garage.s3 |cut -d' ' -f2`
|
||||
garage bucket deny --read --write eprouvette --key $AWS_ACCESS_KEY_ID
|
||||
garage bucket delete --yes eprouvette
|
||||
garage key delete --yes $AWS_ACCESS_KEY_ID
|
||||
garage -c /tmp/config.1.toml bucket deny --read --write eprouvette --key $AWS_ACCESS_KEY_ID
|
||||
garage -c /tmp/config.1.toml bucket delete --yes eprouvette
|
||||
garage -c /tmp/config.1.toml key delete --yes $AWS_ACCESS_KEY_ID
|
||||
|
||||
echo "✅ Success"
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
{
|
||||
system ? builtins.currentSystem,
|
||||
rust ? true,
|
||||
integration ? true,
|
||||
release ? true,
|
||||
}:
|
||||
|
||||
with import ./nix/common.nix;
|
||||
|
||||
let
|
||||
pkgs = import pkgsSrc {
|
||||
inherit system;
|
||||
overlays = [ cargo2nixOverlay ];
|
||||
};
|
||||
kaniko = (import ./nix/kaniko.nix) pkgs;
|
||||
|
||||
in
|
||||
|
||||
pkgs.mkShell {
|
||||
shellHook = ''
|
||||
function to_s3 {
|
||||
aws \
|
||||
--endpoint-url https://garage.deuxfleurs.fr \
|
||||
--region garage \
|
||||
s3 cp \
|
||||
./result/bin/garage \
|
||||
s3://garagehq.deuxfleurs.fr/_releases/''${DRONE_TAG:-$DRONE_COMMIT}/''${TARGET}/garage
|
||||
}
|
||||
|
||||
function to_docker {
|
||||
executor \
|
||||
--force \
|
||||
--customPlatform="''${DOCKER_PLATFORM}" \
|
||||
--destination "''${CONTAINER_NAME}:''${CONTAINER_TAG}" \
|
||||
--context dir://`pwd` \
|
||||
--verbosity=debug
|
||||
}
|
||||
|
||||
function refresh_index {
|
||||
aws \
|
||||
--endpoint-url https://garage.deuxfleurs.fr \
|
||||
--region garage \
|
||||
s3 ls \
|
||||
--recursive \
|
||||
s3://garagehq.deuxfleurs.fr/_releases/ \
|
||||
> aws-list.txt
|
||||
|
||||
nix-build nix/build_index.nix
|
||||
|
||||
aws \
|
||||
--endpoint-url https://garage.deuxfleurs.fr \
|
||||
--region garage \
|
||||
s3 cp \
|
||||
--content-type "text/html" \
|
||||
result \
|
||||
s3://garagehq.deuxfleurs.fr/_releases.html
|
||||
}
|
||||
|
||||
function refresh_toolchain {
|
||||
nix copy \
|
||||
--to 's3://nix?endpoint=garage.deuxfleurs.fr®ion=garage&secret-key=/etc/nix/signing-key.sec' \
|
||||
$(nix-store -qR \
|
||||
$(nix-build --quiet --no-build-output --no-out-link nix/toolchain.nix))
|
||||
}
|
||||
'';
|
||||
|
||||
nativeBuildInputs =
|
||||
(if rust then [
|
||||
pkgs.rustPlatform.rust.rustc
|
||||
pkgs.rustPlatform.rust.cargo
|
||||
pkgs.clippy
|
||||
pkgs.rustfmt
|
||||
/*(pkgs.callPackage cargo2nix {}).package*/
|
||||
] else [])
|
||||
++
|
||||
(if integration then [
|
||||
pkgs.s3cmd
|
||||
pkgs.awscli2
|
||||
pkgs.minio-client
|
||||
pkgs.rclone
|
||||
pkgs.socat
|
||||
pkgs.psmisc
|
||||
pkgs.which
|
||||
pkgs.openssl
|
||||
pkgs.curl
|
||||
] else [])
|
||||
++
|
||||
(if release then [
|
||||
pkgs.awscli2
|
||||
kaniko
|
||||
] else [])
|
||||
;
|
||||
}
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage_api"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -13,9 +13,9 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_model = { version = "0.3.0", path = "../model" }
|
||||
garage_table = { version = "0.3.0", path = "../table" }
|
||||
garage_util = { version = "0.3.0", path = "../util" }
|
||||
garage_model = { version = "0.4.0", path = "../model" }
|
||||
garage_table = { version = "0.4.0", path = "../table" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
|
||||
base64 = "0.13"
|
||||
bytes = "1.0"
|
||||
@@ -35,7 +35,7 @@ tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi
|
||||
http = "0.2"
|
||||
httpdate = "0.3"
|
||||
http-range = "0.1"
|
||||
hyper = "0.14"
|
||||
hyper = { version = "0.14", features = ["server", "http1", "runtime", "tcp", "stream"] }
|
||||
percent-encoding = "2.1.0"
|
||||
roxmltree = "0.14"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
|
||||
+16
-19
@@ -39,7 +39,7 @@ pub async fn run_api_server(
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&addr).serve(service);
|
||||
let server = Server::bind(addr).serve(service);
|
||||
|
||||
let graceful = server.with_graceful_shutdown(shutdown_signal);
|
||||
info!("API server listening on http://{}", addr);
|
||||
@@ -88,8 +88,8 @@ async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Respon
|
||||
|
||||
let (bucket, key) = parse_bucket_key(&path)?;
|
||||
let allowed = match req.method() {
|
||||
&Method::HEAD | &Method::GET => api_key.allow_read(&bucket),
|
||||
_ => api_key.allow_write(&bucket),
|
||||
&Method::HEAD | &Method::GET => api_key.allow_read(bucket),
|
||||
_ => api_key.allow_write(bucket),
|
||||
};
|
||||
if !allowed {
|
||||
return Err(Error::Forbidden(
|
||||
@@ -109,11 +109,11 @@ async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Respon
|
||||
match *req.method() {
|
||||
Method::HEAD => {
|
||||
// HeadObject query
|
||||
Ok(handle_head(garage, &req, &bucket, &key).await?)
|
||||
Ok(handle_head(garage, &req, bucket, key).await?)
|
||||
}
|
||||
Method::GET => {
|
||||
// GetObject query
|
||||
Ok(handle_get(garage, &req, &bucket, &key).await?)
|
||||
Ok(handle_get(garage, &req, bucket, key).await?)
|
||||
}
|
||||
Method::PUT => {
|
||||
if params.contains_key(&"partnumber".to_string())
|
||||
@@ -125,8 +125,8 @@ async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Respon
|
||||
Ok(handle_put_part(
|
||||
garage,
|
||||
req,
|
||||
&bucket,
|
||||
&key,
|
||||
bucket,
|
||||
key,
|
||||
part_number,
|
||||
upload_id,
|
||||
content_sha256,
|
||||
@@ -136,46 +136,43 @@ async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Respon
|
||||
// CopyObject query
|
||||
let copy_source = req.headers().get("x-amz-copy-source").unwrap().to_str()?;
|
||||
let copy_source =
|
||||
percent_encoding::percent_decode_str(©_source).decode_utf8()?;
|
||||
percent_encoding::percent_decode_str(copy_source).decode_utf8()?;
|
||||
let (source_bucket, source_key) = parse_bucket_key(©_source)?;
|
||||
if !api_key.allow_read(&source_bucket) {
|
||||
if !api_key.allow_read(source_bucket) {
|
||||
return Err(Error::Forbidden(format!(
|
||||
"Reading from bucket {} not allowed for this key",
|
||||
source_bucket
|
||||
)));
|
||||
}
|
||||
let source_key = source_key.ok_or_bad_request("No source key specified")?;
|
||||
Ok(
|
||||
handle_copy(garage, &req, &bucket, &key, &source_bucket, &source_key)
|
||||
.await?,
|
||||
)
|
||||
Ok(handle_copy(garage, &req, bucket, key, source_bucket, source_key).await?)
|
||||
} else {
|
||||
// PutObject query
|
||||
Ok(handle_put(garage, req, &bucket, &key, content_sha256).await?)
|
||||
Ok(handle_put(garage, req, bucket, key, content_sha256).await?)
|
||||
}
|
||||
}
|
||||
Method::DELETE => {
|
||||
if params.contains_key(&"uploadid".to_string()) {
|
||||
// AbortMultipartUpload query
|
||||
let upload_id = params.get("uploadid").unwrap();
|
||||
Ok(handle_abort_multipart_upload(garage, &bucket, &key, upload_id).await?)
|
||||
Ok(handle_abort_multipart_upload(garage, bucket, key, upload_id).await?)
|
||||
} else {
|
||||
// DeleteObject query
|
||||
Ok(handle_delete(garage, &bucket, &key).await?)
|
||||
Ok(handle_delete(garage, bucket, key).await?)
|
||||
}
|
||||
}
|
||||
Method::POST => {
|
||||
if params.contains_key(&"uploads".to_string()) {
|
||||
// CreateMultipartUpload call
|
||||
Ok(handle_create_multipart_upload(garage, &req, &bucket, &key).await?)
|
||||
Ok(handle_create_multipart_upload(garage, &req, bucket, key).await?)
|
||||
} else if params.contains_key(&"uploadid".to_string()) {
|
||||
// CompleteMultipartUpload call
|
||||
let upload_id = params.get("uploadid").unwrap();
|
||||
Ok(handle_complete_multipart_upload(
|
||||
garage,
|
||||
req,
|
||||
&bucket,
|
||||
&key,
|
||||
bucket,
|
||||
key,
|
||||
upload_id,
|
||||
content_sha256,
|
||||
)
|
||||
|
||||
+10
-2
@@ -82,7 +82,11 @@ impl Error {
|
||||
match self {
|
||||
Error::NotFound => StatusCode::NOT_FOUND,
|
||||
Error::Forbidden(_) => StatusCode::FORBIDDEN,
|
||||
Error::InternalError(GarageError::Rpc(_)) => StatusCode::SERVICE_UNAVAILABLE,
|
||||
Error::InternalError(
|
||||
GarageError::Timeout
|
||||
| GarageError::RemoteError(_)
|
||||
| GarageError::Quorum(_, _, _, _),
|
||||
) => StatusCode::SERVICE_UNAVAILABLE,
|
||||
Error::InternalError(_) | Error::Hyper(_) | Error::Http(_) => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
@@ -95,7 +99,11 @@ impl Error {
|
||||
Error::NotFound => "NoSuchKey",
|
||||
Error::Forbidden(_) => "AccessDenied",
|
||||
Error::AuthorizationHeaderMalformed(_) => "AuthorizationHeaderMalformed",
|
||||
Error::InternalError(GarageError::Rpc(_)) => "ServiceUnavailable",
|
||||
Error::InternalError(
|
||||
GarageError::Timeout
|
||||
| GarageError::RemoteError(_)
|
||||
| GarageError::Quorum(_, _, _, _),
|
||||
) => "ServiceUnavailable",
|
||||
Error::InternalError(_) | Error::Hyper(_) | Error::Http(_) => "InternalError",
|
||||
_ => "InvalidRequest",
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use hyper::{Body, Request, Response};
|
||||
use hyper::{Body, Request, Response, StatusCode};
|
||||
|
||||
use garage_util::data::*;
|
||||
use garage_util::time::*;
|
||||
@@ -55,7 +55,8 @@ async fn handle_delete_internal(
|
||||
);
|
||||
|
||||
garage.object_table.insert(&object).await?;
|
||||
return Ok((deleted_version, version_uuid));
|
||||
|
||||
Ok((deleted_version, version_uuid))
|
||||
}
|
||||
|
||||
pub async fn handle_delete(
|
||||
@@ -68,6 +69,7 @@ pub async fn handle_delete(
|
||||
|
||||
Ok(Response::builder()
|
||||
.header("x-amz-version-id", hex::encode(delete_marker_version))
|
||||
.status(StatusCode::NO_CONTENT)
|
||||
.body(Body::from(vec![]))
|
||||
.unwrap())
|
||||
}
|
||||
@@ -81,7 +83,7 @@ pub async fn handle_delete_objects(
|
||||
let body = hyper::body::to_bytes(req.into_body()).await?;
|
||||
verify_signed_content(content_sha256, &body[..])?;
|
||||
|
||||
let cmd_xml = roxmltree::Document::parse(&std::str::from_utf8(&body)?)?;
|
||||
let cmd_xml = roxmltree::Document::parse(std::str::from_utf8(&body)?)?;
|
||||
let cmd = parse_delete_objects_xml(&cmd_xml).ok_or_bad_request("Invalid delete XML query")?;
|
||||
|
||||
let mut ret_deleted = Vec::new();
|
||||
|
||||
+5
-5
@@ -106,12 +106,12 @@ pub async fn handle_head(
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
if let Some(cached) = try_answer_cached(&version, version_meta, req) {
|
||||
if let Some(cached) = try_answer_cached(version, version_meta, req) {
|
||||
return Ok(cached);
|
||||
}
|
||||
|
||||
let body: Body = Body::empty();
|
||||
let response = object_headers(&version, version_meta)
|
||||
let response = object_headers(version, version_meta)
|
||||
.header("Content-Length", format!("{}", version_meta.size))
|
||||
.status(StatusCode::OK)
|
||||
.body(body)
|
||||
@@ -149,7 +149,7 @@ pub async fn handle_get(
|
||||
ObjectVersionData::FirstBlock(meta, _) => meta,
|
||||
};
|
||||
|
||||
if let Some(cached) = try_answer_cached(&last_v, last_v_meta, req) {
|
||||
if let Some(cached) = try_answer_cached(last_v, last_v_meta, req) {
|
||||
return Ok(cached);
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ pub async fn handle_get(
|
||||
.await;
|
||||
}
|
||||
|
||||
let resp_builder = object_headers(&last_v, last_v_meta)
|
||||
let resp_builder = object_headers(last_v, last_v_meta)
|
||||
.header("Content-Length", format!("{}", last_v_meta.size))
|
||||
.status(StatusCode::OK);
|
||||
|
||||
@@ -190,7 +190,7 @@ pub async fn handle_get(
|
||||
Ok(resp_builder.body(body)?)
|
||||
}
|
||||
ObjectVersionData::FirstBlock(_, first_block_hash) => {
|
||||
let read_first_block = garage.block_manager.rpc_get_block(&first_block_hash);
|
||||
let read_first_block = garage.block_manager.rpc_get_block(first_block_hash);
|
||||
let get_next_blocks = garage.version_table.get(&last_v.uuid, &EmptyKey);
|
||||
|
||||
let (first_block, version) = futures::try_join!(read_first_block, get_next_blocks)?;
|
||||
|
||||
+160
-58
@@ -68,26 +68,63 @@ pub async fn handle_list(
|
||||
let mut result_keys = BTreeMap::<String, ListResultInfo>::new();
|
||||
let mut result_common_prefixes = BTreeSet::<String>::new();
|
||||
|
||||
let mut next_chunk_start = if query.is_v2 {
|
||||
// Determine the key from where we want to start fetch objects
|
||||
// from the database, and whether the object at this key must
|
||||
// be included or excluded from the response.
|
||||
// This key can be the prefix in the base case, or intermediate
|
||||
// points in the dataset if we are continuing a previous listing.
|
||||
#[allow(clippy::collapsible_else_if)]
|
||||
let (mut next_chunk_start, mut next_chunk_exclude_start) = if query.is_v2 {
|
||||
if let Some(ct) = &query.continuation_token {
|
||||
String::from_utf8(base64::decode(ct.as_bytes())?)?
|
||||
// In V2 mode, the continuation token is defined as an opaque
|
||||
// string in the spec, so we can do whatever we want with it.
|
||||
// In our case, it is defined as either [ or ] (for include
|
||||
// and exclude, respectively), followed by a base64 string
|
||||
// representing the key to start with.
|
||||
let exclude = match &ct[..1] {
|
||||
"[" => false,
|
||||
"]" => true,
|
||||
_ => return Err(Error::BadRequest("Invalid continuation token".to_string())),
|
||||
};
|
||||
(
|
||||
String::from_utf8(base64::decode(ct[1..].as_bytes())?)?,
|
||||
exclude,
|
||||
)
|
||||
} else if let Some(sa) = &query.start_after {
|
||||
// StartAfter has defined semantics in the spec:
|
||||
// start listing at the first key immediately after.
|
||||
(sa.clone(), true)
|
||||
} else {
|
||||
query
|
||||
.start_after
|
||||
.clone()
|
||||
.unwrap_or_else(|| query.prefix.clone())
|
||||
// In the case where neither is specified, we start
|
||||
// listing at the specified prefix. If an object has this
|
||||
// exact same key, we include it. (TODO is this correct?)
|
||||
(query.prefix.clone(), false)
|
||||
}
|
||||
} else {
|
||||
query.marker.clone().unwrap_or_else(|| query.prefix.clone())
|
||||
if let Some(mk) = &query.marker {
|
||||
// In V1 mode, the spec defines the Marker value to mean
|
||||
// the same thing as the StartAfter value in V2 mode.
|
||||
(mk.clone(), true)
|
||||
} else {
|
||||
// Base case, same as in V2 mode
|
||||
(query.prefix.clone(), false)
|
||||
}
|
||||
};
|
||||
|
||||
debug!(
|
||||
"List request: `{:?}` {} `{}`",
|
||||
query.delimiter, query.max_keys, query.prefix
|
||||
"List request: `{:?}` {} `{}`, start from {}, exclude first {}",
|
||||
query.delimiter, query.max_keys, query.prefix, next_chunk_start, next_chunk_exclude_start
|
||||
);
|
||||
|
||||
// `truncated` is a boolean that determines whether there are
|
||||
// more items to be added.
|
||||
let truncated;
|
||||
// `last_processed_item` is the key of the last item
|
||||
// that was included in the listing before truncating.
|
||||
let mut last_processed_item = None;
|
||||
|
||||
'query_loop: loop {
|
||||
// Fetch objects
|
||||
let objects = garage
|
||||
.object_table
|
||||
.get_range(
|
||||
@@ -103,64 +140,120 @@ pub async fn handle_list(
|
||||
query.max_keys + 1,
|
||||
objects.len()
|
||||
);
|
||||
let current_chunk_start = next_chunk_start.clone();
|
||||
|
||||
// Iterate on returned objects and add them to the response.
|
||||
// If a delimiter is specified, we take care of grouping objects
|
||||
// into CommonPrefixes.
|
||||
for object in objects.iter() {
|
||||
// If we have retrieved an object that doesn't start with
|
||||
// the prefix, we know we have finished listing our stuff.
|
||||
if !object.key.starts_with(&query.prefix) {
|
||||
truncated = None;
|
||||
truncated = false;
|
||||
break 'query_loop;
|
||||
}
|
||||
|
||||
if query.is_v2 && query.start_after.as_ref() == Some(&object.key) {
|
||||
// Exclude the starting key if we have to.
|
||||
if object.key == next_chunk_start && next_chunk_exclude_start {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(version) = object.versions().iter().find(|x| x.is_data()) {
|
||||
if result_keys.len() + result_common_prefixes.len() >= query.max_keys {
|
||||
truncated = Some(object.key.to_string());
|
||||
break 'query_loop;
|
||||
}
|
||||
let common_prefix = if let Some(delimiter) = &query.delimiter {
|
||||
let relative_key = &object.key[query.prefix.len()..];
|
||||
relative_key
|
||||
.find(delimiter)
|
||||
.map(|i| &object.key[..query.prefix.len() + i + delimiter.len()])
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(pfx) = common_prefix {
|
||||
// Find if this object has a currently valid (non-deleted,
|
||||
// non-still-uploading) version. If not, skip it.
|
||||
let version = match object.versions().iter().find(|x| x.is_data()) {
|
||||
Some(v) => v,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
// If we don't have space to add this object to our response,
|
||||
// we will need to stop here and mark the key of this object
|
||||
// as the marker from where
|
||||
// we want to start again in the next list call.
|
||||
let cannot_add = result_keys.len() + result_common_prefixes.len() >= query.max_keys;
|
||||
|
||||
// Determine whether this object should be grouped inside
|
||||
// a CommonPrefix because it contains the delimiter,
|
||||
// or if it should be returned as an object.
|
||||
let common_prefix = match &query.delimiter {
|
||||
Some(delimiter) => object.key[query.prefix.len()..]
|
||||
.find(delimiter)
|
||||
.map(|i| &object.key[..query.prefix.len() + i + delimiter.len()]),
|
||||
None => None,
|
||||
};
|
||||
if let Some(pfx) = common_prefix {
|
||||
// In the case where this object must be grouped in a
|
||||
// common prefix, handle it here.
|
||||
if !result_common_prefixes.contains(pfx) {
|
||||
// Determine the first listing key that starts after
|
||||
// the common prefix, by finding the next possible
|
||||
// string by alphabetical order.
|
||||
let mut first_key_after_prefix = pfx.to_string();
|
||||
let tail = first_key_after_prefix.pop().unwrap();
|
||||
first_key_after_prefix.push(((tail as u8) + 1) as char);
|
||||
|
||||
// If this were the end of the chunk,
|
||||
// the next chunk should start after this prefix
|
||||
next_chunk_start = first_key_after_prefix;
|
||||
next_chunk_exclude_start = false;
|
||||
|
||||
if cannot_add {
|
||||
truncated = true;
|
||||
break 'query_loop;
|
||||
}
|
||||
result_common_prefixes.insert(pfx.to_string());
|
||||
} else {
|
||||
let meta = match &version.state {
|
||||
ObjectVersionState::Complete(ObjectVersionData::Inline(meta, _)) => meta,
|
||||
ObjectVersionState::Complete(ObjectVersionData::FirstBlock(meta, _)) => {
|
||||
meta
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let info = match result_keys.get(&object.key) {
|
||||
None => ListResultInfo {
|
||||
last_modified: version.timestamp,
|
||||
size: meta.size,
|
||||
etag: meta.etag.to_string(),
|
||||
},
|
||||
Some(_lri) => {
|
||||
return Err(Error::InternalError(GarageError::Message(format!(
|
||||
"Duplicate key?? {}",
|
||||
object.key
|
||||
))))
|
||||
}
|
||||
};
|
||||
result_keys.insert(object.key.clone(), info);
|
||||
};
|
||||
}
|
||||
last_processed_item = Some(object.key.clone());
|
||||
continue;
|
||||
};
|
||||
|
||||
// This is not a common prefix, we want to add it to our
|
||||
// response directly.
|
||||
next_chunk_start = object.key.clone();
|
||||
|
||||
if cannot_add {
|
||||
truncated = true;
|
||||
next_chunk_exclude_start = false;
|
||||
break 'query_loop;
|
||||
}
|
||||
|
||||
let meta = match &version.state {
|
||||
ObjectVersionState::Complete(ObjectVersionData::Inline(meta, _)) => meta,
|
||||
ObjectVersionState::Complete(ObjectVersionData::FirstBlock(meta, _)) => meta,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let info = match result_keys.get(&object.key) {
|
||||
None => ListResultInfo {
|
||||
last_modified: version.timestamp,
|
||||
size: meta.size,
|
||||
etag: meta.etag.to_string(),
|
||||
},
|
||||
Some(_lri) => {
|
||||
return Err(Error::InternalError(GarageError::Message(format!(
|
||||
"Duplicate key?? {} (this is a bug, please report it)",
|
||||
object.key
|
||||
))))
|
||||
}
|
||||
};
|
||||
result_keys.insert(object.key.clone(), info);
|
||||
last_processed_item = Some(object.key.clone());
|
||||
next_chunk_exclude_start = true;
|
||||
}
|
||||
|
||||
// If our database returned less objects than what we were asking for,
|
||||
// it means that no more objects are in the bucket. So we stop here.
|
||||
if objects.len() < query.max_keys + 1 {
|
||||
truncated = None;
|
||||
truncated = false;
|
||||
break 'query_loop;
|
||||
}
|
||||
if !objects.is_empty() {
|
||||
next_chunk_start = objects[objects.len() - 1].key.clone();
|
||||
|
||||
// Sanity check: we should have added at least an object
|
||||
// or a prefix to our returned result.
|
||||
if next_chunk_start == current_chunk_start || last_processed_item.is_none() {
|
||||
return Err(Error::InternalError(GarageError::Message(format!(
|
||||
"S3 ListObject: made no progress, still starting at {} (this is a bug, please report it)", next_chunk_start))));
|
||||
}
|
||||
|
||||
// Loop and fetch more objects
|
||||
}
|
||||
|
||||
let mut result = s3_xml::ListBucketResult {
|
||||
@@ -181,11 +274,10 @@ pub async fn handle_list(
|
||||
true => Some(s3_xml::Value("url".to_string())),
|
||||
false => None,
|
||||
},
|
||||
|
||||
key_count: Some(s3_xml::IntValue(
|
||||
result_keys.len() as i64 + result_common_prefixes.len() as i64,
|
||||
)),
|
||||
is_truncated: s3_xml::Value(format!("{}", truncated.is_some())),
|
||||
is_truncated: s3_xml::Value(format!("{}", truncated)),
|
||||
contents: vec![],
|
||||
common_prefixes: vec![],
|
||||
};
|
||||
@@ -197,16 +289,27 @@ pub async fn handle_list(
|
||||
if let Some(sa) = &query.start_after {
|
||||
result.start_after = Some(uriencode_maybe(sa, query.urlencode_resp));
|
||||
}
|
||||
if let Some(nct) = truncated {
|
||||
result.next_continuation_token = Some(s3_xml::Value(base64::encode(nct.as_bytes())));
|
||||
if truncated {
|
||||
let b64 = base64::encode(next_chunk_start.as_bytes());
|
||||
let nct = if next_chunk_exclude_start {
|
||||
format!("]{}", b64)
|
||||
} else {
|
||||
format!("[{}", b64)
|
||||
};
|
||||
result.next_continuation_token = Some(s3_xml::Value(nct));
|
||||
}
|
||||
} else {
|
||||
// TODO: are these supposed to be urlencoded when encoding-type is URL??
|
||||
if let Some(mkr) = &query.marker {
|
||||
result.marker = Some(uriencode_maybe(mkr, query.urlencode_resp));
|
||||
}
|
||||
if let Some(next_marker) = truncated {
|
||||
result.next_marker = Some(uriencode_maybe(&next_marker, query.urlencode_resp));
|
||||
if truncated {
|
||||
if let Some(lpi) = last_processed_item {
|
||||
result.next_marker = Some(uriencode_maybe(&lpi, query.urlencode_resp));
|
||||
} else {
|
||||
return Err(Error::InternalError(GarageError::Message(
|
||||
"S3 ListObject: last_processed_item is None but the response was truncated, indicating that many items were processed (this is a bug, please report it)".to_string())));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,7 +324,6 @@ pub async fn handle_list(
|
||||
}
|
||||
|
||||
for pfx in result_common_prefixes.iter() {
|
||||
//TODO: in V1, are these urlencoded when urlencode_resp is true ?? (proably)
|
||||
result.common_prefixes.push(s3_xml::CommonPrefix {
|
||||
prefix: uriencode_maybe(pfx, query.urlencode_resp),
|
||||
});
|
||||
|
||||
+5
-5
@@ -193,8 +193,8 @@ async fn read_and_put_blocks(
|
||||
|
||||
let mut next_offset = first_block.len();
|
||||
let mut put_curr_version_block = put_block_meta(
|
||||
&garage,
|
||||
&version,
|
||||
garage,
|
||||
version,
|
||||
part_number,
|
||||
0,
|
||||
first_block_hash,
|
||||
@@ -213,8 +213,8 @@ async fn read_and_put_blocks(
|
||||
let block_hash = blake2sum(&block[..]);
|
||||
let block_len = block.len();
|
||||
put_curr_version_block = put_block_meta(
|
||||
&garage,
|
||||
&version,
|
||||
garage,
|
||||
version,
|
||||
part_number,
|
||||
next_offset as u64,
|
||||
block_hash,
|
||||
@@ -437,7 +437,7 @@ pub async fn handle_complete_multipart_upload(
|
||||
let body = hyper::body::to_bytes(req.into_body()).await?;
|
||||
verify_signed_content(content_sha256, &body[..])?;
|
||||
|
||||
let body_xml = roxmltree::Document::parse(&std::str::from_utf8(&body)?)?;
|
||||
let body_xml = roxmltree::Document::parse(std::str::from_utf8(&body)?)?;
|
||||
let body_list_of_parts = parse_complete_multpart_upload_body(&body_xml)
|
||||
.ok_or_bad_request("Invalid CompleteMultipartUpload XML")?;
|
||||
debug!(
|
||||
|
||||
@@ -70,7 +70,7 @@ pub async fn check_signature(
|
||||
let canonical_request = canonical_request(
|
||||
request.method(),
|
||||
&request.uri().path().to_string(),
|
||||
&canonical_query_string(&request.uri()),
|
||||
&canonical_query_string(request.uri()),
|
||||
&headers,
|
||||
&authorization.signed_headers,
|
||||
&authorization.content_sha256,
|
||||
@@ -252,7 +252,7 @@ fn canonical_request(
|
||||
method.as_str(),
|
||||
url_path,
|
||||
canonical_query_string,
|
||||
&canonical_header_string(&headers, signed_headers),
|
||||
&canonical_header_string(headers, signed_headers),
|
||||
"",
|
||||
signed_headers,
|
||||
content_sha256,
|
||||
|
||||
+12
-7
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -14,12 +14,12 @@ path = "main.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_api = { version = "0.3.0", path = "../api" }
|
||||
garage_model = { version = "0.3.0", path = "../model" }
|
||||
garage_rpc = { version = "0.3.0", path = "../rpc" }
|
||||
garage_table = { version = "0.3.0", path = "../table" }
|
||||
garage_util = { version = "0.3.0", path = "../util" }
|
||||
garage_web = { version = "0.3.0", path = "../web" }
|
||||
garage_api = { version = "0.4.0", path = "../api" }
|
||||
garage_model = { version = "0.4.0", path = "../model" }
|
||||
garage_rpc = { version = "0.4.0", path = "../rpc" }
|
||||
garage_table = { version = "0.4.0", path = "../table" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
garage_web = { version = "0.4.0", path = "../web" }
|
||||
|
||||
bytes = "1.0"
|
||||
git-version = "0.3.4"
|
||||
@@ -27,6 +27,8 @@ hex = "0.4"
|
||||
log = "0.4"
|
||||
pretty_env_logger = "0.4"
|
||||
rand = "0.8"
|
||||
async-trait = "0.1.7"
|
||||
sodiumoxide = { version = "0.2.5-0", package = "kuska-sodiumoxide" }
|
||||
|
||||
sled = "0.34"
|
||||
|
||||
@@ -38,3 +40,6 @@ toml = "0.5"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
|
||||
|
||||
#netapp = { version = "0.3.0", git = "https://git.deuxfleurs.fr/lx/netapp" }
|
||||
netapp = "0.3.0"
|
||||
|
||||
@@ -2,6 +2,7 @@ use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use garage_util::error::Error;
|
||||
@@ -10,8 +11,7 @@ use garage_table::crdt::Crdt;
|
||||
use garage_table::replication::*;
|
||||
use garage_table::*;
|
||||
|
||||
use garage_rpc::rpc_client::*;
|
||||
use garage_rpc::rpc_server::*;
|
||||
use garage_rpc::*;
|
||||
|
||||
use garage_model::bucket_table::*;
|
||||
use garage_model::garage::Garage;
|
||||
@@ -19,10 +19,8 @@ use garage_model::key_table::*;
|
||||
|
||||
use crate::cli::*;
|
||||
use crate::repair::Repair;
|
||||
use crate::*;
|
||||
|
||||
pub const ADMIN_RPC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
pub const ADMIN_RPC_PATH: &str = "_admin";
|
||||
pub const ADMIN_RPC_PATH: &str = "garage/admin_rpc.rs/Rpc";
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum AdminRpc {
|
||||
@@ -39,35 +37,24 @@ pub enum AdminRpc {
|
||||
KeyInfo(Key),
|
||||
}
|
||||
|
||||
impl RpcMessage for AdminRpc {}
|
||||
impl Rpc for AdminRpc {
|
||||
type Response = Result<AdminRpc, Error>;
|
||||
}
|
||||
|
||||
pub struct AdminRpcHandler {
|
||||
garage: Arc<Garage>,
|
||||
rpc_client: Arc<RpcClient<AdminRpc>>,
|
||||
endpoint: Arc<Endpoint<AdminRpc, Self>>,
|
||||
}
|
||||
|
||||
impl AdminRpcHandler {
|
||||
pub fn new(garage: Arc<Garage>) -> Arc<Self> {
|
||||
let rpc_client = garage.system.clone().rpc_client::<AdminRpc>(ADMIN_RPC_PATH);
|
||||
Arc::new(Self { garage, rpc_client })
|
||||
let endpoint = garage.system.netapp.endpoint(ADMIN_RPC_PATH.into());
|
||||
let admin = Arc::new(Self { garage, endpoint });
|
||||
admin.endpoint.set_handler(admin.clone());
|
||||
admin
|
||||
}
|
||||
|
||||
pub fn register_handler(self: Arc<Self>, rpc_server: &mut RpcServer) {
|
||||
rpc_server.add_handler::<AdminRpc, _, _>(ADMIN_RPC_PATH.to_string(), move |msg, _addr| {
|
||||
let self2 = self.clone();
|
||||
async move {
|
||||
match msg {
|
||||
AdminRpc::BucketOperation(bo) => self2.handle_bucket_cmd(bo).await,
|
||||
AdminRpc::KeyOperation(ko) => self2.handle_key_cmd(ko).await,
|
||||
AdminRpc::LaunchRepair(opt) => self2.handle_launch_repair(opt).await,
|
||||
AdminRpc::Stats(opt) => self2.handle_stats(opt).await,
|
||||
_ => Err(Error::BadRpc("Invalid RPC".to_string())),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_bucket_cmd(&self, cmd: BucketOperation) -> Result<AdminRpc, Error> {
|
||||
async fn handle_bucket_cmd(&self, cmd: &BucketOperation) -> Result<AdminRpc, Error> {
|
||||
match cmd {
|
||||
BucketOperation::List => {
|
||||
let bucket_names = self
|
||||
@@ -187,7 +174,7 @@ impl AdminRpcHandler {
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_key_cmd(&self, cmd: KeyOperation) -> Result<AdminRpc, Error> {
|
||||
async fn handle_key_cmd(&self, cmd: &KeyOperation) -> Result<AdminRpc, Error> {
|
||||
match cmd {
|
||||
KeyOperation::List => {
|
||||
let key_ids = self
|
||||
@@ -210,13 +197,13 @@ impl AdminRpcHandler {
|
||||
Ok(AdminRpc::KeyInfo(key))
|
||||
}
|
||||
KeyOperation::New(query) => {
|
||||
let key = Key::new(query.name);
|
||||
let key = Key::new(query.name.clone());
|
||||
self.garage.key_table.insert(&key).await?;
|
||||
Ok(AdminRpc::KeyInfo(key))
|
||||
}
|
||||
KeyOperation::Rename(query) => {
|
||||
let mut key = self.get_existing_key(&query.key_pattern).await?;
|
||||
key.name.update(query.new_name);
|
||||
key.name.update(query.new_name.clone());
|
||||
self.garage.key_table.insert(&key).await?;
|
||||
Ok(AdminRpc::KeyInfo(key))
|
||||
}
|
||||
@@ -353,17 +340,17 @@ impl AdminRpcHandler {
|
||||
let mut failures = vec![];
|
||||
let ring = self.garage.system.ring.borrow().clone();
|
||||
for node in ring.config.members.keys() {
|
||||
if self
|
||||
.rpc_client
|
||||
let node = (*node).into();
|
||||
let resp = self
|
||||
.endpoint
|
||||
.call(
|
||||
*node,
|
||||
AdminRpc::LaunchRepair(opt_to_send.clone()),
|
||||
ADMIN_RPC_TIMEOUT,
|
||||
&node,
|
||||
&AdminRpc::LaunchRepair(opt_to_send.clone()),
|
||||
PRIO_NORMAL,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
failures.push(*node);
|
||||
.await;
|
||||
if !matches!(resp, Ok(Ok(_))) {
|
||||
failures.push(node);
|
||||
}
|
||||
}
|
||||
if failures.is_empty() {
|
||||
@@ -402,10 +389,12 @@ impl AdminRpcHandler {
|
||||
|
||||
writeln!(&mut ret, "\n======================").unwrap();
|
||||
writeln!(&mut ret, "Stats for node {:?}:", node).unwrap();
|
||||
|
||||
let node_id = (*node).into();
|
||||
match self
|
||||
.rpc_client
|
||||
.call(*node, AdminRpc::Stats(opt), ADMIN_RPC_TIMEOUT)
|
||||
.await
|
||||
.endpoint
|
||||
.call(&node_id, &AdminRpc::Stats(opt), PRIO_NORMAL)
|
||||
.await?
|
||||
{
|
||||
Ok(AdminRpc::Ok(s)) => writeln!(&mut ret, "{}", s).unwrap(),
|
||||
Ok(x) => writeln!(&mut ret, "Bad answer: {:?}", x).unwrap(),
|
||||
@@ -423,7 +412,11 @@ impl AdminRpcHandler {
|
||||
writeln!(
|
||||
&mut ret,
|
||||
"\nGarage version: {}",
|
||||
git_version::git_version!()
|
||||
option_env!("GIT_VERSION").unwrap_or(git_version::git_version!(
|
||||
prefix = "git:",
|
||||
cargo_prefix = "cargo:",
|
||||
fallback = "unknown"
|
||||
))
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
@@ -453,7 +446,7 @@ impl AdminRpcHandler {
|
||||
if opt.detailed {
|
||||
writeln!(
|
||||
&mut ret,
|
||||
" number of blocks: {}",
|
||||
" number of RC entries (~= number of blocks): {}",
|
||||
self.garage.block_manager.rc_len()
|
||||
)
|
||||
.unwrap();
|
||||
@@ -492,3 +485,20 @@ impl AdminRpcHandler {
|
||||
writeln!(to, " GC todo queue length: {}", t.data.gc_todo_len()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EndpointHandler<AdminRpc> for AdminRpcHandler {
|
||||
async fn handle(
|
||||
self: &Arc<Self>,
|
||||
message: &AdminRpc,
|
||||
_from: NodeID,
|
||||
) -> Result<AdminRpc, Error> {
|
||||
match message {
|
||||
AdminRpc::BucketOperation(bo) => self.handle_bucket_cmd(bo).await,
|
||||
AdminRpc::KeyOperation(ko) => self.handle_key_cmd(ko).await,
|
||||
AdminRpc::LaunchRepair(opt) => self.handle_launch_repair(opt.clone()).await,
|
||||
AdminRpc::Stats(opt) => self.handle_stats(opt.clone()).await,
|
||||
_ => Err(Error::BadRpc("Invalid RPC".to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,634 +0,0 @@
|
||||
use std::cmp::max;
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use structopt::StructOpt;
|
||||
|
||||
use garage_util::data::Uuid;
|
||||
use garage_util::error::Error;
|
||||
use garage_util::time::*;
|
||||
|
||||
use garage_rpc::membership::*;
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::rpc_client::*;
|
||||
|
||||
use garage_model::bucket_table::*;
|
||||
use garage_model::key_table::*;
|
||||
|
||||
use crate::admin_rpc::*;
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub enum Command {
|
||||
/// Run Garage server
|
||||
#[structopt(name = "server")]
|
||||
Server(ServerOpt),
|
||||
|
||||
/// Get network status
|
||||
#[structopt(name = "status")]
|
||||
Status,
|
||||
|
||||
/// Garage node operations
|
||||
#[structopt(name = "node")]
|
||||
Node(NodeOperation),
|
||||
|
||||
/// Bucket operations
|
||||
#[structopt(name = "bucket")]
|
||||
Bucket(BucketOperation),
|
||||
|
||||
/// Key operations
|
||||
#[structopt(name = "key")]
|
||||
Key(KeyOperation),
|
||||
|
||||
/// Start repair of node data
|
||||
#[structopt(name = "repair")]
|
||||
Repair(RepairOpt),
|
||||
|
||||
/// Gather node statistics
|
||||
#[structopt(name = "stats")]
|
||||
Stats(StatsOpt),
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct ServerOpt {
|
||||
/// Configuration file
|
||||
#[structopt(short = "c", long = "config", default_value = "./config.toml")]
|
||||
pub config_file: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub enum NodeOperation {
|
||||
/// Configure Garage node
|
||||
#[structopt(name = "configure")]
|
||||
Configure(ConfigureNodeOpt),
|
||||
|
||||
/// Remove Garage node from cluster
|
||||
#[structopt(name = "remove")]
|
||||
Remove(RemoveNodeOpt),
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct ConfigureNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
node_id: String,
|
||||
|
||||
/// Location (zone or datacenter) of the node
|
||||
#[structopt(short = "z", long = "zone")]
|
||||
zone: Option<String>,
|
||||
|
||||
/// Capacity (in relative terms, use 1 to represent your smallest server)
|
||||
#[structopt(short = "c", long = "capacity")]
|
||||
capacity: Option<u32>,
|
||||
|
||||
/// Gateway-only node
|
||||
#[structopt(short = "g", long = "gateway")]
|
||||
gateway: bool,
|
||||
|
||||
/// Optional node tag
|
||||
#[structopt(short = "t", long = "tag")]
|
||||
tag: Option<String>,
|
||||
|
||||
/// Replaced node(s): list of node IDs that will be removed from the current cluster
|
||||
#[structopt(long = "replace")]
|
||||
replace: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct RemoveNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
node_id: String,
|
||||
|
||||
/// If this flag is not given, the node won't be removed
|
||||
#[structopt(long = "yes")]
|
||||
yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub enum BucketOperation {
|
||||
/// List buckets
|
||||
#[structopt(name = "list")]
|
||||
List,
|
||||
|
||||
/// Get bucket info
|
||||
#[structopt(name = "info")]
|
||||
Info(BucketOpt),
|
||||
|
||||
/// Create bucket
|
||||
#[structopt(name = "create")]
|
||||
Create(BucketOpt),
|
||||
|
||||
/// Delete bucket
|
||||
#[structopt(name = "delete")]
|
||||
Delete(DeleteBucketOpt),
|
||||
|
||||
/// Allow key to read or write to bucket
|
||||
#[structopt(name = "allow")]
|
||||
Allow(PermBucketOpt),
|
||||
|
||||
/// Deny key from reading or writing to bucket
|
||||
#[structopt(name = "deny")]
|
||||
Deny(PermBucketOpt),
|
||||
|
||||
/// Expose as website or not
|
||||
#[structopt(name = "website")]
|
||||
Website(WebsiteOpt),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct WebsiteOpt {
|
||||
/// Create
|
||||
#[structopt(long = "allow")]
|
||||
pub allow: bool,
|
||||
|
||||
/// Delete
|
||||
#[structopt(long = "deny")]
|
||||
pub deny: bool,
|
||||
|
||||
/// Bucket name
|
||||
pub bucket: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct BucketOpt {
|
||||
/// Bucket name
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct DeleteBucketOpt {
|
||||
/// Bucket name
|
||||
pub name: String,
|
||||
|
||||
/// If this flag is not given, the bucket won't be deleted
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct PermBucketOpt {
|
||||
/// Access key name or ID
|
||||
#[structopt(long = "key")]
|
||||
pub key_pattern: String,
|
||||
|
||||
/// Allow/deny read operations
|
||||
#[structopt(long = "read")]
|
||||
pub read: bool,
|
||||
|
||||
/// Allow/deny write operations
|
||||
#[structopt(long = "write")]
|
||||
pub write: bool,
|
||||
|
||||
/// Bucket name
|
||||
pub bucket: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub enum KeyOperation {
|
||||
/// List keys
|
||||
#[structopt(name = "list")]
|
||||
List,
|
||||
|
||||
/// Get key info
|
||||
#[structopt(name = "info")]
|
||||
Info(KeyOpt),
|
||||
|
||||
/// Create new key
|
||||
#[structopt(name = "new")]
|
||||
New(KeyNewOpt),
|
||||
|
||||
/// Rename key
|
||||
#[structopt(name = "rename")]
|
||||
Rename(KeyRenameOpt),
|
||||
|
||||
/// Delete key
|
||||
#[structopt(name = "delete")]
|
||||
Delete(KeyDeleteOpt),
|
||||
|
||||
/// Import key
|
||||
#[structopt(name = "import")]
|
||||
Import(KeyImportOpt),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyNewOpt {
|
||||
/// Name of the key
|
||||
#[structopt(long = "name", default_value = "Unnamed key")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyRenameOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
|
||||
/// New name of the key
|
||||
pub new_name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyDeleteOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
|
||||
/// Confirm deletion
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyImportOpt {
|
||||
/// Access key ID
|
||||
pub key_id: String,
|
||||
|
||||
/// Secret access key
|
||||
pub secret_key: String,
|
||||
|
||||
/// Key name
|
||||
#[structopt(short = "n", default_value = "Imported key")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Clone)]
|
||||
pub struct RepairOpt {
|
||||
/// Launch repair operation on all nodes
|
||||
#[structopt(short = "a", long = "all-nodes")]
|
||||
pub all_nodes: bool,
|
||||
|
||||
/// Confirm the launch of the repair operation
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
|
||||
#[structopt(subcommand)]
|
||||
pub what: Option<RepairWhat>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Eq, PartialEq, Clone)]
|
||||
pub enum RepairWhat {
|
||||
/// Only do a full sync of metadata tables
|
||||
#[structopt(name = "tables")]
|
||||
Tables,
|
||||
/// Only repair (resync/rebalance) the set of stored blocks
|
||||
#[structopt(name = "blocks")]
|
||||
Blocks,
|
||||
/// Only redo the propagation of object deletions to the version table (slow)
|
||||
#[structopt(name = "versions")]
|
||||
Versions,
|
||||
/// Only redo the propagation of version deletions to the block ref table (extremely slow)
|
||||
#[structopt(name = "block_refs")]
|
||||
BlockRefs,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Clone)]
|
||||
pub struct StatsOpt {
|
||||
/// Gather statistics from all nodes
|
||||
#[structopt(short = "a", long = "all-nodes")]
|
||||
pub all_nodes: bool,
|
||||
|
||||
/// Gather detailed statistics (this can be long)
|
||||
#[structopt(short = "d", long = "detailed")]
|
||||
pub detailed: bool,
|
||||
}
|
||||
|
||||
pub async fn cli_cmd(
|
||||
cmd: Command,
|
||||
membership_rpc_cli: RpcAddrClient<Message>,
|
||||
admin_rpc_cli: RpcAddrClient<AdminRpc>,
|
||||
rpc_host: SocketAddr,
|
||||
) -> Result<(), Error> {
|
||||
match cmd {
|
||||
Command::Status => cmd_status(membership_rpc_cli, rpc_host).await,
|
||||
Command::Node(NodeOperation::Configure(configure_opt)) => {
|
||||
cmd_configure(membership_rpc_cli, rpc_host, configure_opt).await
|
||||
}
|
||||
Command::Node(NodeOperation::Remove(remove_opt)) => {
|
||||
cmd_remove(membership_rpc_cli, rpc_host, remove_opt).await
|
||||
}
|
||||
Command::Bucket(bo) => {
|
||||
cmd_admin(admin_rpc_cli, rpc_host, AdminRpc::BucketOperation(bo)).await
|
||||
}
|
||||
Command::Key(ko) => cmd_admin(admin_rpc_cli, rpc_host, AdminRpc::KeyOperation(ko)).await,
|
||||
Command::Repair(ro) => cmd_admin(admin_rpc_cli, rpc_host, AdminRpc::LaunchRepair(ro)).await,
|
||||
Command::Stats(so) => cmd_admin(admin_rpc_cli, rpc_host, AdminRpc::Stats(so)).await,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cmd_status(
|
||||
rpc_cli: RpcAddrClient<Message>,
|
||||
rpc_host: SocketAddr,
|
||||
) -> Result<(), Error> {
|
||||
let status = match rpc_cli
|
||||
.call(&rpc_host, &Message::PullStatus, ADMIN_RPC_TIMEOUT)
|
||||
.await??
|
||||
{
|
||||
Message::AdvertiseNodesUp(nodes) => nodes,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
let config = match rpc_cli
|
||||
.call(&rpc_host, &Message::PullConfig, ADMIN_RPC_TIMEOUT)
|
||||
.await??
|
||||
{
|
||||
Message::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
let (hostname_len, addr_len, tag_len, zone_len) = status
|
||||
.iter()
|
||||
.map(|adv| (adv, config.members.get(&adv.id)))
|
||||
.map(|(adv, cfg)| {
|
||||
(
|
||||
adv.state_info.hostname.len(),
|
||||
adv.addr.to_string().len(),
|
||||
cfg.map(|c| c.tag.len()).unwrap_or(0),
|
||||
cfg.map(|c| c.zone.len()).unwrap_or(0),
|
||||
)
|
||||
})
|
||||
.fold((0, 0, 0, 0), |(h, a, t, z), (mh, ma, mt, mz)| {
|
||||
(max(h, mh), max(a, ma), max(t, mt), max(z, mz))
|
||||
});
|
||||
|
||||
println!("Healthy nodes:");
|
||||
for adv in status.iter().filter(|x| x.is_up) {
|
||||
if let Some(cfg) = config.members.get(&adv.id) {
|
||||
println!(
|
||||
"{id:?}\t{host}{h_pad}\t{addr}{a_pad}\t[{tag}]{t_pad}\t{zone}{z_pad}\t{capacity}",
|
||||
id = adv.id,
|
||||
host = adv.state_info.hostname,
|
||||
addr = adv.addr,
|
||||
tag = cfg.tag,
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
h_pad = " ".repeat(hostname_len - adv.state_info.hostname.len()),
|
||||
a_pad = " ".repeat(addr_len - adv.addr.to_string().len()),
|
||||
t_pad = " ".repeat(tag_len - cfg.tag.len()),
|
||||
z_pad = " ".repeat(zone_len - cfg.zone.len()),
|
||||
);
|
||||
} else {
|
||||
println!(
|
||||
"{id:?}\t{h}{h_pad}\t{addr}{a_pad}\tUNCONFIGURED/REMOVED",
|
||||
id = adv.id,
|
||||
h = adv.state_info.hostname,
|
||||
addr = adv.addr,
|
||||
h_pad = " ".repeat(hostname_len - adv.state_info.hostname.len()),
|
||||
a_pad = " ".repeat(addr_len - adv.addr.to_string().len()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let status_keys = status.iter().map(|x| x.id).collect::<HashSet<_>>();
|
||||
let failure_case_1 = status.iter().any(|x| !x.is_up);
|
||||
let failure_case_2 = config
|
||||
.members
|
||||
.iter()
|
||||
.any(|(id, _)| !status_keys.contains(id));
|
||||
if failure_case_1 || failure_case_2 {
|
||||
println!("\nFailed nodes:");
|
||||
for adv in status.iter().filter(|x| !x.is_up) {
|
||||
if let Some(cfg) = config.members.get(&adv.id) {
|
||||
println!(
|
||||
"{id:?}\t{host}{h_pad}\t{addr}{a_pad}\t[{tag}]{t_pad}\t{zone}{z_pad}\t{capacity}\tlast seen: {last_seen}s ago",
|
||||
id=adv.id,
|
||||
host=adv.state_info.hostname,
|
||||
addr=adv.addr,
|
||||
tag=cfg.tag,
|
||||
zone=cfg.zone,
|
||||
capacity=cfg.capacity_string(),
|
||||
last_seen=(now_msec() - adv.last_seen) / 1000,
|
||||
h_pad=" ".repeat(hostname_len - adv.state_info.hostname.len()),
|
||||
a_pad=" ".repeat(addr_len - adv.addr.to_string().len()),
|
||||
t_pad=" ".repeat(tag_len - cfg.tag.len()),
|
||||
z_pad=" ".repeat(zone_len - cfg.zone.len()),
|
||||
);
|
||||
}
|
||||
}
|
||||
let (tag_len, zone_len) = config
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(&id, _)| !status.iter().any(|x| x.id == id))
|
||||
.map(|(_, cfg)| (cfg.tag.len(), cfg.zone.len()))
|
||||
.fold((0, 0), |(t, z), (mt, mz)| (max(t, mt), max(z, mz)));
|
||||
|
||||
for (id, cfg) in config.members.iter() {
|
||||
if !status.iter().any(|x| x.id == *id) {
|
||||
println!(
|
||||
"{id:?}\t{tag}{t_pad}\t{zone}{z_pad}\t{capacity}\tnever seen",
|
||||
id = id,
|
||||
tag = cfg.tag,
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
t_pad = " ".repeat(tag_len - cfg.tag.len()),
|
||||
z_pad = " ".repeat(zone_len - cfg.zone.len()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn find_matching_node(
|
||||
cand: impl std::iter::Iterator<Item = Uuid>,
|
||||
pattern: &str,
|
||||
) -> Result<Uuid, Error> {
|
||||
let mut candidates = vec![];
|
||||
for c in cand {
|
||||
if hex::encode(&c).starts_with(&pattern) {
|
||||
candidates.push(c);
|
||||
}
|
||||
}
|
||||
if candidates.len() != 1 {
|
||||
Err(Error::Message(format!(
|
||||
"{} nodes match '{}'",
|
||||
candidates.len(),
|
||||
pattern,
|
||||
)))
|
||||
} else {
|
||||
Ok(candidates[0])
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cmd_configure(
|
||||
rpc_cli: RpcAddrClient<Message>,
|
||||
rpc_host: SocketAddr,
|
||||
args: ConfigureNodeOpt,
|
||||
) -> Result<(), Error> {
|
||||
let status = match rpc_cli
|
||||
.call(&rpc_host, &Message::PullStatus, ADMIN_RPC_TIMEOUT)
|
||||
.await??
|
||||
{
|
||||
Message::AdvertiseNodesUp(nodes) => nodes,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
let added_node = find_matching_node(status.iter().map(|x| x.id), &args.node_id)?;
|
||||
|
||||
let mut config = match rpc_cli
|
||||
.call(&rpc_host, &Message::PullConfig, ADMIN_RPC_TIMEOUT)
|
||||
.await??
|
||||
{
|
||||
Message::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
for replaced in args.replace.iter() {
|
||||
let replaced_node = find_matching_node(config.members.keys().cloned(), replaced)?;
|
||||
if config.members.remove(&replaced_node).is_none() {
|
||||
return Err(Error::Message(format!(
|
||||
"Cannot replace node {:?} as it is not in current configuration",
|
||||
replaced_node
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if args.capacity.is_some() && args.gateway {
|
||||
return Err(Error::Message(
|
||||
"-c and -g are mutually exclusive, please configure node either with c>0 to act as a storage node or with -g to act as a gateway node".into()));
|
||||
}
|
||||
if args.capacity == Some(0) {
|
||||
return Err(Error::Message("Invalid capacity value: 0".into()));
|
||||
}
|
||||
|
||||
let new_entry = match config.members.get(&added_node) {
|
||||
None => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
_ => return Err(Error::Message(
|
||||
"Please specify a capacity with the -c flag, or set node explicitly as gateway with -g".into())),
|
||||
};
|
||||
NetworkConfigEntry {
|
||||
zone: args.zone.expect("Please specifiy a zone with the -z flag"),
|
||||
capacity,
|
||||
tag: args.tag.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
Some(old) => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
_ => old.capacity,
|
||||
};
|
||||
NetworkConfigEntry {
|
||||
zone: args.zone.unwrap_or_else(|| old.zone.to_string()),
|
||||
capacity,
|
||||
tag: args.tag.unwrap_or_else(|| old.tag.to_string()),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
config.members.insert(added_node, new_entry);
|
||||
config.version += 1;
|
||||
|
||||
rpc_cli
|
||||
.call(
|
||||
&rpc_host,
|
||||
&Message::AdvertiseConfig(config),
|
||||
ADMIN_RPC_TIMEOUT,
|
||||
)
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_remove(
|
||||
rpc_cli: RpcAddrClient<Message>,
|
||||
rpc_host: SocketAddr,
|
||||
args: RemoveNodeOpt,
|
||||
) -> Result<(), Error> {
|
||||
let mut config = match rpc_cli
|
||||
.call(&rpc_host, &Message::PullConfig, ADMIN_RPC_TIMEOUT)
|
||||
.await??
|
||||
{
|
||||
Message::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
let deleted_node = find_matching_node(config.members.keys().cloned(), &args.node_id)?;
|
||||
|
||||
if !args.yes {
|
||||
return Err(Error::Message(format!(
|
||||
"Add the flag --yes to really remove {:?} from the cluster",
|
||||
deleted_node
|
||||
)));
|
||||
}
|
||||
|
||||
config.members.remove(&deleted_node);
|
||||
config.version += 1;
|
||||
|
||||
rpc_cli
|
||||
.call(
|
||||
&rpc_host,
|
||||
&Message::AdvertiseConfig(config),
|
||||
ADMIN_RPC_TIMEOUT,
|
||||
)
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_admin(
|
||||
rpc_cli: RpcAddrClient<AdminRpc>,
|
||||
rpc_host: SocketAddr,
|
||||
args: AdminRpc,
|
||||
) -> Result<(), Error> {
|
||||
match rpc_cli.call(&rpc_host, args, ADMIN_RPC_TIMEOUT).await?? {
|
||||
AdminRpc::Ok(msg) => {
|
||||
println!("{}", msg);
|
||||
}
|
||||
AdminRpc::BucketList(bl) => {
|
||||
println!("List of buckets:");
|
||||
for bucket in bl {
|
||||
println!("{}", bucket);
|
||||
}
|
||||
}
|
||||
AdminRpc::BucketInfo(bucket) => {
|
||||
print_bucket_info(&bucket);
|
||||
}
|
||||
AdminRpc::KeyList(kl) => {
|
||||
println!("List of keys:");
|
||||
for key in kl {
|
||||
println!("{}\t{}", key.0, key.1);
|
||||
}
|
||||
}
|
||||
AdminRpc::KeyInfo(key) => {
|
||||
print_key_info(&key);
|
||||
}
|
||||
r => {
|
||||
error!("Unexpected response: {:?}", r);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_key_info(key: &Key) {
|
||||
println!("Key name: {}", key.name.get());
|
||||
println!("Key ID: {}", key.key_id);
|
||||
println!("Secret key: {}", key.secret_key);
|
||||
if key.deleted.get() {
|
||||
println!("Key is deleted.");
|
||||
} else {
|
||||
println!("Authorized buckets:");
|
||||
for (b, _, perm) in key.authorized_buckets.items().iter() {
|
||||
println!("- {} R:{} W:{}", b, perm.allow_read, perm.allow_write);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_bucket_info(bucket: &Bucket) {
|
||||
println!("Bucket name: {}", bucket.name);
|
||||
match bucket.state.get() {
|
||||
BucketState::Deleted => println!("Bucket is deleted."),
|
||||
BucketState::Present(p) => {
|
||||
println!("Authorized keys:");
|
||||
for (k, _, perm) in p.authorized_keys.items().iter() {
|
||||
println!("- {} R:{} W:{}", k, perm.allow_read, perm.allow_write);
|
||||
}
|
||||
println!("Website access: {}", p.website.get());
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use garage_util::error::*;
|
||||
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::system::*;
|
||||
use garage_rpc::*;
|
||||
|
||||
use crate::admin::*;
|
||||
use crate::cli::*;
|
||||
|
||||
pub async fn cli_command_dispatch(
|
||||
cmd: Command,
|
||||
system_rpc_endpoint: &Endpoint<SystemRpc, ()>,
|
||||
admin_rpc_endpoint: &Endpoint<AdminRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
) -> Result<(), Error> {
|
||||
match cmd {
|
||||
Command::Status => cmd_status(system_rpc_endpoint, rpc_host).await,
|
||||
Command::Node(NodeOperation::Connect(connect_opt)) => {
|
||||
cmd_connect(system_rpc_endpoint, rpc_host, connect_opt).await
|
||||
}
|
||||
Command::Node(NodeOperation::Configure(configure_opt)) => {
|
||||
cmd_configure(system_rpc_endpoint, rpc_host, configure_opt).await
|
||||
}
|
||||
Command::Node(NodeOperation::Remove(remove_opt)) => {
|
||||
cmd_remove(system_rpc_endpoint, rpc_host, remove_opt).await
|
||||
}
|
||||
Command::Bucket(bo) => {
|
||||
cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::BucketOperation(bo)).await
|
||||
}
|
||||
Command::Key(ko) => {
|
||||
cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::KeyOperation(ko)).await
|
||||
}
|
||||
Command::Repair(ro) => {
|
||||
cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::LaunchRepair(ro)).await
|
||||
}
|
||||
Command::Stats(so) => cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::Stats(so)).await,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cmd_status(rpc_cli: &Endpoint<SystemRpc, ()>, rpc_host: NodeID) -> Result<(), Error> {
|
||||
let status = match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::GetKnownNodes, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::ReturnKnownNodes(nodes) => nodes,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
let config = match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::PullConfig, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
println!("==== HEALTHY NODES ====");
|
||||
let mut healthy_nodes = vec!["ID\tHostname\tAddress\tTag\tZone\tCapacity".to_string()];
|
||||
for adv in status.iter().filter(|adv| adv.is_up) {
|
||||
if let Some(cfg) = config.members.get(&adv.id) {
|
||||
healthy_nodes.push(format!(
|
||||
"{id:?}\t{host}\t{addr}\t[{tag}]\t{zone}\t{capacity}",
|
||||
id = adv.id,
|
||||
host = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
tag = cfg.tag,
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
));
|
||||
} else {
|
||||
healthy_nodes.push(format!(
|
||||
"{id:?}\t{h}\t{addr}\tNO ROLE ASSIGNED",
|
||||
id = adv.id,
|
||||
h = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
));
|
||||
}
|
||||
}
|
||||
format_table(healthy_nodes);
|
||||
|
||||
let status_keys = status.iter().map(|adv| adv.id).collect::<HashSet<_>>();
|
||||
let failure_case_1 = status.iter().any(|adv| !adv.is_up);
|
||||
let failure_case_2 = config
|
||||
.members
|
||||
.iter()
|
||||
.any(|(id, _)| !status_keys.contains(id));
|
||||
if failure_case_1 || failure_case_2 {
|
||||
println!("\n==== FAILED NODES ====");
|
||||
let mut failed_nodes =
|
||||
vec!["ID\tHostname\tAddress\tTag\tZone\tCapacity\tLast seen".to_string()];
|
||||
for adv in status.iter().filter(|adv| !adv.is_up) {
|
||||
if let Some(cfg) = config.members.get(&adv.id) {
|
||||
failed_nodes.push(format!(
|
||||
"{id:?}\t{host}\t{addr}\t[{tag}]\t{zone}\t{capacity}\t{last_seen}",
|
||||
id = adv.id,
|
||||
host = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
tag = cfg.tag,
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
last_seen = adv
|
||||
.last_seen_secs_ago
|
||||
.map(|s| format!("{}s ago", s))
|
||||
.unwrap_or_else(|| "never seen".into()),
|
||||
));
|
||||
}
|
||||
}
|
||||
for (id, cfg) in config.members.iter() {
|
||||
if !status_keys.contains(id) {
|
||||
failed_nodes.push(format!(
|
||||
"{id:?}\t??\t??\t[{tag}]\t{zone}\t{capacity}\tnever seen",
|
||||
id = id,
|
||||
tag = cfg.tag,
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
format_table(failed_nodes);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_connect(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: ConnectNodeOpt,
|
||||
) -> Result<(), Error> {
|
||||
match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::Connect(args.node), PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::Ok => {
|
||||
println!("Success.");
|
||||
Ok(())
|
||||
}
|
||||
r => Err(Error::BadRpc(format!("Unexpected response: {:?}", r))),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cmd_configure(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: ConfigureNodeOpt,
|
||||
) -> Result<(), Error> {
|
||||
let status = match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::GetKnownNodes, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::ReturnKnownNodes(nodes) => nodes,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
let added_node = find_matching_node(status.iter().map(|adv| adv.id), &args.node_id)?;
|
||||
|
||||
let mut config = match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::PullConfig, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
for replaced in args.replace.iter() {
|
||||
let replaced_node = find_matching_node(config.members.keys().cloned(), replaced)?;
|
||||
if config.members.remove(&replaced_node).is_none() {
|
||||
return Err(Error::Message(format!(
|
||||
"Cannot replace node {:?} as it is not in current configuration",
|
||||
replaced_node
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
if args.capacity.is_some() && args.gateway {
|
||||
return Err(Error::Message(
|
||||
"-c and -g are mutually exclusive, please configure node either with c>0 to act as a storage node or with -g to act as a gateway node".into()));
|
||||
}
|
||||
if args.capacity == Some(0) {
|
||||
return Err(Error::Message("Invalid capacity value: 0".into()));
|
||||
}
|
||||
|
||||
let new_entry = match config.members.get(&added_node) {
|
||||
None => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
_ => return Err(Error::Message(
|
||||
"Please specify a capacity with the -c flag, or set node explicitly as gateway with -g".into())),
|
||||
};
|
||||
NetworkConfigEntry {
|
||||
zone: args.zone.ok_or("Please specifiy a zone with the -z flag")?,
|
||||
capacity,
|
||||
tag: args.tag.unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
Some(old) => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
_ => old.capacity,
|
||||
};
|
||||
NetworkConfigEntry {
|
||||
zone: args.zone.unwrap_or_else(|| old.zone.to_string()),
|
||||
capacity,
|
||||
tag: args.tag.unwrap_or_else(|| old.tag.to_string()),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
config.members.insert(added_node, new_entry);
|
||||
config.version += 1;
|
||||
|
||||
rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::AdvertiseConfig(config), PRIO_NORMAL)
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_remove(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: RemoveNodeOpt,
|
||||
) -> Result<(), Error> {
|
||||
let mut config = match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::PullConfig, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::AdvertiseConfig(cfg) => cfg,
|
||||
resp => return Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
};
|
||||
|
||||
let deleted_node = find_matching_node(config.members.keys().cloned(), &args.node_id)?;
|
||||
|
||||
if !args.yes {
|
||||
return Err(Error::Message(format!(
|
||||
"Add the flag --yes to really remove {:?} from the cluster",
|
||||
deleted_node
|
||||
)));
|
||||
}
|
||||
|
||||
config.members.remove(&deleted_node);
|
||||
config.version += 1;
|
||||
|
||||
rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::AdvertiseConfig(config), PRIO_NORMAL)
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_admin(
|
||||
rpc_cli: &Endpoint<AdminRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: AdminRpc,
|
||||
) -> Result<(), Error> {
|
||||
match rpc_cli.call(&rpc_host, &args, PRIO_NORMAL).await?? {
|
||||
AdminRpc::Ok(msg) => {
|
||||
println!("{}", msg);
|
||||
}
|
||||
AdminRpc::BucketList(bl) => {
|
||||
println!("List of buckets:");
|
||||
for bucket in bl {
|
||||
println!("{}", bucket);
|
||||
}
|
||||
}
|
||||
AdminRpc::BucketInfo(bucket) => {
|
||||
print_bucket_info(&bucket);
|
||||
}
|
||||
AdminRpc::KeyList(kl) => {
|
||||
println!("List of keys:");
|
||||
for key in kl {
|
||||
println!("{}\t{}", key.0, key.1);
|
||||
}
|
||||
}
|
||||
AdminRpc::KeyInfo(key) => {
|
||||
print_key_info(&key);
|
||||
}
|
||||
r => {
|
||||
error!("Unexpected response: {:?}", r);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- Utility functions ----
|
||||
@@ -0,0 +1,67 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use log::warn;
|
||||
|
||||
use garage_util::error::*;
|
||||
|
||||
pub const READ_KEY_ERROR: &str = "Unable to read node key. It will be generated by your garage node the first time is it launched. Ensure that your garage node is currently running. (The node key is supposed to be stored in your metadata directory.)";
|
||||
|
||||
pub fn node_id_command(config_file: PathBuf, quiet: bool) -> Result<(), Error> {
|
||||
let config = garage_util::config::read_config(config_file.clone()).err_context(format!(
|
||||
"Unable to read configuration file {}",
|
||||
config_file.to_string_lossy(),
|
||||
))?;
|
||||
|
||||
let node_id =
|
||||
garage_rpc::system::read_node_id(&config.metadata_dir).err_context(READ_KEY_ERROR)?;
|
||||
|
||||
let idstr = if let Some(addr) = config.rpc_public_addr {
|
||||
let idstr = format!("{}@{}", hex::encode(&node_id), addr);
|
||||
println!("{}", idstr);
|
||||
idstr
|
||||
} else {
|
||||
let idstr = hex::encode(&node_id);
|
||||
println!("{}", idstr);
|
||||
|
||||
if !quiet {
|
||||
warn!("WARNING: I don't know the public address to reach this node.");
|
||||
warn!("In all of the instructions below, replace 127.0.0.1:{} by the appropriate address and port.", config.rpc_bind_addr.port());
|
||||
}
|
||||
|
||||
format!("{}@127.0.0.1:{}", idstr, config.rpc_bind_addr.port())
|
||||
};
|
||||
|
||||
if !quiet {
|
||||
eprintln!();
|
||||
eprintln!(
|
||||
"To instruct a node to connect to this node, run the following command on that node:"
|
||||
);
|
||||
eprintln!(" garage [-c <config file path>] node connect {}", idstr);
|
||||
eprintln!();
|
||||
eprintln!("Or instruct them to connect from here by running:");
|
||||
eprintln!(
|
||||
" garage -c {} -h <remote node> node connect {}",
|
||||
config_file.to_string_lossy(),
|
||||
idstr
|
||||
);
|
||||
eprintln!(
|
||||
"where <remote_node> is their own node identifier in the format: <pubkey>@<ip>:<port>"
|
||||
);
|
||||
eprintln!();
|
||||
eprintln!("This node identifier can also be added as a bootstrap node in other node's garage.toml files:");
|
||||
eprintln!(" bootstrap_peers = [");
|
||||
eprintln!(" \"{}\",", idstr);
|
||||
eprintln!(" ...");
|
||||
eprintln!(" ]");
|
||||
eprintln!();
|
||||
eprintln!(
|
||||
r#"Security notice: Garage's intra-cluster communications are secured primarily by the shared
|
||||
secret value rpc_secret. However, an attacker that knows rpc_secret (for example if it
|
||||
leaks) cannot connect if they do not know any of the identifiers of the nodes in the
|
||||
cluster. It is thus a good security measure to try to keep them secret if possible.
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub(crate) mod cmd;
|
||||
pub(crate) mod init;
|
||||
pub(crate) mod structs;
|
||||
pub(crate) mod util;
|
||||
|
||||
pub(crate) use cmd::*;
|
||||
pub(crate) use init::*;
|
||||
pub(crate) use structs::*;
|
||||
pub(crate) use util::*;
|
||||
@@ -0,0 +1,302 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use structopt::StructOpt;
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub enum Command {
|
||||
/// Run Garage server
|
||||
#[structopt(name = "server")]
|
||||
Server,
|
||||
|
||||
/// Print identifier (public key) of this Garage node
|
||||
#[structopt(name = "node-id")]
|
||||
NodeId(NodeIdOpt),
|
||||
|
||||
/// Get network status
|
||||
#[structopt(name = "status")]
|
||||
Status,
|
||||
|
||||
/// Garage node operations
|
||||
#[structopt(name = "node")]
|
||||
Node(NodeOperation),
|
||||
|
||||
/// Bucket operations
|
||||
#[structopt(name = "bucket")]
|
||||
Bucket(BucketOperation),
|
||||
|
||||
/// Key operations
|
||||
#[structopt(name = "key")]
|
||||
Key(KeyOperation),
|
||||
|
||||
/// Start repair of node data
|
||||
#[structopt(name = "repair")]
|
||||
Repair(RepairOpt),
|
||||
|
||||
/// Gather node statistics
|
||||
#[structopt(name = "stats")]
|
||||
Stats(StatsOpt),
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub enum NodeOperation {
|
||||
/// Connect to Garage node that is currently isolated from the system
|
||||
#[structopt(name = "connect")]
|
||||
Connect(ConnectNodeOpt),
|
||||
|
||||
/// Configure Garage node
|
||||
#[structopt(name = "configure")]
|
||||
Configure(ConfigureNodeOpt),
|
||||
|
||||
/// Remove Garage node from cluster
|
||||
#[structopt(name = "remove")]
|
||||
Remove(RemoveNodeOpt),
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct NodeIdOpt {
|
||||
/// Do not print usage instructions to stderr
|
||||
#[structopt(short = "q", long = "quiet")]
|
||||
pub(crate) quiet: bool,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct ConnectNodeOpt {
|
||||
/// Node public key and address, in the format:
|
||||
/// `<public key hexadecimal>@<ip or hostname>:<port>`
|
||||
pub(crate) node: String,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct ConfigureNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
pub(crate) node_id: String,
|
||||
|
||||
/// Location (zone or datacenter) of the node
|
||||
#[structopt(short = "z", long = "zone")]
|
||||
pub(crate) zone: Option<String>,
|
||||
|
||||
/// Capacity (in relative terms, use 1 to represent your smallest server)
|
||||
#[structopt(short = "c", long = "capacity")]
|
||||
pub(crate) capacity: Option<u32>,
|
||||
|
||||
/// Gateway-only node
|
||||
#[structopt(short = "g", long = "gateway")]
|
||||
pub(crate) gateway: bool,
|
||||
|
||||
/// Optional node tag
|
||||
#[structopt(short = "t", long = "tag")]
|
||||
pub(crate) tag: Option<String>,
|
||||
|
||||
/// Replaced node(s): list of node IDs that will be removed from the current cluster
|
||||
#[structopt(long = "replace")]
|
||||
pub(crate) replace: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct RemoveNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
pub(crate) node_id: String,
|
||||
|
||||
/// If this flag is not given, the node won't be removed
|
||||
#[structopt(long = "yes")]
|
||||
pub(crate) yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub enum BucketOperation {
|
||||
/// List buckets
|
||||
#[structopt(name = "list")]
|
||||
List,
|
||||
|
||||
/// Get bucket info
|
||||
#[structopt(name = "info")]
|
||||
Info(BucketOpt),
|
||||
|
||||
/// Create bucket
|
||||
#[structopt(name = "create")]
|
||||
Create(BucketOpt),
|
||||
|
||||
/// Delete bucket
|
||||
#[structopt(name = "delete")]
|
||||
Delete(DeleteBucketOpt),
|
||||
|
||||
/// Allow key to read or write to bucket
|
||||
#[structopt(name = "allow")]
|
||||
Allow(PermBucketOpt),
|
||||
|
||||
/// Deny key from reading or writing to bucket
|
||||
#[structopt(name = "deny")]
|
||||
Deny(PermBucketOpt),
|
||||
|
||||
/// Expose as website or not
|
||||
#[structopt(name = "website")]
|
||||
Website(WebsiteOpt),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct WebsiteOpt {
|
||||
/// Create
|
||||
#[structopt(long = "allow")]
|
||||
pub allow: bool,
|
||||
|
||||
/// Delete
|
||||
#[structopt(long = "deny")]
|
||||
pub deny: bool,
|
||||
|
||||
/// Bucket name
|
||||
pub bucket: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct BucketOpt {
|
||||
/// Bucket name
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct DeleteBucketOpt {
|
||||
/// Bucket name
|
||||
pub name: String,
|
||||
|
||||
/// If this flag is not given, the bucket won't be deleted
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct PermBucketOpt {
|
||||
/// Access key name or ID
|
||||
#[structopt(long = "key")]
|
||||
pub key_pattern: String,
|
||||
|
||||
/// Allow/deny read operations
|
||||
#[structopt(long = "read")]
|
||||
pub read: bool,
|
||||
|
||||
/// Allow/deny write operations
|
||||
#[structopt(long = "write")]
|
||||
pub write: bool,
|
||||
|
||||
/// Bucket name
|
||||
pub bucket: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub enum KeyOperation {
|
||||
/// List keys
|
||||
#[structopt(name = "list")]
|
||||
List,
|
||||
|
||||
/// Get key info
|
||||
#[structopt(name = "info")]
|
||||
Info(KeyOpt),
|
||||
|
||||
/// Create new key
|
||||
#[structopt(name = "new")]
|
||||
New(KeyNewOpt),
|
||||
|
||||
/// Rename key
|
||||
#[structopt(name = "rename")]
|
||||
Rename(KeyRenameOpt),
|
||||
|
||||
/// Delete key
|
||||
#[structopt(name = "delete")]
|
||||
Delete(KeyDeleteOpt),
|
||||
|
||||
/// Import key
|
||||
#[structopt(name = "import")]
|
||||
Import(KeyImportOpt),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyNewOpt {
|
||||
/// Name of the key
|
||||
#[structopt(long = "name", default_value = "Unnamed key")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyRenameOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
|
||||
/// New name of the key
|
||||
pub new_name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyDeleteOpt {
|
||||
/// ID or name of the key
|
||||
pub key_pattern: String,
|
||||
|
||||
/// Confirm deletion
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
pub struct KeyImportOpt {
|
||||
/// Access key ID
|
||||
pub key_id: String,
|
||||
|
||||
/// Secret access key
|
||||
pub secret_key: String,
|
||||
|
||||
/// Key name
|
||||
#[structopt(short = "n", default_value = "Imported key")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Clone)]
|
||||
pub struct RepairOpt {
|
||||
/// Launch repair operation on all nodes
|
||||
#[structopt(short = "a", long = "all-nodes")]
|
||||
pub all_nodes: bool,
|
||||
|
||||
/// Confirm the launch of the repair operation
|
||||
#[structopt(long = "yes")]
|
||||
pub yes: bool,
|
||||
|
||||
#[structopt(subcommand)]
|
||||
pub what: RepairWhat,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Eq, PartialEq, Clone)]
|
||||
pub enum RepairWhat {
|
||||
/// Only do a full sync of metadata tables
|
||||
#[structopt(name = "tables")]
|
||||
Tables,
|
||||
/// Only repair (resync/rebalance) the set of stored blocks
|
||||
#[structopt(name = "blocks")]
|
||||
Blocks,
|
||||
/// Only redo the propagation of object deletions to the version table (slow)
|
||||
#[structopt(name = "versions")]
|
||||
Versions,
|
||||
/// Only redo the propagation of version deletions to the block ref table (extremely slow)
|
||||
#[structopt(name = "block_refs")]
|
||||
BlockRefs,
|
||||
/// Verify integrity of all blocks on disc (extremely slow, i/o intensive)
|
||||
#[structopt(name = "scrub")]
|
||||
Scrub {
|
||||
/// Tranquility factor (see tranquilizer documentation)
|
||||
#[structopt(name = "tranquility", default_value = "2")]
|
||||
tranquility: u32,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug, Clone)]
|
||||
pub struct StatsOpt {
|
||||
/// Gather statistics from all nodes
|
||||
#[structopt(short = "a", long = "all-nodes")]
|
||||
pub all_nodes: bool,
|
||||
|
||||
/// Gather detailed statistics (this can be long)
|
||||
#[structopt(short = "d", long = "detailed")]
|
||||
pub detailed: bool,
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use garage_util::data::Uuid;
|
||||
use garage_util::error::*;
|
||||
|
||||
use garage_model::bucket_table::*;
|
||||
use garage_model::key_table::*;
|
||||
|
||||
pub fn print_key_info(key: &Key) {
|
||||
println!("Key name: {}", key.name.get());
|
||||
println!("Key ID: {}", key.key_id);
|
||||
println!("Secret key: {}", key.secret_key);
|
||||
if key.deleted.get() {
|
||||
println!("Key is deleted.");
|
||||
} else {
|
||||
println!("Authorized buckets:");
|
||||
for (b, _, perm) in key.authorized_buckets.items().iter() {
|
||||
println!("- {} R:{} W:{}", b, perm.allow_read, perm.allow_write);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_bucket_info(bucket: &Bucket) {
|
||||
println!("Bucket name: {}", bucket.name);
|
||||
match bucket.state.get() {
|
||||
BucketState::Deleted => println!("Bucket is deleted."),
|
||||
BucketState::Present(p) => {
|
||||
println!("Authorized keys:");
|
||||
for (k, _, perm) in p.authorized_keys.items().iter() {
|
||||
println!("- {} R:{} W:{}", k, perm.allow_read, perm.allow_write);
|
||||
}
|
||||
println!("Website access: {}", p.website.get());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub fn format_table(data: Vec<String>) {
|
||||
let data = data
|
||||
.iter()
|
||||
.map(|s| s.split('\t').collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let columns = data.iter().map(|row| row.len()).fold(0, std::cmp::max);
|
||||
let mut column_size = vec![0; columns];
|
||||
|
||||
let mut out = String::new();
|
||||
|
||||
for row in data.iter() {
|
||||
for (i, col) in row.iter().enumerate() {
|
||||
column_size[i] = std::cmp::max(column_size[i], col.chars().count());
|
||||
}
|
||||
}
|
||||
|
||||
for row in data.iter() {
|
||||
for (col, col_len) in row[..row.len() - 1].iter().zip(column_size.iter()) {
|
||||
out.push_str(col);
|
||||
(0..col_len - col.chars().count() + 2).for_each(|_| out.push(' '));
|
||||
}
|
||||
out.push_str(row[row.len() - 1]);
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
print!("{}", out);
|
||||
}
|
||||
|
||||
pub fn find_matching_node(
|
||||
cand: impl std::iter::Iterator<Item = Uuid>,
|
||||
pattern: &str,
|
||||
) -> Result<Uuid, Error> {
|
||||
let mut candidates = vec![];
|
||||
for c in cand {
|
||||
if hex::encode(&c).starts_with(&pattern) {
|
||||
candidates.push(c);
|
||||
}
|
||||
}
|
||||
if candidates.len() != 1 {
|
||||
Err(Error::Message(format!(
|
||||
"{} nodes match '{}'",
|
||||
candidates.len(),
|
||||
pattern,
|
||||
)))
|
||||
} else {
|
||||
Ok(candidates[0])
|
||||
}
|
||||
}
|
||||
+91
-51
@@ -4,39 +4,47 @@
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
mod admin_rpc;
|
||||
mod admin;
|
||||
mod cli;
|
||||
mod repair;
|
||||
mod server;
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use structopt::StructOpt;
|
||||
|
||||
use garage_util::config::TlsConfig;
|
||||
use garage_util::error::Error;
|
||||
use netapp::util::parse_and_resolve_peer_addr;
|
||||
use netapp::NetworkKey;
|
||||
|
||||
use garage_rpc::membership::*;
|
||||
use garage_rpc::rpc_client::*;
|
||||
use garage_util::error::*;
|
||||
|
||||
use admin_rpc::*;
|
||||
use garage_rpc::system::*;
|
||||
use garage_rpc::*;
|
||||
|
||||
use admin::*;
|
||||
use cli::*;
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
#[structopt(name = "garage")]
|
||||
struct Opt {
|
||||
/// RPC connect to this host to execute client operations
|
||||
#[structopt(short = "h", long = "rpc-host", default_value = "127.0.0.1:3901", parse(try_from_str = parse_address))]
|
||||
pub rpc_host: SocketAddr,
|
||||
/// Host to connect to for admin operations, in the format:
|
||||
/// <public-key>@<ip>:<port>
|
||||
#[structopt(short = "h", long = "rpc-host", env = "GARAGE_RPC_HOST")]
|
||||
pub rpc_host: Option<String>,
|
||||
|
||||
#[structopt(long = "ca-cert")]
|
||||
pub ca_cert: Option<String>,
|
||||
#[structopt(long = "client-cert")]
|
||||
pub client_cert: Option<String>,
|
||||
#[structopt(long = "client-key")]
|
||||
pub client_key: Option<String>,
|
||||
/// RPC secret network key for admin operations
|
||||
#[structopt(short = "s", long = "rpc-secret", env = "GARAGE_RPC_SECRET")]
|
||||
pub rpc_secret: Option<String>,
|
||||
|
||||
/// Configuration file (garage.toml)
|
||||
#[structopt(
|
||||
short = "c",
|
||||
long = "config",
|
||||
env = "GARAGE_CONFIG_FILE",
|
||||
default_value = "/etc/garage.toml"
|
||||
)]
|
||||
pub config_file: PathBuf,
|
||||
|
||||
#[structopt(subcommand)]
|
||||
cmd: Command,
|
||||
@@ -44,55 +52,87 @@ struct Opt {
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
if std::env::var("RUST_LOG").is_err() {
|
||||
std::env::set_var("RUST_LOG", "garage=info")
|
||||
}
|
||||
pretty_env_logger::init();
|
||||
sodiumoxide::init().expect("Unable to init sodiumoxide");
|
||||
|
||||
let opt = Opt::from_args();
|
||||
|
||||
let res = if let Command::Server(server_opt) = opt.cmd {
|
||||
// Abort on panic (same behavior as in Go)
|
||||
std::panic::set_hook(Box::new(|panic_info| {
|
||||
error!("{}", panic_info.to_string());
|
||||
std::process::abort();
|
||||
}));
|
||||
let res = match opt.cmd {
|
||||
Command::Server => {
|
||||
// Abort on panic (same behavior as in Go)
|
||||
std::panic::set_hook(Box::new(|panic_info| {
|
||||
error!("{}", panic_info.to_string());
|
||||
std::process::abort();
|
||||
}));
|
||||
|
||||
server::run_server(server_opt.config_file).await
|
||||
} else {
|
||||
cli_command(opt).await
|
||||
server::run_server(opt.config_file).await
|
||||
}
|
||||
Command::NodeId(node_id_opt) => node_id_command(opt.config_file, node_id_opt.quiet),
|
||||
_ => cli_command(opt).await,
|
||||
};
|
||||
|
||||
if let Err(e) = res {
|
||||
error!("{}", e);
|
||||
eprintln!("Error: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async fn cli_command(opt: Opt) -> Result<(), Error> {
|
||||
let tls_config = match (opt.ca_cert, opt.client_cert, opt.client_key) {
|
||||
(Some(ca_cert), Some(client_cert), Some(client_key)) => Some(TlsConfig {
|
||||
ca_cert,
|
||||
node_cert: client_cert,
|
||||
node_key: client_key,
|
||||
}),
|
||||
(None, None, None) => None,
|
||||
_ => {
|
||||
warn!("Missing one of: --ca-cert, --node-cert, --node-key. Not using TLS.");
|
||||
None
|
||||
let config = if opt.rpc_secret.is_none() || opt.rpc_host.is_none() {
|
||||
Some(garage_util::config::read_config(opt.config_file.clone())
|
||||
.err_context(format!("Unable to read configuration file {}. Configuration file is needed because -h or -s is not provided on the command line.", opt.config_file.to_string_lossy()))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Find and parse network RPC secret
|
||||
let net_key_hex_str = opt
|
||||
.rpc_secret
|
||||
.as_ref()
|
||||
.or_else(|| config.as_ref().map(|c| &c.rpc_secret))
|
||||
.ok_or("No RPC secret provided")?;
|
||||
let network_key = NetworkKey::from_slice(
|
||||
&hex::decode(net_key_hex_str).err_context("Invalid RPC secret key (bad hex)")?[..],
|
||||
)
|
||||
.ok_or("Invalid RPC secret provided (wrong length)")?;
|
||||
|
||||
// Generate a temporary keypair for our RPC client
|
||||
let (_pk, sk) = sodiumoxide::crypto::sign::ed25519::gen_keypair();
|
||||
|
||||
let netapp = NetApp::new(network_key, sk);
|
||||
|
||||
// Find and parse the address of the target host
|
||||
let (id, addr) = if let Some(h) = opt.rpc_host {
|
||||
let (id, addrs) = parse_and_resolve_peer_addr(&h).ok_or_else(|| format!("Invalid RPC remote node identifier: {}. Expected format is <pubkey>@<IP or hostname>:<port>.", h))?;
|
||||
(id, addrs[0])
|
||||
} else {
|
||||
let node_id = garage_rpc::system::read_node_id(&config.as_ref().unwrap().metadata_dir)
|
||||
.err_context(READ_KEY_ERROR)?;
|
||||
if let Some(a) = config.as_ref().map(|c| c.rpc_public_addr).flatten() {
|
||||
(node_id, a)
|
||||
} else {
|
||||
let default_addr = SocketAddr::new(
|
||||
"127.0.0.1".parse().unwrap(),
|
||||
config.as_ref().unwrap().rpc_bind_addr.port(),
|
||||
);
|
||||
warn!(
|
||||
"Trying to contact Garage node at default address {}",
|
||||
default_addr
|
||||
);
|
||||
warn!("If this doesn't work, consider adding rpc_public_addr in your config file or specifying the -h command line parameter.");
|
||||
(node_id, default_addr)
|
||||
}
|
||||
};
|
||||
|
||||
let rpc_http_cli =
|
||||
Arc::new(RpcHttpClient::new(8, &tls_config).expect("Could not create RPC client"));
|
||||
let membership_rpc_cli =
|
||||
RpcAddrClient::new(rpc_http_cli.clone(), MEMBERSHIP_RPC_PATH.to_string());
|
||||
let admin_rpc_cli = RpcAddrClient::new(rpc_http_cli.clone(), ADMIN_RPC_PATH.to_string());
|
||||
// Connect to target host
|
||||
netapp.clone().try_connect(addr, id).await
|
||||
.err_context("Unable to connect to destination RPC host. Check that you are using the same value of rpc_secret as them, and that you have their correct public key.")?;
|
||||
|
||||
cli_cmd(opt.cmd, membership_rpc_cli, admin_rpc_cli, opt.rpc_host).await
|
||||
}
|
||||
let system_rpc_endpoint = netapp.endpoint::<SystemRpc, ()>(SYSTEM_RPC_PATH.into());
|
||||
let admin_rpc_endpoint = netapp.endpoint::<AdminRpc, ()>(ADMIN_RPC_PATH.into());
|
||||
|
||||
fn parse_address(address: &str) -> Result<SocketAddr, String> {
|
||||
use std::net::ToSocketAddrs;
|
||||
address
|
||||
.to_socket_addrs()
|
||||
.map_err(|_| format!("Could not resolve {}", address))?
|
||||
.next()
|
||||
.ok_or_else(|| format!("Could not resolve {}", address))
|
||||
cli_command_dispatch(opt.cmd, &system_rpc_endpoint, &admin_rpc_endpoint, id).await
|
||||
}
|
||||
|
||||
+31
-41
@@ -27,42 +27,38 @@ impl Repair {
|
||||
opt: RepairOpt,
|
||||
must_exit: watch::Receiver<bool>,
|
||||
) -> Result<(), Error> {
|
||||
let todo = |x| opt.what.as_ref().map(|y| *y == x).unwrap_or(true);
|
||||
|
||||
if todo(RepairWhat::Tables) {
|
||||
info!("Launching a full sync of tables");
|
||||
self.garage.bucket_table.syncer.add_full_sync();
|
||||
self.garage.object_table.syncer.add_full_sync();
|
||||
self.garage.version_table.syncer.add_full_sync();
|
||||
self.garage.block_ref_table.syncer.add_full_sync();
|
||||
self.garage.key_table.syncer.add_full_sync();
|
||||
match opt.what {
|
||||
RepairWhat::Tables => {
|
||||
info!("Launching a full sync of tables");
|
||||
self.garage.bucket_table.syncer.add_full_sync();
|
||||
self.garage.object_table.syncer.add_full_sync();
|
||||
self.garage.version_table.syncer.add_full_sync();
|
||||
self.garage.block_ref_table.syncer.add_full_sync();
|
||||
self.garage.key_table.syncer.add_full_sync();
|
||||
}
|
||||
RepairWhat::Versions => {
|
||||
info!("Repairing the versions table");
|
||||
self.repair_versions(&must_exit).await?;
|
||||
}
|
||||
RepairWhat::BlockRefs => {
|
||||
info!("Repairing the block refs table");
|
||||
self.repair_block_ref(&must_exit).await?;
|
||||
}
|
||||
RepairWhat::Blocks => {
|
||||
info!("Repairing the stored blocks");
|
||||
self.garage
|
||||
.block_manager
|
||||
.repair_data_store(&must_exit)
|
||||
.await?;
|
||||
}
|
||||
RepairWhat::Scrub { tranquility } => {
|
||||
info!("Verifying integrity of stored blocks");
|
||||
self.garage
|
||||
.block_manager
|
||||
.scrub_data_store(&must_exit, tranquility)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: wait for full sync to finish before proceeding to the rest?
|
||||
|
||||
if todo(RepairWhat::Versions) {
|
||||
info!("Repairing the versions table");
|
||||
self.repair_versions(&must_exit).await?;
|
||||
}
|
||||
|
||||
if todo(RepairWhat::BlockRefs) {
|
||||
info!("Repairing the block refs table");
|
||||
self.repair_block_ref(&must_exit).await?;
|
||||
}
|
||||
|
||||
if opt.what.is_none() {
|
||||
info!("Repairing the RC");
|
||||
self.repair_rc(&must_exit).await?;
|
||||
}
|
||||
|
||||
if todo(RepairWhat::Blocks) {
|
||||
info!("Repairing the stored blocks");
|
||||
self.garage
|
||||
.block_manager
|
||||
.repair_data_store(&must_exit)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -150,10 +146,4 @@ impl Repair {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn repair_rc(&self, _must_exit: &watch::Receiver<bool>) -> Result<(), Error> {
|
||||
// TODO
|
||||
warn!("repair_rc: not implemented");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+39
-52
@@ -1,7 +1,5 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures_util::future::*;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use garage_util::background::*;
|
||||
@@ -10,20 +8,9 @@ use garage_util::error::Error;
|
||||
|
||||
use garage_api::run_api_server;
|
||||
use garage_model::garage::Garage;
|
||||
use garage_rpc::rpc_server::RpcServer;
|
||||
use garage_web::run_web_server;
|
||||
|
||||
use crate::admin_rpc::*;
|
||||
|
||||
async fn shutdown_signal(send_cancel: watch::Sender<bool>) -> Result<(), Error> {
|
||||
// Wait for the CTRL+C signal
|
||||
tokio::signal::ctrl_c()
|
||||
.await
|
||||
.expect("failed to install CTRL+C signal handler");
|
||||
info!("Received CTRL+C, shutting down.");
|
||||
send_cancel.send(true)?;
|
||||
Ok(())
|
||||
}
|
||||
use crate::admin::*;
|
||||
|
||||
async fn wait_from(mut chan: watch::Receiver<bool>) {
|
||||
while !*chan.borrow() {
|
||||
@@ -47,52 +34,52 @@ pub async fn run_server(config_file: PathBuf) -> Result<(), Error> {
|
||||
.open()
|
||||
.expect("Unable to open sled DB");
|
||||
|
||||
info!("Initialize RPC server...");
|
||||
let mut rpc_server = RpcServer::new(config.rpc_bind_addr, config.rpc_tls.clone());
|
||||
|
||||
info!("Initializing background runner...");
|
||||
let (send_cancel, watch_cancel) = watch::channel(false);
|
||||
let watch_cancel = netapp::util::watch_ctrl_c();
|
||||
let (background, await_background_done) = BackgroundRunner::new(16, watch_cancel.clone());
|
||||
|
||||
info!("Initializing Garage main data store...");
|
||||
let garage = Garage::new(config.clone(), db, background, &mut rpc_server);
|
||||
let bootstrap = garage.system.clone().bootstrap(
|
||||
config.bootstrap_peers,
|
||||
config.consul_host,
|
||||
config.consul_service_name,
|
||||
);
|
||||
let garage = Garage::new(config.clone(), db, background);
|
||||
|
||||
let run_system = tokio::spawn(garage.system.clone().run(watch_cancel.clone()));
|
||||
|
||||
info!("Crate admin RPC handler...");
|
||||
AdminRpcHandler::new(garage.clone()).register_handler(&mut rpc_server);
|
||||
AdminRpcHandler::new(garage.clone());
|
||||
|
||||
info!("Initializing RPC and API servers...");
|
||||
let run_rpc_server = Arc::new(rpc_server).run(wait_from(watch_cancel.clone()));
|
||||
let api_server = run_api_server(garage.clone(), wait_from(watch_cancel.clone()));
|
||||
let web_server = run_web_server(garage, wait_from(watch_cancel.clone()));
|
||||
info!("Initializing API server...");
|
||||
let api_server = tokio::spawn(run_api_server(
|
||||
garage.clone(),
|
||||
wait_from(watch_cancel.clone()),
|
||||
));
|
||||
|
||||
futures::try_join!(
|
||||
bootstrap.map(|()| {
|
||||
info!("Bootstrap done");
|
||||
Ok(())
|
||||
}),
|
||||
run_rpc_server.map(|rv| {
|
||||
info!("RPC server exited");
|
||||
rv
|
||||
}),
|
||||
api_server.map(|rv| {
|
||||
info!("API server exited");
|
||||
rv
|
||||
}),
|
||||
web_server.map(|rv| {
|
||||
info!("Web server exited");
|
||||
rv
|
||||
}),
|
||||
await_background_done.map(|rv| {
|
||||
info!("Background runner exited: {:?}", rv);
|
||||
Ok(())
|
||||
}),
|
||||
shutdown_signal(send_cancel),
|
||||
)?;
|
||||
info!("Initializing web server...");
|
||||
let web_server = tokio::spawn(run_web_server(
|
||||
garage.clone(),
|
||||
wait_from(watch_cancel.clone()),
|
||||
));
|
||||
|
||||
// Stuff runs
|
||||
|
||||
// When a cancel signal is sent, stuff stops
|
||||
if let Err(e) = api_server.await? {
|
||||
warn!("API server exited with error: {}", e);
|
||||
}
|
||||
if let Err(e) = web_server.await? {
|
||||
warn!("Web server exited with error: {}", e);
|
||||
}
|
||||
|
||||
// Remove RPC handlers for system to break reference cycles
|
||||
garage.system.netapp.drop_all_handlers();
|
||||
|
||||
// Await for netapp RPC system to end
|
||||
run_system.await?;
|
||||
|
||||
// Break last reference cycles so that stuff can terminate properly
|
||||
garage.break_reference_cycles();
|
||||
drop(garage);
|
||||
|
||||
// Await for all background tasks to end
|
||||
await_background_done.await?;
|
||||
|
||||
info!("Cleaning up...");
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage_model"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -13,10 +13,11 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_rpc = { version = "0.3.0", path = "../rpc" }
|
||||
garage_table = { version = "0.3.0", path = "../table" }
|
||||
garage_util = { version = "0.3.0", path = "../util" }
|
||||
garage_rpc = { version = "0.4.0", path = "../rpc" }
|
||||
garage_table = { version = "0.4.0", path = "../table" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
|
||||
async-trait = "0.1.7"
|
||||
arc-swap = "1.0"
|
||||
hex = "0.4"
|
||||
log = "0.4"
|
||||
@@ -31,3 +32,6 @@ serde_bytes = "0.11"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
|
||||
|
||||
#netapp = { version = "0.3.0", git = "https://git.deuxfleurs.fr/lx/netapp" }
|
||||
netapp = "0.3.0"
|
||||
|
||||
+565
-296
File diff suppressed because it is too large
Load Diff
+18
-28
@@ -1,11 +1,11 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use netapp::NetworkKey;
|
||||
|
||||
use garage_util::background::*;
|
||||
use garage_util::config::*;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::rpc_client::RpcHttpClient;
|
||||
use garage_rpc::rpc_server::RpcServer;
|
||||
use garage_rpc::system::System;
|
||||
|
||||
use garage_table::replication::ReplicationMode;
|
||||
use garage_table::replication::TableFullReplication;
|
||||
@@ -45,26 +45,21 @@ pub struct Garage {
|
||||
|
||||
impl Garage {
|
||||
/// Create and run garage
|
||||
pub fn new(
|
||||
config: Config,
|
||||
db: sled::Db,
|
||||
background: Arc<BackgroundRunner>,
|
||||
rpc_server: &mut RpcServer,
|
||||
) -> Arc<Self> {
|
||||
pub fn new(config: Config, db: sled::Db, background: Arc<BackgroundRunner>) -> Arc<Self> {
|
||||
let network_key = NetworkKey::from_slice(
|
||||
&hex::decode(&config.rpc_secret).expect("Invalid RPC secret key")[..],
|
||||
)
|
||||
.expect("Invalid RPC secret key");
|
||||
|
||||
let replication_mode = ReplicationMode::parse(&config.replication_mode)
|
||||
.expect("Invalid replication_mode in config file.");
|
||||
|
||||
info!("Initialize membership management system...");
|
||||
let rpc_http_client = Arc::new(
|
||||
RpcHttpClient::new(config.max_concurrent_rpc_requests, &config.rpc_tls)
|
||||
.expect("Could not create RPC client"),
|
||||
);
|
||||
let system = System::new(
|
||||
config.metadata_dir.clone(),
|
||||
rpc_http_client,
|
||||
network_key,
|
||||
background.clone(),
|
||||
rpc_server,
|
||||
replication_mode.replication_factor(),
|
||||
&config,
|
||||
);
|
||||
|
||||
let data_rep_param = TableShardedReplication {
|
||||
@@ -87,13 +82,8 @@ impl Garage {
|
||||
};
|
||||
|
||||
info!("Initialize block manager...");
|
||||
let block_manager = BlockManager::new(
|
||||
&db,
|
||||
config.data_dir.clone(),
|
||||
data_rep_param,
|
||||
system.clone(),
|
||||
rpc_server,
|
||||
);
|
||||
let block_manager =
|
||||
BlockManager::new(&db, config.data_dir.clone(), data_rep_param, system.clone());
|
||||
|
||||
info!("Initialize block_ref_table...");
|
||||
let block_ref_table = Table::new(
|
||||
@@ -104,7 +94,6 @@ impl Garage {
|
||||
system.clone(),
|
||||
&db,
|
||||
"block_ref".to_string(),
|
||||
rpc_server,
|
||||
);
|
||||
|
||||
info!("Initialize version_table...");
|
||||
@@ -117,7 +106,6 @@ impl Garage {
|
||||
system.clone(),
|
||||
&db,
|
||||
"version".to_string(),
|
||||
rpc_server,
|
||||
);
|
||||
|
||||
info!("Initialize object_table...");
|
||||
@@ -130,7 +118,6 @@ impl Garage {
|
||||
system.clone(),
|
||||
&db,
|
||||
"object".to_string(),
|
||||
rpc_server,
|
||||
);
|
||||
|
||||
info!("Initialize bucket_table...");
|
||||
@@ -140,7 +127,6 @@ impl Garage {
|
||||
system.clone(),
|
||||
&db,
|
||||
"bucket".to_string(),
|
||||
rpc_server,
|
||||
);
|
||||
|
||||
info!("Initialize key_table_table...");
|
||||
@@ -150,7 +136,6 @@ impl Garage {
|
||||
system.clone(),
|
||||
&db,
|
||||
"key".to_string(),
|
||||
rpc_server,
|
||||
);
|
||||
|
||||
info!("Initialize Garage...");
|
||||
@@ -173,4 +158,9 @@ impl Garage {
|
||||
|
||||
garage
|
||||
}
|
||||
|
||||
/// Use this for shutdown
|
||||
pub fn break_reference_cycles(&self) {
|
||||
self.block_manager.garage.swap(None);
|
||||
}
|
||||
}
|
||||
|
||||
+8
-11
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage_rpc"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -13,16 +13,17 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_util = { version = "0.3.0", path = "../util" }
|
||||
|
||||
garage_rpc_021 = { package = "garage_rpc", version = "0.2.1" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
|
||||
arc-swap = "1.0"
|
||||
bytes = "1.0"
|
||||
gethostname = "0.2"
|
||||
hex = "0.4"
|
||||
log = "0.4"
|
||||
rand = "0.8"
|
||||
sodiumoxide = { version = "0.2.5-0", package = "kuska-sodiumoxide" }
|
||||
|
||||
async-trait = "0.1.7"
|
||||
rmp-serde = "0.15"
|
||||
serde = { version = "1.0", default-features = false, features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
@@ -32,11 +33,7 @@ futures-util = "0.3"
|
||||
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
|
||||
tokio-stream = { version = "0.1", features = ["net"] }
|
||||
|
||||
http = "0.2"
|
||||
hyper = { version = "0.14", features = ["full"] }
|
||||
hyper-rustls = { version = "0.22", default-features = false }
|
||||
rustls = "0.19"
|
||||
tokio-rustls = "0.22"
|
||||
webpki = "0.21"
|
||||
|
||||
#netapp = { version = "0.3.0", git = "https://git.deuxfleurs.fr/lx/netapp" }
|
||||
netapp = "0.3.0"
|
||||
hyper = { version = "0.14", features = ["client", "http1", "runtime", "tcp"] }
|
||||
|
||||
|
||||
+113
-12
@@ -1,24 +1,31 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
|
||||
use hyper::client::Client;
|
||||
use hyper::StatusCode;
|
||||
use hyper::{Body, Method, Request};
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use netapp::NodeID;
|
||||
|
||||
use garage_util::error::Error;
|
||||
|
||||
#[derive(Deserialize, Clone)]
|
||||
struct ConsulEntry {
|
||||
#[serde(alias = "Address")]
|
||||
// ---- READING FROM CONSUL CATALOG ----
|
||||
|
||||
#[derive(Deserialize, Clone, Debug)]
|
||||
struct ConsulQueryEntry {
|
||||
#[serde(rename = "Address")]
|
||||
address: String,
|
||||
#[serde(alias = "ServicePort")]
|
||||
#[serde(rename = "ServicePort")]
|
||||
service_port: u16,
|
||||
#[serde(rename = "NodeMeta")]
|
||||
node_meta: HashMap<String, String>,
|
||||
}
|
||||
|
||||
pub async fn get_consul_nodes(
|
||||
consul_host: &str,
|
||||
consul_service_name: &str,
|
||||
) -> Result<Vec<SocketAddr>, Error> {
|
||||
) -> Result<Vec<(NodeID, SocketAddr)>, Error> {
|
||||
let url = format!(
|
||||
"http://{}/v1/catalog/service/{}",
|
||||
consul_host, consul_service_name
|
||||
@@ -36,17 +43,111 @@ pub async fn get_consul_nodes(
|
||||
}
|
||||
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await?;
|
||||
let entries = serde_json::from_slice::<Vec<ConsulEntry>>(body.as_ref())?;
|
||||
let entries = serde_json::from_slice::<Vec<ConsulQueryEntry>>(body.as_ref())?;
|
||||
|
||||
let mut ret = vec![];
|
||||
for ent in entries {
|
||||
let ip = ent
|
||||
.address
|
||||
.parse::<IpAddr>()
|
||||
.map_err(|e| Error::Message(format!("Could not parse IP address: {}", e)))?;
|
||||
ret.push(SocketAddr::new(ip, ent.service_port));
|
||||
let ip = ent.address.parse::<IpAddr>().ok();
|
||||
let pubkey = ent
|
||||
.node_meta
|
||||
.get("pubkey")
|
||||
.map(|k| hex::decode(&k).ok())
|
||||
.flatten()
|
||||
.map(|k| NodeID::from_slice(&k[..]))
|
||||
.flatten();
|
||||
if let (Some(ip), Some(pubkey)) = (ip, pubkey) {
|
||||
ret.push((pubkey, SocketAddr::new(ip, ent.service_port)));
|
||||
} else {
|
||||
warn!(
|
||||
"Could not process node spec from Consul: {:?} (invalid IP or public key)",
|
||||
ent
|
||||
);
|
||||
}
|
||||
}
|
||||
debug!("Got nodes from Consul: {:?}", ret);
|
||||
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
// ---- PUBLISHING TO CONSUL CATALOG ----
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
struct ConsulPublishEntry {
|
||||
#[serde(rename = "Node")]
|
||||
node: String,
|
||||
#[serde(rename = "Address")]
|
||||
address: IpAddr,
|
||||
#[serde(rename = "NodeMeta")]
|
||||
node_meta: HashMap<String, String>,
|
||||
#[serde(rename = "Service")]
|
||||
service: ConsulPublishService,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone, Debug)]
|
||||
struct ConsulPublishService {
|
||||
#[serde(rename = "ID")]
|
||||
service_id: String,
|
||||
#[serde(rename = "Service")]
|
||||
service_name: String,
|
||||
#[serde(rename = "Tags")]
|
||||
tags: Vec<String>,
|
||||
#[serde(rename = "Address")]
|
||||
address: IpAddr,
|
||||
#[serde(rename = "Port")]
|
||||
port: u16,
|
||||
}
|
||||
|
||||
pub async fn publish_consul_service(
|
||||
consul_host: &str,
|
||||
consul_service_name: &str,
|
||||
node_id: NodeID,
|
||||
hostname: &str,
|
||||
rpc_public_addr: SocketAddr,
|
||||
) -> Result<(), Error> {
|
||||
let node = format!("garage:{}", hex::encode(&node_id[..8]));
|
||||
|
||||
let advertisment = ConsulPublishEntry {
|
||||
node: node.clone(),
|
||||
address: rpc_public_addr.ip(),
|
||||
node_meta: [
|
||||
("pubkey".to_string(), hex::encode(node_id)),
|
||||
("hostname".to_string(), hostname.to_string()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
service: ConsulPublishService {
|
||||
service_id: node.clone(),
|
||||
service_name: consul_service_name.to_string(),
|
||||
tags: vec!["advertised-by-garage".into(), hostname.into()],
|
||||
address: rpc_public_addr.ip(),
|
||||
port: rpc_public_addr.port(),
|
||||
},
|
||||
};
|
||||
|
||||
let url = format!("http://{}/v1/catalog/register", consul_host);
|
||||
let req_body = serde_json::to_string(&advertisment)?;
|
||||
debug!("Request body for consul adv: {}", req_body);
|
||||
|
||||
let req = Request::builder()
|
||||
.uri(url)
|
||||
.method(Method::PUT)
|
||||
.body(Body::from(req_body))?;
|
||||
|
||||
let client = Client::new();
|
||||
|
||||
let resp = client.request(req).await?;
|
||||
debug!("Response of advertising to Consul: {:?}", resp);
|
||||
let resp_code = resp.status();
|
||||
debug!(
|
||||
"{}",
|
||||
std::str::from_utf8(&hyper::body::to_bytes(resp.into_body()).await?)
|
||||
.unwrap_or("<invalid utf8>")
|
||||
);
|
||||
|
||||
if resp_code != StatusCode::OK {
|
||||
return Err(Error::Message(format!("HTTP error {}", resp_code)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+4
-4
@@ -4,10 +4,10 @@
|
||||
extern crate log;
|
||||
|
||||
mod consul;
|
||||
pub(crate) mod tls_util;
|
||||
|
||||
pub mod membership;
|
||||
pub mod ring;
|
||||
pub mod system;
|
||||
|
||||
pub mod rpc_client;
|
||||
pub mod rpc_server;
|
||||
pub mod rpc_helper;
|
||||
|
||||
pub use rpc_helper::*;
|
||||
|
||||
@@ -1,722 +0,0 @@
|
||||
//! Module containing structs related to membership management
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as FmtWrite;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::future::join_all;
|
||||
use futures::select;
|
||||
use futures_util::future::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::watch;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use garage_util::background::BackgroundRunner;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
use garage_util::persister::Persister;
|
||||
use garage_util::time::*;
|
||||
|
||||
use crate::consul::get_consul_nodes;
|
||||
use crate::ring::*;
|
||||
use crate::rpc_client::*;
|
||||
use crate::rpc_server::*;
|
||||
|
||||
const PING_INTERVAL: Duration = Duration::from_secs(10);
|
||||
const DISCOVERY_INTERVAL: Duration = Duration::from_secs(60);
|
||||
const PING_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
const MAX_FAILURES_BEFORE_CONSIDERED_DOWN: usize = 5;
|
||||
|
||||
/// RPC endpoint used for calls related to membership
|
||||
pub const MEMBERSHIP_RPC_PATH: &str = "_membership";
|
||||
|
||||
/// RPC messages related to membership
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub enum Message {
|
||||
/// Response to successfull advertisements
|
||||
Ok,
|
||||
/// Message sent to detect other nodes status
|
||||
Ping(PingMessage),
|
||||
/// Ask other node for the nodes it knows. Answered with AdvertiseNodesUp
|
||||
PullStatus,
|
||||
/// Ask other node its config. Answered with AdvertiseConfig
|
||||
PullConfig,
|
||||
/// Advertisement of nodes the host knows up. Sent spontanously or in response to PullStatus
|
||||
AdvertiseNodesUp(Vec<AdvertisedNode>),
|
||||
/// Advertisement of nodes config. Sent spontanously or in response to PullConfig
|
||||
AdvertiseConfig(NetworkConfig),
|
||||
}
|
||||
|
||||
impl RpcMessage for Message {}
|
||||
|
||||
/// A ping, containing informations about status and config
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct PingMessage {
|
||||
id: Uuid,
|
||||
rpc_port: u16,
|
||||
|
||||
status_hash: Hash,
|
||||
config_version: u64,
|
||||
|
||||
state_info: StateInfo,
|
||||
}
|
||||
|
||||
/// A node advertisement
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AdvertisedNode {
|
||||
/// Id of the node this advertisement relates to
|
||||
pub id: Uuid,
|
||||
/// IP and port of the node
|
||||
pub addr: SocketAddr,
|
||||
|
||||
/// Is the node considered up
|
||||
pub is_up: bool,
|
||||
/// When was the node last seen up, in milliseconds since UNIX epoch
|
||||
pub last_seen: u64,
|
||||
|
||||
pub state_info: StateInfo,
|
||||
}
|
||||
|
||||
/// This node's membership manager
|
||||
pub struct System {
|
||||
/// The id of this node
|
||||
pub id: Uuid,
|
||||
|
||||
persist_config: Persister<NetworkConfig>,
|
||||
persist_status: Persister<Vec<AdvertisedNode>>,
|
||||
rpc_local_port: u16,
|
||||
|
||||
state_info: StateInfo,
|
||||
|
||||
rpc_http_client: Arc<RpcHttpClient>,
|
||||
rpc_client: Arc<RpcClient<Message>>,
|
||||
|
||||
replication_factor: usize,
|
||||
pub(crate) status: watch::Receiver<Arc<Status>>,
|
||||
/// The ring
|
||||
pub ring: watch::Receiver<Arc<Ring>>,
|
||||
|
||||
update_lock: Mutex<Updaters>,
|
||||
|
||||
/// The job runner of this node
|
||||
pub background: Arc<BackgroundRunner>,
|
||||
}
|
||||
|
||||
struct Updaters {
|
||||
update_status: watch::Sender<Arc<Status>>,
|
||||
update_ring: watch::Sender<Arc<Ring>>,
|
||||
}
|
||||
|
||||
/// The status of each nodes, viewed by this node
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Status {
|
||||
/// Mapping of each node id to its known status
|
||||
pub nodes: HashMap<Uuid, Arc<StatusEntry>>,
|
||||
/// Hash of `nodes`, used to detect when nodes have different views of the cluster
|
||||
pub hash: Hash,
|
||||
}
|
||||
|
||||
/// The status of a single node
|
||||
#[derive(Debug)]
|
||||
pub struct StatusEntry {
|
||||
/// The IP and port used to connect to this node
|
||||
pub addr: SocketAddr,
|
||||
/// Last time this node was seen
|
||||
pub last_seen: u64,
|
||||
/// Number of consecutive pings sent without reply to this node
|
||||
pub num_failures: AtomicUsize,
|
||||
pub state_info: StateInfo,
|
||||
}
|
||||
|
||||
impl StatusEntry {
|
||||
/// is the node associated to this entry considered up
|
||||
pub fn is_up(&self) -> bool {
|
||||
self.num_failures.load(Ordering::SeqCst) < MAX_FAILURES_BEFORE_CONSIDERED_DOWN
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StateInfo {
|
||||
/// Hostname of the node
|
||||
pub hostname: String,
|
||||
/// Replication factor configured on the node
|
||||
pub replication_factor: Option<usize>, // TODO Option is just for retrocompatibility. It should become a simple usize at some point
|
||||
}
|
||||
|
||||
impl Status {
|
||||
fn handle_ping(&mut self, ip: IpAddr, info: &PingMessage) -> bool {
|
||||
let addr = SocketAddr::new(ip, info.rpc_port);
|
||||
let old_status = self.nodes.insert(
|
||||
info.id,
|
||||
Arc::new(StatusEntry {
|
||||
addr,
|
||||
last_seen: now_msec(),
|
||||
num_failures: AtomicUsize::from(0),
|
||||
state_info: info.state_info.clone(),
|
||||
}),
|
||||
);
|
||||
match old_status {
|
||||
None => {
|
||||
info!("Newly pingable node: {}", hex::encode(&info.id));
|
||||
true
|
||||
}
|
||||
Some(x) => x.addr != addr,
|
||||
}
|
||||
}
|
||||
|
||||
fn recalculate_hash(&mut self) {
|
||||
let mut nodes = self.nodes.iter().collect::<Vec<_>>();
|
||||
nodes.sort_unstable_by_key(|(id, _status)| *id);
|
||||
|
||||
let mut nodes_txt = String::new();
|
||||
debug!("Current set of pingable nodes: --");
|
||||
for (id, status) in nodes {
|
||||
debug!("{} {}", hex::encode(&id), status.addr);
|
||||
writeln!(&mut nodes_txt, "{} {}", hex::encode(&id), status.addr).unwrap();
|
||||
}
|
||||
debug!("END --");
|
||||
self.hash = blake2sum(nodes_txt.as_bytes());
|
||||
}
|
||||
|
||||
fn to_serializable_membership(&self, system: &System) -> Vec<AdvertisedNode> {
|
||||
let mut mem = vec![];
|
||||
for (node, status) in self.nodes.iter() {
|
||||
let state_info = if *node == system.id {
|
||||
system.state_info.clone()
|
||||
} else {
|
||||
status.state_info.clone()
|
||||
};
|
||||
mem.push(AdvertisedNode {
|
||||
id: *node,
|
||||
addr: status.addr,
|
||||
is_up: status.is_up(),
|
||||
last_seen: status.last_seen,
|
||||
state_info,
|
||||
});
|
||||
}
|
||||
mem
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_node_id(metadata_dir: &Path) -> Result<Uuid, Error> {
|
||||
let mut id_file = metadata_dir.to_path_buf();
|
||||
id_file.push("node_id");
|
||||
if id_file.as_path().exists() {
|
||||
let mut f = std::fs::File::open(id_file.as_path())?;
|
||||
let mut d = vec![];
|
||||
f.read_to_end(&mut d)?;
|
||||
if d.len() != 32 {
|
||||
return Err(Error::Message("Corrupt node_id file".to_string()));
|
||||
}
|
||||
|
||||
let mut id = [0u8; 32];
|
||||
id.copy_from_slice(&d[..]);
|
||||
Ok(id.into())
|
||||
} else {
|
||||
let id = gen_uuid();
|
||||
|
||||
let mut f = std::fs::File::create(id_file.as_path())?;
|
||||
f.write_all(id.as_slice())?;
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl System {
|
||||
/// Create this node's membership manager
|
||||
pub fn new(
|
||||
metadata_dir: PathBuf,
|
||||
rpc_http_client: Arc<RpcHttpClient>,
|
||||
background: Arc<BackgroundRunner>,
|
||||
rpc_server: &mut RpcServer,
|
||||
replication_factor: usize,
|
||||
) -> Arc<Self> {
|
||||
let id = gen_node_id(&metadata_dir).expect("Unable to read or generate node ID");
|
||||
info!("Node ID: {}", hex::encode(&id));
|
||||
|
||||
let persist_config = Persister::new(&metadata_dir, "network_config");
|
||||
let persist_status = Persister::new(&metadata_dir, "peer_info");
|
||||
|
||||
let net_config = match persist_config.load() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
match Persister::<garage_rpc_021::ring::NetworkConfig>::new(
|
||||
&metadata_dir,
|
||||
"network_config",
|
||||
)
|
||||
.load()
|
||||
{
|
||||
Ok(old_config) => NetworkConfig::migrate_from_021(old_config),
|
||||
Err(e2) => {
|
||||
info!(
|
||||
"No valid previous network configuration stored ({}, {}), starting fresh.",
|
||||
e, e2
|
||||
);
|
||||
NetworkConfig::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut status = Status {
|
||||
nodes: HashMap::new(),
|
||||
hash: Hash::default(),
|
||||
};
|
||||
status.recalculate_hash();
|
||||
let (update_status, status) = watch::channel(Arc::new(status));
|
||||
|
||||
let state_info = StateInfo {
|
||||
hostname: gethostname::gethostname()
|
||||
.into_string()
|
||||
.unwrap_or_else(|_| "<invalid utf-8>".to_string()),
|
||||
replication_factor: Some(replication_factor),
|
||||
};
|
||||
|
||||
let ring = Ring::new(net_config, replication_factor);
|
||||
let (update_ring, ring) = watch::channel(Arc::new(ring));
|
||||
|
||||
let rpc_path = MEMBERSHIP_RPC_PATH.to_string();
|
||||
let rpc_client = RpcClient::new(
|
||||
RpcAddrClient::<Message>::new(rpc_http_client.clone(), rpc_path.clone()),
|
||||
background.clone(),
|
||||
status.clone(),
|
||||
);
|
||||
|
||||
let sys = Arc::new(System {
|
||||
id,
|
||||
persist_config,
|
||||
persist_status,
|
||||
rpc_local_port: rpc_server.bind_addr.port(),
|
||||
state_info,
|
||||
rpc_http_client,
|
||||
rpc_client,
|
||||
replication_factor,
|
||||
status,
|
||||
ring,
|
||||
update_lock: Mutex::new(Updaters {
|
||||
update_status,
|
||||
update_ring,
|
||||
}),
|
||||
background,
|
||||
});
|
||||
sys.clone().register_handler(rpc_server, rpc_path);
|
||||
sys
|
||||
}
|
||||
|
||||
fn register_handler(self: Arc<Self>, rpc_server: &mut RpcServer, path: String) {
|
||||
rpc_server.add_handler::<Message, _, _>(path, move |msg, addr| {
|
||||
let self2 = self.clone();
|
||||
async move {
|
||||
match msg {
|
||||
Message::Ping(ping) => self2.handle_ping(&addr, &ping).await,
|
||||
|
||||
Message::PullStatus => Ok(self2.handle_pull_status()),
|
||||
Message::PullConfig => Ok(self2.handle_pull_config()),
|
||||
Message::AdvertiseNodesUp(adv) => self2.handle_advertise_nodes_up(&adv).await,
|
||||
Message::AdvertiseConfig(adv) => self2.handle_advertise_config(&adv).await,
|
||||
|
||||
_ => Err(Error::BadRpc("Unexpected RPC message".to_string())),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Get an RPC client
|
||||
pub fn rpc_client<M: RpcMessage + 'static>(self: &Arc<Self>, path: &str) -> Arc<RpcClient<M>> {
|
||||
RpcClient::new(
|
||||
RpcAddrClient::new(self.rpc_http_client.clone(), path.to_string()),
|
||||
self.background.clone(),
|
||||
self.status.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Save network configuration to disc
|
||||
async fn save_network_config(self: Arc<Self>) -> Result<(), Error> {
|
||||
let ring = self.ring.borrow().clone();
|
||||
self.persist_config
|
||||
.save_async(&ring.config)
|
||||
.await
|
||||
.expect("Cannot save current cluster configuration");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_ping(&self) -> Message {
|
||||
let status = self.status.borrow().clone();
|
||||
let ring = self.ring.borrow().clone();
|
||||
Message::Ping(PingMessage {
|
||||
id: self.id,
|
||||
rpc_port: self.rpc_local_port,
|
||||
status_hash: status.hash,
|
||||
config_version: ring.config.version,
|
||||
state_info: self.state_info.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn broadcast(self: Arc<Self>, msg: Message, timeout: Duration) {
|
||||
let status = self.status.borrow().clone();
|
||||
let to = status
|
||||
.nodes
|
||||
.keys()
|
||||
.filter(|x| **x != self.id)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
self.rpc_client.call_many(&to[..], msg, timeout).await;
|
||||
}
|
||||
|
||||
/// Perform bootstraping, starting the ping loop
|
||||
pub async fn bootstrap(
|
||||
self: Arc<Self>,
|
||||
peers: Vec<SocketAddr>,
|
||||
consul_host: Option<String>,
|
||||
consul_service_name: Option<String>,
|
||||
) {
|
||||
let self2 = self.clone();
|
||||
self.background
|
||||
.spawn_worker("discovery loop".to_string(), |stop_signal| {
|
||||
self2.discovery_loop(peers, consul_host, consul_service_name, stop_signal)
|
||||
});
|
||||
|
||||
let self2 = self.clone();
|
||||
self.background
|
||||
.spawn_worker("ping loop".to_string(), |stop_signal| {
|
||||
self2.ping_loop(stop_signal)
|
||||
});
|
||||
}
|
||||
|
||||
async fn ping_nodes(self: Arc<Self>, peers: Vec<(SocketAddr, Option<Uuid>)>) {
|
||||
let ping_msg = self.make_ping();
|
||||
let ping_resps = join_all(peers.iter().map(|(addr, id_option)| {
|
||||
let sys = self.clone();
|
||||
let ping_msg_ref = &ping_msg;
|
||||
async move {
|
||||
(
|
||||
id_option,
|
||||
addr,
|
||||
sys.rpc_client
|
||||
.by_addr()
|
||||
.call(&addr, ping_msg_ref, PING_TIMEOUT)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
}))
|
||||
.await;
|
||||
|
||||
let update_locked = self.update_lock.lock().await;
|
||||
let mut status: Status = self.status.borrow().as_ref().clone();
|
||||
let ring = self.ring.borrow().clone();
|
||||
|
||||
let mut has_changes = false;
|
||||
let mut to_advertise = vec![];
|
||||
|
||||
for (id_option, addr, ping_resp) in ping_resps {
|
||||
if let Ok(Ok(Message::Ping(info))) = ping_resp {
|
||||
let is_new = status.handle_ping(addr.ip(), &info);
|
||||
if is_new {
|
||||
has_changes = true;
|
||||
to_advertise.push(AdvertisedNode {
|
||||
id: info.id,
|
||||
addr: *addr,
|
||||
is_up: true,
|
||||
last_seen: now_msec(),
|
||||
state_info: info.state_info.clone(),
|
||||
});
|
||||
}
|
||||
if is_new || status.hash != info.status_hash {
|
||||
self.background
|
||||
.spawn_cancellable(self.clone().pull_status(info.id).map(Ok));
|
||||
}
|
||||
if is_new || ring.config.version < info.config_version {
|
||||
self.background
|
||||
.spawn_cancellable(self.clone().pull_config(info.id).map(Ok));
|
||||
}
|
||||
} else if let Some(id) = id_option {
|
||||
if let Some(st) = status.nodes.get_mut(id) {
|
||||
// we need to increment failure counter as call was done using by_addr so the
|
||||
// counter was not auto-incremented
|
||||
st.num_failures.fetch_add(1, Ordering::SeqCst);
|
||||
if !st.is_up() {
|
||||
warn!("Node {:?} seems to be down.", id);
|
||||
if !ring.config.members.contains_key(id) {
|
||||
info!("Removing node {:?} from status (not in config and not responding to pings anymore)", id);
|
||||
status.nodes.remove(&id);
|
||||
has_changes = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if has_changes {
|
||||
status.recalculate_hash();
|
||||
}
|
||||
self.update_status(&update_locked, status).await;
|
||||
drop(update_locked);
|
||||
|
||||
if !to_advertise.is_empty() {
|
||||
self.broadcast(Message::AdvertiseNodesUp(to_advertise), PING_TIMEOUT)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_ping(
|
||||
self: Arc<Self>,
|
||||
from: &SocketAddr,
|
||||
ping: &PingMessage,
|
||||
) -> Result<Message, Error> {
|
||||
let update_locked = self.update_lock.lock().await;
|
||||
let mut status: Status = self.status.borrow().as_ref().clone();
|
||||
|
||||
let is_new = status.handle_ping(from.ip(), ping);
|
||||
if is_new {
|
||||
status.recalculate_hash();
|
||||
}
|
||||
let status_hash = status.hash;
|
||||
let config_version = self.ring.borrow().config.version;
|
||||
|
||||
self.update_status(&update_locked, status).await;
|
||||
drop(update_locked);
|
||||
|
||||
if is_new || status_hash != ping.status_hash {
|
||||
self.background
|
||||
.spawn_cancellable(self.clone().pull_status(ping.id).map(Ok));
|
||||
}
|
||||
if is_new || config_version < ping.config_version {
|
||||
self.background
|
||||
.spawn_cancellable(self.clone().pull_config(ping.id).map(Ok));
|
||||
}
|
||||
|
||||
Ok(self.make_ping())
|
||||
}
|
||||
|
||||
fn handle_pull_status(&self) -> Message {
|
||||
Message::AdvertiseNodesUp(self.status.borrow().to_serializable_membership(self))
|
||||
}
|
||||
|
||||
fn handle_pull_config(&self) -> Message {
|
||||
let ring = self.ring.borrow().clone();
|
||||
Message::AdvertiseConfig(ring.config.clone())
|
||||
}
|
||||
|
||||
async fn handle_advertise_nodes_up(
|
||||
self: Arc<Self>,
|
||||
adv: &[AdvertisedNode],
|
||||
) -> Result<Message, Error> {
|
||||
let mut to_ping = vec![];
|
||||
|
||||
let update_lock = self.update_lock.lock().await;
|
||||
let mut status: Status = self.status.borrow().as_ref().clone();
|
||||
let mut has_changed = false;
|
||||
let mut max_replication_factor = 0;
|
||||
|
||||
for node in adv.iter() {
|
||||
if node.id == self.id {
|
||||
// learn our own ip address
|
||||
let self_addr = SocketAddr::new(node.addr.ip(), self.rpc_local_port);
|
||||
let old_self = status.nodes.insert(
|
||||
node.id,
|
||||
Arc::new(StatusEntry {
|
||||
addr: self_addr,
|
||||
last_seen: now_msec(),
|
||||
num_failures: AtomicUsize::from(0),
|
||||
state_info: self.state_info.clone(),
|
||||
}),
|
||||
);
|
||||
has_changed = match old_self {
|
||||
None => true,
|
||||
Some(x) => x.addr != self_addr,
|
||||
};
|
||||
} else {
|
||||
let ping_them = match status.nodes.get(&node.id) {
|
||||
// Case 1: new node
|
||||
None => true,
|
||||
// Case 2: the node might have changed address
|
||||
Some(our_node) => node.is_up && !our_node.is_up() && our_node.addr != node.addr,
|
||||
};
|
||||
max_replication_factor = std::cmp::max(
|
||||
max_replication_factor,
|
||||
node.state_info.replication_factor.unwrap_or_default(),
|
||||
);
|
||||
if ping_them {
|
||||
to_ping.push((node.addr, Some(node.id)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.replication_factor < max_replication_factor {
|
||||
error!("Some node have a higher replication factor ({}) than this one ({}). This is not supported and might lead to bugs",
|
||||
max_replication_factor,
|
||||
self.replication_factor);
|
||||
std::process::exit(1);
|
||||
}
|
||||
if has_changed {
|
||||
status.recalculate_hash();
|
||||
}
|
||||
self.update_status(&update_lock, status).await;
|
||||
drop(update_lock);
|
||||
|
||||
if !to_ping.is_empty() {
|
||||
self.background
|
||||
.spawn_cancellable(self.clone().ping_nodes(to_ping).map(Ok));
|
||||
}
|
||||
|
||||
Ok(Message::Ok)
|
||||
}
|
||||
|
||||
async fn handle_advertise_config(
|
||||
self: Arc<Self>,
|
||||
adv: &NetworkConfig,
|
||||
) -> Result<Message, Error> {
|
||||
let update_lock = self.update_lock.lock().await;
|
||||
let ring: Arc<Ring> = self.ring.borrow().clone();
|
||||
|
||||
if adv.version > ring.config.version {
|
||||
let ring = Ring::new(adv.clone(), self.replication_factor);
|
||||
update_lock.update_ring.send(Arc::new(ring))?;
|
||||
drop(update_lock);
|
||||
|
||||
self.background.spawn_cancellable(
|
||||
self.clone()
|
||||
.broadcast(Message::AdvertiseConfig(adv.clone()), PING_TIMEOUT)
|
||||
.map(Ok),
|
||||
);
|
||||
self.background.spawn(self.clone().save_network_config());
|
||||
}
|
||||
|
||||
Ok(Message::Ok)
|
||||
}
|
||||
|
||||
async fn ping_loop(self: Arc<Self>, mut stop_signal: watch::Receiver<bool>) {
|
||||
while !*stop_signal.borrow() {
|
||||
let restart_at = tokio::time::sleep(PING_INTERVAL);
|
||||
|
||||
let status = self.status.borrow().clone();
|
||||
let ping_addrs = status
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(id, _)| **id != self.id)
|
||||
.map(|(id, status)| (status.addr, Some(*id)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
self.clone().ping_nodes(ping_addrs).await;
|
||||
|
||||
select! {
|
||||
_ = restart_at.fuse() => {},
|
||||
_ = stop_signal.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discovery_loop(
|
||||
self: Arc<Self>,
|
||||
bootstrap_peers: Vec<SocketAddr>,
|
||||
consul_host: Option<String>,
|
||||
consul_service_name: Option<String>,
|
||||
mut stop_signal: watch::Receiver<bool>,
|
||||
) {
|
||||
let consul_config = match (consul_host, consul_service_name) {
|
||||
(Some(ch), Some(csn)) => Some((ch, csn)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
while !*stop_signal.borrow() {
|
||||
let not_configured = self.ring.borrow().config.members.is_empty();
|
||||
let no_peers = self.status.borrow().nodes.len() < 3;
|
||||
let bad_peers = self
|
||||
.status
|
||||
.borrow()
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, v)| v.is_up())
|
||||
.count() != self.ring.borrow().config.members.len();
|
||||
|
||||
if not_configured || no_peers || bad_peers {
|
||||
info!("Doing a bootstrap/discovery step (not_configured: {}, no_peers: {}, bad_peers: {})", not_configured, no_peers, bad_peers);
|
||||
|
||||
let mut ping_list = bootstrap_peers
|
||||
.iter()
|
||||
.map(|ip| (*ip, None))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if let Ok(peers) = self.persist_status.load_async().await {
|
||||
ping_list.extend(peers.iter().map(|x| (x.addr, Some(x.id))));
|
||||
}
|
||||
|
||||
if let Some((consul_host, consul_service_name)) = &consul_config {
|
||||
match get_consul_nodes(consul_host, consul_service_name).await {
|
||||
Ok(node_list) => {
|
||||
ping_list.extend(node_list.iter().map(|a| (*a, None)));
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Could not retrieve node list from Consul: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.clone().ping_nodes(ping_list).await;
|
||||
}
|
||||
|
||||
let restart_at = tokio::time::sleep(DISCOVERY_INTERVAL);
|
||||
select! {
|
||||
_ = restart_at.fuse() => {},
|
||||
_ = stop_signal.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// for some reason fixing this is causing compilation error, see https://github.com/rust-lang/rust-clippy/issues/7052
|
||||
#[allow(clippy::manual_async_fn)]
|
||||
fn pull_status(
|
||||
self: Arc<Self>,
|
||||
peer: Uuid,
|
||||
) -> impl futures::future::Future<Output = ()> + Send + 'static {
|
||||
async move {
|
||||
let resp = self
|
||||
.rpc_client
|
||||
.call(peer, Message::PullStatus, PING_TIMEOUT)
|
||||
.await;
|
||||
if let Ok(Message::AdvertiseNodesUp(nodes)) = resp {
|
||||
let _: Result<_, _> = self.handle_advertise_nodes_up(&nodes).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pull_config(self: Arc<Self>, peer: Uuid) {
|
||||
let resp = self
|
||||
.rpc_client
|
||||
.call(peer, Message::PullConfig, PING_TIMEOUT)
|
||||
.await;
|
||||
if let Ok(Message::AdvertiseConfig(config)) = resp {
|
||||
let _: Result<_, _> = self.handle_advertise_config(&config).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn update_status(self: &Arc<Self>, updaters: &Updaters, status: Status) {
|
||||
if status.hash != self.status.borrow().hash {
|
||||
let mut list = status.to_serializable_membership(&self);
|
||||
|
||||
// Combine with old peer list to make sure no peer is lost
|
||||
if let Ok(old_list) = self.persist_status.load_async().await {
|
||||
for pp in old_list {
|
||||
if !list.iter().any(|np| pp.id == np.id) {
|
||||
list.push(pp);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !list.is_empty() {
|
||||
info!("Persisting new peer list ({} peers)", list.len());
|
||||
self.persist_status
|
||||
.save_async(&list)
|
||||
.await
|
||||
.expect("Unable to persist peer list");
|
||||
}
|
||||
}
|
||||
|
||||
updaters
|
||||
.update_status
|
||||
.send(Arc::new(status))
|
||||
.expect("Could not update internal membership status");
|
||||
}
|
||||
}
|
||||
@@ -38,31 +38,6 @@ impl NetworkConfig {
|
||||
version: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_from_021(old: garage_rpc_021::ring::NetworkConfig) -> Self {
|
||||
let members = old
|
||||
.members
|
||||
.into_iter()
|
||||
.map(|(id, conf)| {
|
||||
(
|
||||
Hash::try_from(id.as_slice()).unwrap(),
|
||||
NetworkConfigEntry {
|
||||
zone: conf.datacenter,
|
||||
capacity: if conf.capacity == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(conf.capacity)
|
||||
},
|
||||
tag: conf.tag,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
members,
|
||||
version: old.version,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The overall configuration of one (possibly remote) node
|
||||
|
||||
@@ -1,369 +0,0 @@
|
||||
//! Contain structs related to making RPCs
|
||||
use std::borrow::Borrow;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use futures::future::Future;
|
||||
use futures::stream::futures_unordered::FuturesUnordered;
|
||||
use futures::stream::StreamExt;
|
||||
use futures_util::future::FutureExt;
|
||||
use hyper::client::{Client, HttpConnector};
|
||||
use hyper::{Body, Method, Request};
|
||||
use tokio::sync::{watch, Semaphore};
|
||||
|
||||
use garage_util::background::BackgroundRunner;
|
||||
use garage_util::config::TlsConfig;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::{Error, RpcError};
|
||||
|
||||
use crate::membership::Status;
|
||||
use crate::rpc_server::RpcMessage;
|
||||
use crate::tls_util;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Strategy to apply when making RPC
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct RequestStrategy {
|
||||
/// Max time to wait for reponse
|
||||
pub rs_timeout: Duration,
|
||||
/// Min number of response to consider the request successful
|
||||
pub rs_quorum: usize,
|
||||
/// Should requests be dropped after enough response are received
|
||||
pub rs_interrupt_after_quorum: bool,
|
||||
}
|
||||
|
||||
impl RequestStrategy {
|
||||
/// Create a RequestStrategy with default timeout and not interrupting when quorum reached
|
||||
pub fn with_quorum(quorum: usize) -> Self {
|
||||
RequestStrategy {
|
||||
rs_timeout: DEFAULT_TIMEOUT,
|
||||
rs_quorum: quorum,
|
||||
rs_interrupt_after_quorum: false,
|
||||
}
|
||||
}
|
||||
/// Set timeout of the strategy
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.rs_timeout = timeout;
|
||||
self
|
||||
}
|
||||
/// Set if requests can be dropped after quorum has been reached
|
||||
/// In general true for read requests, and false for write
|
||||
pub fn interrupt_after_quorum(mut self, interrupt: bool) -> Self {
|
||||
self.rs_interrupt_after_quorum = interrupt;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Shortcut for a boxed async function taking a message, and resolving to another message or an
|
||||
/// error
|
||||
pub type LocalHandlerFn<M> =
|
||||
Box<dyn Fn(Arc<M>) -> Pin<Box<dyn Future<Output = Result<M, Error>> + Send>> + Send + Sync>;
|
||||
|
||||
/// Client used to send RPC
|
||||
pub struct RpcClient<M: RpcMessage> {
|
||||
status: watch::Receiver<Arc<Status>>,
|
||||
background: Arc<BackgroundRunner>,
|
||||
|
||||
local_handler: ArcSwapOption<(Uuid, LocalHandlerFn<M>)>,
|
||||
|
||||
rpc_addr_client: RpcAddrClient<M>,
|
||||
}
|
||||
|
||||
impl<M: RpcMessage + 'static> RpcClient<M> {
|
||||
/// Create a new RpcClient from an address, a job runner, and the status of all RPC servers
|
||||
pub fn new(
|
||||
rac: RpcAddrClient<M>,
|
||||
background: Arc<BackgroundRunner>,
|
||||
status: watch::Receiver<Arc<Status>>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
rpc_addr_client: rac,
|
||||
background,
|
||||
status,
|
||||
local_handler: ArcSwapOption::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
/// Set the local handler, to process RPC to this node without network usage
|
||||
pub fn set_local_handler<F, Fut>(&self, my_id: Uuid, handler: F)
|
||||
where
|
||||
F: Fn(Arc<M>) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<M, Error>> + Send + 'static,
|
||||
{
|
||||
let handler_arc = Arc::new(handler);
|
||||
let handler: LocalHandlerFn<M> = Box::new(move |msg| {
|
||||
let handler_arc2 = handler_arc.clone();
|
||||
Box::pin(async move { handler_arc2(msg).await })
|
||||
});
|
||||
self.local_handler.swap(Some(Arc::new((my_id, handler))));
|
||||
}
|
||||
|
||||
/// Get a RPC client to make calls using node's SocketAddr instead of its ID
|
||||
pub fn by_addr(&self) -> &RpcAddrClient<M> {
|
||||
&self.rpc_addr_client
|
||||
}
|
||||
|
||||
/// Make a RPC call
|
||||
pub async fn call(&self, to: Uuid, msg: M, timeout: Duration) -> Result<M, Error> {
|
||||
self.call_arc(to, Arc::new(msg), timeout).await
|
||||
}
|
||||
|
||||
/// Make a RPC call from a message stored in an Arc
|
||||
pub async fn call_arc(&self, to: Uuid, msg: Arc<M>, timeout: Duration) -> Result<M, Error> {
|
||||
if let Some(lh) = self.local_handler.load_full() {
|
||||
let (my_id, local_handler) = lh.as_ref();
|
||||
if to.borrow() == my_id {
|
||||
return local_handler(msg).await;
|
||||
}
|
||||
}
|
||||
let status = self.status.borrow().clone();
|
||||
let node_status = match status.nodes.get(&to) {
|
||||
Some(node_status) => {
|
||||
if node_status.is_up() {
|
||||
node_status
|
||||
} else {
|
||||
return Err(Error::from(RpcError::NodeDown(to)));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
return Err(Error::Message(format!(
|
||||
"Peer ID not found: {:?}",
|
||||
to.borrow()
|
||||
)))
|
||||
}
|
||||
};
|
||||
match self
|
||||
.rpc_addr_client
|
||||
.call(&node_status.addr, msg, timeout)
|
||||
.await
|
||||
{
|
||||
Err(rpc_error) => {
|
||||
node_status.num_failures.fetch_add(1, Ordering::SeqCst);
|
||||
Err(Error::from(rpc_error))
|
||||
}
|
||||
Ok(x) => x,
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a RPC call to multiple servers, returning a Vec containing each result
|
||||
pub async fn call_many(&self, to: &[Uuid], msg: M, timeout: Duration) -> Vec<Result<M, Error>> {
|
||||
let msg = Arc::new(msg);
|
||||
let mut resp_stream = to
|
||||
.iter()
|
||||
.map(|to| self.call_arc(*to, msg.clone(), timeout))
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
|
||||
let mut results = vec![];
|
||||
while let Some(resp) = resp_stream.next().await {
|
||||
results.push(resp);
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
/// Make a RPC call to multiple servers, returning either a Vec of responses, or an error if
|
||||
/// strategy could not be respected due to too many errors
|
||||
pub async fn try_call_many(
|
||||
self: &Arc<Self>,
|
||||
to: &[Uuid],
|
||||
msg: M,
|
||||
strategy: RequestStrategy,
|
||||
) -> Result<Vec<M>, Error> {
|
||||
let timeout = strategy.rs_timeout;
|
||||
|
||||
let msg = Arc::new(msg);
|
||||
let mut resp_stream = to
|
||||
.to_vec()
|
||||
.into_iter()
|
||||
.map(|to| {
|
||||
let self2 = self.clone();
|
||||
let msg = msg.clone();
|
||||
async move { self2.call_arc(to, msg, timeout).await }
|
||||
})
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
|
||||
let mut results = vec![];
|
||||
let mut errors = vec![];
|
||||
|
||||
while let Some(resp) = resp_stream.next().await {
|
||||
match resp {
|
||||
Ok(msg) => {
|
||||
results.push(msg);
|
||||
if results.len() >= strategy.rs_quorum {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if results.len() >= strategy.rs_quorum {
|
||||
// Continue requests in background.
|
||||
// Continue the remaining requests immediately using tokio::spawn
|
||||
// but enqueue a task in the background runner
|
||||
// to ensure that the process won't exit until the requests are done
|
||||
// (if we had just enqueued the resp_stream.collect directly in the background runner,
|
||||
// the requests might have been put on hold in the background runner's queue,
|
||||
// in which case they might timeout or otherwise fail)
|
||||
if !strategy.rs_interrupt_after_quorum {
|
||||
let wait_finished_fut = tokio::spawn(async move {
|
||||
resp_stream.collect::<Vec<_>>().await;
|
||||
});
|
||||
self.background.spawn(wait_finished_fut.map(|_| Ok(())));
|
||||
}
|
||||
|
||||
Ok(results)
|
||||
} else {
|
||||
let errors = errors.iter().map(|e| format!("{}", e)).collect::<Vec<_>>();
|
||||
Err(Error::from(RpcError::TooManyErrors(errors)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thin wrapper arround an `RpcHttpClient` specifying the path of the request
|
||||
pub struct RpcAddrClient<M: RpcMessage> {
|
||||
phantom: PhantomData<M>,
|
||||
|
||||
http_client: Arc<RpcHttpClient>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl<M: RpcMessage> RpcAddrClient<M> {
|
||||
/// Create an RpcAddrClient from an HTTP client and the endpoint to reach for RPCs
|
||||
pub fn new(http_client: Arc<RpcHttpClient>, path: String) -> Self {
|
||||
Self {
|
||||
phantom: PhantomData::default(),
|
||||
http_client,
|
||||
path,
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a RPC
|
||||
pub async fn call<MB>(
|
||||
&self,
|
||||
to_addr: &SocketAddr,
|
||||
msg: MB,
|
||||
timeout: Duration,
|
||||
) -> Result<Result<M, Error>, RpcError>
|
||||
where
|
||||
MB: Borrow<M>,
|
||||
{
|
||||
self.http_client
|
||||
.call(&self.path, to_addr, msg, timeout)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP client used to make RPCs
|
||||
pub struct RpcHttpClient {
|
||||
request_limiter: Semaphore,
|
||||
method: ClientMethod,
|
||||
}
|
||||
|
||||
enum ClientMethod {
|
||||
Http(Client<HttpConnector, hyper::Body>),
|
||||
Https(Client<tls_util::HttpsConnectorFixedDnsname<HttpConnector>, hyper::Body>),
|
||||
}
|
||||
|
||||
impl RpcHttpClient {
|
||||
/// Create a new RpcHttpClient
|
||||
pub fn new(
|
||||
max_concurrent_requests: usize,
|
||||
tls_config: &Option<TlsConfig>,
|
||||
) -> Result<Self, Error> {
|
||||
let method = if let Some(cf) = tls_config {
|
||||
let ca_certs = tls_util::load_certs(&cf.ca_cert).map_err(|e| {
|
||||
Error::Message(format!("Failed to open CA certificate file: {:?}", e))
|
||||
})?;
|
||||
let node_certs = tls_util::load_certs(&cf.node_cert)
|
||||
.map_err(|e| Error::Message(format!("Failed to open certificate file: {:?}", e)))?;
|
||||
let node_key = tls_util::load_private_key(&cf.node_key)
|
||||
.map_err(|e| Error::Message(format!("Failed to open private key file: {:?}", e)))?;
|
||||
|
||||
let mut config = rustls::ClientConfig::new();
|
||||
|
||||
for crt in ca_certs.iter() {
|
||||
config.root_store.add(crt)?;
|
||||
}
|
||||
|
||||
config.set_single_client_cert([&node_certs[..], &ca_certs[..]].concat(), node_key)?;
|
||||
|
||||
let connector =
|
||||
tls_util::HttpsConnectorFixedDnsname::<HttpConnector>::new(config, "garage");
|
||||
|
||||
ClientMethod::Https(Client::builder().build(connector))
|
||||
} else {
|
||||
ClientMethod::Http(Client::new())
|
||||
};
|
||||
Ok(RpcHttpClient {
|
||||
method,
|
||||
request_limiter: Semaphore::new(max_concurrent_requests),
|
||||
})
|
||||
}
|
||||
|
||||
/// Make a RPC
|
||||
async fn call<M, MB>(
|
||||
&self,
|
||||
path: &str,
|
||||
to_addr: &SocketAddr,
|
||||
msg: MB,
|
||||
timeout: Duration,
|
||||
) -> Result<Result<M, Error>, RpcError>
|
||||
where
|
||||
MB: Borrow<M>,
|
||||
M: RpcMessage,
|
||||
{
|
||||
let uri = match self.method {
|
||||
ClientMethod::Http(_) => format!("http://{}/{}", to_addr, path),
|
||||
ClientMethod::Https(_) => format!("https://{}/{}", to_addr, path),
|
||||
};
|
||||
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(uri)
|
||||
.body(Body::from(rmp_to_vec_all_named(msg.borrow())?))?;
|
||||
|
||||
let resp_fut = match &self.method {
|
||||
ClientMethod::Http(client) => client.request(req).fuse(),
|
||||
ClientMethod::Https(client) => client.request(req).fuse(),
|
||||
};
|
||||
|
||||
trace!("({}) Acquiring request_limiter slot...", path);
|
||||
let slot = self.request_limiter.acquire().await;
|
||||
trace!("({}) Got slot, doing request to {}...", path, to_addr);
|
||||
let resp = tokio::time::timeout(timeout, resp_fut)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
debug!(
|
||||
"RPC timeout to {}: {}",
|
||||
to_addr,
|
||||
debug_serialize(msg.borrow())
|
||||
);
|
||||
e
|
||||
})?
|
||||
.map_err(|e| {
|
||||
warn!(
|
||||
"RPC HTTP client error when connecting to {}: {}",
|
||||
to_addr, e
|
||||
);
|
||||
e
|
||||
})?;
|
||||
|
||||
let status = resp.status();
|
||||
trace!("({}) Request returned, got status {}", path, status);
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await?;
|
||||
drop(slot);
|
||||
|
||||
match rmp_serde::decode::from_read::<_, Result<M, String>>(&body[..])? {
|
||||
Err(e) => Ok(Err(Error::RemoteError(e, status))),
|
||||
Ok(x) => Ok(Ok(x)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
//! Contain structs related to making RPCs
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::future::join_all;
|
||||
use futures::stream::futures_unordered::FuturesUnordered;
|
||||
use futures::stream::StreamExt;
|
||||
use futures_util::future::FutureExt;
|
||||
use tokio::select;
|
||||
use tokio::sync::{watch, Semaphore};
|
||||
|
||||
pub use netapp::endpoint::{Endpoint, EndpointHandler, Message as Rpc};
|
||||
use netapp::peering::fullmesh::FullMeshPeeringStrategy;
|
||||
pub use netapp::proto::*;
|
||||
pub use netapp::{NetApp, NodeID};
|
||||
|
||||
use garage_util::background::BackgroundRunner;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
|
||||
use crate::ring::Ring;
|
||||
|
||||
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
// Try to never have more than 200MB of outgoing requests
|
||||
// buffered at the same time. Other requests are queued until
|
||||
// space is freed.
|
||||
const REQUEST_BUFFER_SIZE: usize = 200 * 1024 * 1024;
|
||||
|
||||
/// Strategy to apply when making RPC
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct RequestStrategy {
|
||||
/// Max time to wait for reponse
|
||||
pub rs_timeout: Duration,
|
||||
/// Min number of response to consider the request successful
|
||||
pub rs_quorum: Option<usize>,
|
||||
/// Should requests be dropped after enough response are received
|
||||
pub rs_interrupt_after_quorum: bool,
|
||||
/// Request priority
|
||||
pub rs_priority: RequestPriority,
|
||||
}
|
||||
|
||||
impl RequestStrategy {
|
||||
/// Create a RequestStrategy with default timeout and not interrupting when quorum reached
|
||||
pub fn with_priority(prio: RequestPriority) -> Self {
|
||||
RequestStrategy {
|
||||
rs_timeout: DEFAULT_TIMEOUT,
|
||||
rs_quorum: None,
|
||||
rs_interrupt_after_quorum: false,
|
||||
rs_priority: prio,
|
||||
}
|
||||
}
|
||||
/// Set quorum to be reached for request
|
||||
pub fn with_quorum(mut self, quorum: usize) -> Self {
|
||||
self.rs_quorum = Some(quorum);
|
||||
self
|
||||
}
|
||||
/// Set timeout of the strategy
|
||||
pub fn with_timeout(mut self, timeout: Duration) -> Self {
|
||||
self.rs_timeout = timeout;
|
||||
self
|
||||
}
|
||||
/// Set if requests can be dropped after quorum has been reached
|
||||
/// In general true for read requests, and false for write
|
||||
pub fn interrupt_after_quorum(mut self, interrupt: bool) -> Self {
|
||||
self.rs_interrupt_after_quorum = interrupt;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RpcHelper(Arc<RpcHelperInner>);
|
||||
|
||||
struct RpcHelperInner {
|
||||
our_node_id: Uuid,
|
||||
fullmesh: Arc<FullMeshPeeringStrategy>,
|
||||
background: Arc<BackgroundRunner>,
|
||||
ring: watch::Receiver<Arc<Ring>>,
|
||||
request_buffer_semaphore: Semaphore,
|
||||
}
|
||||
|
||||
impl RpcHelper {
|
||||
pub(crate) fn new(
|
||||
our_node_id: Uuid,
|
||||
fullmesh: Arc<FullMeshPeeringStrategy>,
|
||||
background: Arc<BackgroundRunner>,
|
||||
ring: watch::Receiver<Arc<Ring>>,
|
||||
) -> Self {
|
||||
Self(Arc::new(RpcHelperInner {
|
||||
our_node_id,
|
||||
fullmesh,
|
||||
background,
|
||||
ring,
|
||||
request_buffer_semaphore: Semaphore::new(REQUEST_BUFFER_SIZE),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn call<M, H, S>(
|
||||
&self,
|
||||
endpoint: &Endpoint<M, H>,
|
||||
to: Uuid,
|
||||
msg: M,
|
||||
strat: RequestStrategy,
|
||||
) -> Result<S, Error>
|
||||
where
|
||||
M: Rpc<Response = Result<S, Error>>,
|
||||
H: EndpointHandler<M>,
|
||||
{
|
||||
self.call_arc(endpoint, to, Arc::new(msg), strat).await
|
||||
}
|
||||
|
||||
pub async fn call_arc<M, H, S>(
|
||||
&self,
|
||||
endpoint: &Endpoint<M, H>,
|
||||
to: Uuid,
|
||||
msg: Arc<M>,
|
||||
strat: RequestStrategy,
|
||||
) -> Result<S, Error>
|
||||
where
|
||||
M: Rpc<Response = Result<S, Error>>,
|
||||
H: EndpointHandler<M>,
|
||||
{
|
||||
let msg_size = rmp_to_vec_all_named(&msg)?.len() as u32;
|
||||
let permit = self
|
||||
.0
|
||||
.request_buffer_semaphore
|
||||
.acquire_many(msg_size)
|
||||
.await?;
|
||||
|
||||
let node_id = to.into();
|
||||
select! {
|
||||
res = endpoint.call(&node_id, &msg, strat.rs_priority) => {
|
||||
drop(permit);
|
||||
Ok(res??)
|
||||
}
|
||||
_ = tokio::time::sleep(strat.rs_timeout) => {
|
||||
drop(permit);
|
||||
Err(Error::Timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn call_many<M, H, S>(
|
||||
&self,
|
||||
endpoint: &Endpoint<M, H>,
|
||||
to: &[Uuid],
|
||||
msg: M,
|
||||
strat: RequestStrategy,
|
||||
) -> Vec<(Uuid, Result<S, Error>)>
|
||||
where
|
||||
M: Rpc<Response = Result<S, Error>>,
|
||||
H: EndpointHandler<M>,
|
||||
{
|
||||
let msg = Arc::new(msg);
|
||||
let resps = join_all(
|
||||
to.iter()
|
||||
.map(|to| self.call_arc(endpoint, *to, msg.clone(), strat)),
|
||||
)
|
||||
.await;
|
||||
to.iter()
|
||||
.cloned()
|
||||
.zip(resps.into_iter())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
|
||||
pub async fn broadcast<M, H, S>(
|
||||
&self,
|
||||
endpoint: &Endpoint<M, H>,
|
||||
msg: M,
|
||||
strat: RequestStrategy,
|
||||
) -> Vec<(Uuid, Result<S, Error>)>
|
||||
where
|
||||
M: Rpc<Response = Result<S, Error>>,
|
||||
H: EndpointHandler<M>,
|
||||
{
|
||||
let to = self
|
||||
.0
|
||||
.fullmesh
|
||||
.get_peer_list()
|
||||
.iter()
|
||||
.map(|p| p.id.into())
|
||||
.collect::<Vec<_>>();
|
||||
self.call_many(endpoint, &to[..], msg, strat).await
|
||||
}
|
||||
|
||||
/// Make a RPC call to multiple servers, returning either a Vec of responses,
|
||||
/// or an error if quorum could not be reached due to too many errors
|
||||
pub async fn try_call_many<M, H, S>(
|
||||
&self,
|
||||
endpoint: &Arc<Endpoint<M, H>>,
|
||||
to: &[Uuid],
|
||||
msg: M,
|
||||
strategy: RequestStrategy,
|
||||
) -> Result<Vec<S>, Error>
|
||||
where
|
||||
M: Rpc<Response = Result<S, Error>> + 'static,
|
||||
H: EndpointHandler<M> + 'static,
|
||||
S: Send,
|
||||
{
|
||||
let msg = Arc::new(msg);
|
||||
|
||||
// Build future for each request
|
||||
// They are not started now: they are added below in a FuturesUnordered
|
||||
// object that will take care of polling them (see below)
|
||||
let requests = to.iter().cloned().map(|to| {
|
||||
let self2 = self.clone();
|
||||
let msg = msg.clone();
|
||||
let endpoint2 = endpoint.clone();
|
||||
(to, async move {
|
||||
self2.call_arc(&endpoint2, to, msg, strategy).await
|
||||
})
|
||||
});
|
||||
let quorum = strategy.rs_quorum.unwrap_or(to.len());
|
||||
|
||||
// Vectors in which success results and errors will be collected
|
||||
let mut successes = vec![];
|
||||
let mut errors = vec![];
|
||||
|
||||
if strategy.rs_interrupt_after_quorum {
|
||||
// Case 1: once quorum is reached, other requests don't matter.
|
||||
// What we do here is only send the required number of requests
|
||||
// to reach a quorum, priorizing nodes with the lowest latency.
|
||||
// When there are errors, we start new requests to compensate.
|
||||
|
||||
// Retrieve some status variables that we will use to sort requests
|
||||
let peer_list = self.0.fullmesh.get_peer_list();
|
||||
let ring: Arc<Ring> = self.0.ring.borrow().clone();
|
||||
let our_zone = match ring.config.members.get(&self.0.our_node_id) {
|
||||
Some(pc) => &pc.zone,
|
||||
None => "",
|
||||
};
|
||||
|
||||
// Augment requests with some information used to sort them.
|
||||
// The tuples are as follows:
|
||||
// (is another node?, is another zone?, latency, node ID, request future)
|
||||
// We store all of these tuples in a vec that we can sort.
|
||||
// By sorting this vec, we priorize ourself, then nodes in the same zone,
|
||||
// and within a same zone we priorize nodes with the lowest latency.
|
||||
let mut requests = requests
|
||||
.map(|(to, fut)| {
|
||||
let peer_zone = match ring.config.members.get(&to) {
|
||||
Some(pc) => &pc.zone,
|
||||
None => "",
|
||||
};
|
||||
let peer_avg_ping = peer_list
|
||||
.iter()
|
||||
.find(|x| x.id.as_ref() == to.as_slice())
|
||||
.map(|pi| pi.avg_ping)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Duration::from_secs(1));
|
||||
(
|
||||
to != self.0.our_node_id,
|
||||
peer_zone != our_zone,
|
||||
peer_avg_ping,
|
||||
to,
|
||||
fut,
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Sort requests by (priorize ourself, priorize same zone, priorize low latency)
|
||||
requests
|
||||
.sort_by_key(|(diffnode, diffzone, ping, _to, _fut)| (*diffnode, *diffzone, *ping));
|
||||
|
||||
// Make an iterator to take requests in their sorted order
|
||||
let mut requests = requests.into_iter();
|
||||
|
||||
// resp_stream will contain all of the requests that are currently in flight.
|
||||
// (for the moment none, they will be added in the loop below)
|
||||
let mut resp_stream = FuturesUnordered::new();
|
||||
|
||||
// Do some requests and collect results
|
||||
'request_loop: while successes.len() < quorum {
|
||||
// If the current set of requests that are running is not enough to possibly
|
||||
// reach quorum, start some new requests.
|
||||
while successes.len() + resp_stream.len() < quorum {
|
||||
if let Some((_, _, _, _to, fut)) = requests.next() {
|
||||
resp_stream.push(fut);
|
||||
} else {
|
||||
// If we have no request to add, we know that we won't ever
|
||||
// reach quorum: bail out now.
|
||||
break 'request_loop;
|
||||
}
|
||||
}
|
||||
assert!(!resp_stream.is_empty()); // because of loop invariants
|
||||
|
||||
// Wait for one request to terminate
|
||||
match resp_stream.next().await.unwrap() {
|
||||
Ok(msg) => {
|
||||
successes.push(msg);
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Case 2: all of the requests need to be sent in all cases,
|
||||
// and need to terminate. (this is the case for writes that
|
||||
// must be spread to n nodes)
|
||||
// Just start all the requests in parallel and return as soon
|
||||
// as the quorum is reached.
|
||||
let mut resp_stream = requests
|
||||
.map(|(_, fut)| fut)
|
||||
.collect::<FuturesUnordered<_>>();
|
||||
|
||||
while let Some(resp) = resp_stream.next().await {
|
||||
match resp {
|
||||
Ok(msg) => {
|
||||
successes.push(msg);
|
||||
if successes.len() >= quorum {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !resp_stream.is_empty() {
|
||||
// Continue remaining requests in background.
|
||||
// Continue the remaining requests immediately using tokio::spawn
|
||||
// but enqueue a task in the background runner
|
||||
// to ensure that the process won't exit until the requests are done
|
||||
// (if we had just enqueued the resp_stream.collect directly in the background runner,
|
||||
// the requests might have been put on hold in the background runner's queue,
|
||||
// in which case they might timeout or otherwise fail)
|
||||
let wait_finished_fut = tokio::spawn(async move {
|
||||
resp_stream.collect::<Vec<Result<_, _>>>().await;
|
||||
});
|
||||
self.0.background.spawn(wait_finished_fut.map(|_| Ok(())));
|
||||
}
|
||||
}
|
||||
|
||||
if successes.len() >= quorum {
|
||||
Ok(successes)
|
||||
} else {
|
||||
let errors = errors.iter().map(|e| format!("{}", e)).collect::<Vec<_>>();
|
||||
Err(Error::Quorum(quorum, successes.len(), to.len(), errors))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
//! Contains structs related to receiving RPCs
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
|
||||
use futures::future::Future;
|
||||
use futures_util::future::*;
|
||||
use futures_util::stream::*;
|
||||
use hyper::server::conn::AddrStream;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio_rustls::server::TlsStream;
|
||||
use tokio_rustls::TlsAcceptor;
|
||||
use tokio_stream::wrappers::TcpListenerStream;
|
||||
|
||||
use garage_util::config::TlsConfig;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
|
||||
use crate::tls_util;
|
||||
|
||||
/// Trait for messages that can be sent as RPC
|
||||
pub trait RpcMessage: Serialize + for<'de> Deserialize<'de> + Send + Sync {}
|
||||
|
||||
type ResponseFuture = Pin<Box<dyn Future<Output = Result<Response<Body>, Error>> + Send>>;
|
||||
type Handler = Box<dyn Fn(Request<Body>, SocketAddr) -> ResponseFuture + Send + Sync>;
|
||||
|
||||
/// Structure handling RPCs
|
||||
pub struct RpcServer {
|
||||
/// The address the RpcServer will bind
|
||||
pub bind_addr: SocketAddr,
|
||||
/// The tls configuration used for RPC
|
||||
pub tls_config: Option<TlsConfig>,
|
||||
|
||||
handlers: HashMap<String, Handler>,
|
||||
}
|
||||
|
||||
async fn handle_func<M, F, Fut>(
|
||||
handler: Arc<F>,
|
||||
req: Request<Body>,
|
||||
sockaddr: SocketAddr,
|
||||
name: Arc<String>,
|
||||
) -> Result<Response<Body>, Error>
|
||||
where
|
||||
M: RpcMessage + 'static,
|
||||
F: Fn(M, SocketAddr) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<M, Error>> + Send + 'static,
|
||||
{
|
||||
let begin_time = Instant::now();
|
||||
let whole_body = hyper::body::to_bytes(req.into_body()).await?;
|
||||
let msg = rmp_serde::decode::from_read::<_, M>(&whole_body[..])?;
|
||||
|
||||
trace!(
|
||||
"Request message: {}",
|
||||
serde_json::to_string(&msg)
|
||||
.unwrap_or_else(|_| "<json error>".into())
|
||||
.chars()
|
||||
.take(100)
|
||||
.collect::<String>()
|
||||
);
|
||||
|
||||
match handler(msg, sockaddr).await {
|
||||
Ok(resp) => {
|
||||
let resp_bytes = rmp_to_vec_all_named::<Result<M, String>>(&Ok(resp))?;
|
||||
let rpc_duration = (Instant::now() - begin_time).as_millis();
|
||||
if rpc_duration > 100 {
|
||||
debug!("RPC {} ok, took long: {} ms", name, rpc_duration,);
|
||||
}
|
||||
Ok(Response::new(Body::from(resp_bytes)))
|
||||
}
|
||||
Err(e) => {
|
||||
let err_str = format!("{}", e);
|
||||
let rep_bytes = rmp_to_vec_all_named::<Result<M, String>>(&Err(err_str))?;
|
||||
let mut err_response = Response::new(Body::from(rep_bytes));
|
||||
*err_response.status_mut() = match e {
|
||||
Error::BadRpc(_) => StatusCode::BAD_REQUEST,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
};
|
||||
warn!(
|
||||
"RPC error ({}): {} ({} ms)",
|
||||
name,
|
||||
e,
|
||||
(Instant::now() - begin_time).as_millis(),
|
||||
);
|
||||
Ok(err_response)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RpcServer {
|
||||
/// Create a new RpcServer
|
||||
pub fn new(bind_addr: SocketAddr, tls_config: Option<TlsConfig>) -> Self {
|
||||
Self {
|
||||
bind_addr,
|
||||
tls_config,
|
||||
handlers: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add handler handling request made to `name`
|
||||
pub fn add_handler<M, F, Fut>(&mut self, name: String, handler: F)
|
||||
where
|
||||
M: RpcMessage + 'static,
|
||||
F: Fn(M, SocketAddr) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<M, Error>> + Send + 'static,
|
||||
{
|
||||
let name2 = Arc::new(name.clone());
|
||||
let handler_arc = Arc::new(handler);
|
||||
let handler = Box::new(move |req: Request<Body>, sockaddr: SocketAddr| {
|
||||
let handler2 = handler_arc.clone();
|
||||
let b: ResponseFuture = Box::pin(handle_func(handler2, req, sockaddr, name2.clone()));
|
||||
b
|
||||
});
|
||||
self.handlers.insert(name, handler);
|
||||
}
|
||||
|
||||
async fn handler(
|
||||
self: Arc<Self>,
|
||||
req: Request<Body>,
|
||||
addr: SocketAddr,
|
||||
) -> Result<Response<Body>, Error> {
|
||||
if req.method() != Method::POST {
|
||||
let mut bad_request = Response::default();
|
||||
*bad_request.status_mut() = StatusCode::BAD_REQUEST;
|
||||
return Ok(bad_request);
|
||||
}
|
||||
|
||||
let path = &req.uri().path()[1..].to_string();
|
||||
|
||||
let handler = match self.handlers.get(path) {
|
||||
Some(h) => h,
|
||||
None => {
|
||||
let mut not_found = Response::default();
|
||||
*not_found.status_mut() = StatusCode::NOT_FOUND;
|
||||
return Ok(not_found);
|
||||
}
|
||||
};
|
||||
|
||||
trace!("({}) Handling request", path);
|
||||
|
||||
let resp_waiter = tokio::spawn(handler(req, addr));
|
||||
match resp_waiter.await {
|
||||
Err(err) => {
|
||||
warn!("Handler await error: {}", err);
|
||||
let mut ise = Response::default();
|
||||
*ise.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
|
||||
Ok(ise)
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
trace!("({}) Request handler failed: {}", path, err);
|
||||
let mut bad_request = Response::new(Body::from(format!("{}", err)));
|
||||
*bad_request.status_mut() = StatusCode::BAD_REQUEST;
|
||||
Ok(bad_request)
|
||||
}
|
||||
Ok(Ok(resp)) => {
|
||||
trace!("({}) Request handler succeeded", path);
|
||||
Ok(resp)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the RpcServer
|
||||
pub async fn run(
|
||||
self: Arc<Self>,
|
||||
shutdown_signal: impl Future<Output = ()>,
|
||||
) -> Result<(), Error> {
|
||||
if let Some(tls_config) = self.tls_config.as_ref() {
|
||||
let ca_certs = tls_util::load_certs(&tls_config.ca_cert)?;
|
||||
let node_certs = tls_util::load_certs(&tls_config.node_cert)?;
|
||||
let node_key = tls_util::load_private_key(&tls_config.node_key)?;
|
||||
|
||||
let mut ca_store = rustls::RootCertStore::empty();
|
||||
for crt in ca_certs.iter() {
|
||||
ca_store.add(crt)?;
|
||||
}
|
||||
|
||||
let mut config =
|
||||
rustls::ServerConfig::new(rustls::AllowAnyAuthenticatedClient::new(ca_store));
|
||||
config.set_single_cert([&node_certs[..], &ca_certs[..]].concat(), node_key)?;
|
||||
let tls_acceptor = Arc::new(TlsAcceptor::from(Arc::new(config)));
|
||||
|
||||
let listener = TcpListener::bind(&self.bind_addr).await?;
|
||||
let incoming = TcpListenerStream::new(listener).filter_map(|socket| async {
|
||||
match socket {
|
||||
Ok(stream) => match tls_acceptor.clone().accept(stream).await {
|
||||
Ok(x) => Some(Ok::<_, hyper::Error>(x)),
|
||||
Err(_e) => None,
|
||||
},
|
||||
Err(_) => None,
|
||||
}
|
||||
});
|
||||
let incoming = hyper::server::accept::from_stream(incoming);
|
||||
|
||||
let self_arc = self.clone();
|
||||
let service = make_service_fn(|conn: &TlsStream<TcpStream>| {
|
||||
let client_addr = conn
|
||||
.get_ref()
|
||||
.0
|
||||
.peer_addr()
|
||||
.unwrap_or_else(|_| ([0, 0, 0, 0], 0).into());
|
||||
let self_arc = self_arc.clone();
|
||||
async move {
|
||||
Ok::<_, Error>(service_fn(move |req: Request<Body>| {
|
||||
self_arc.clone().handler(req, client_addr).map_err(|e| {
|
||||
warn!("RPC handler error: {}", e);
|
||||
e
|
||||
})
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::builder(incoming).serve(service);
|
||||
|
||||
let graceful = server.with_graceful_shutdown(shutdown_signal);
|
||||
info!("RPC server listening on http://{}", self.bind_addr);
|
||||
|
||||
graceful.await?;
|
||||
} else {
|
||||
let self_arc = self.clone();
|
||||
let service = make_service_fn(move |conn: &AddrStream| {
|
||||
let client_addr = conn.remote_addr();
|
||||
let self_arc = self_arc.clone();
|
||||
async move {
|
||||
Ok::<_, Error>(service_fn(move |req: Request<Body>| {
|
||||
self_arc.clone().handler(req, client_addr).map_err(|e| {
|
||||
warn!("RPC handler error: {}", e);
|
||||
e
|
||||
})
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&self.bind_addr).serve(service);
|
||||
|
||||
let graceful = server.with_graceful_shutdown(shutdown_signal);
|
||||
info!("RPC server listening on http://{}", self.bind_addr);
|
||||
|
||||
graceful.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
//! Module containing structs related to membership management
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use async_trait::async_trait;
|
||||
use futures::{join, select};
|
||||
use futures_util::future::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sodiumoxide::crypto::sign::ed25519;
|
||||
use tokio::sync::watch;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use netapp::endpoint::{Endpoint, EndpointHandler};
|
||||
use netapp::peering::fullmesh::FullMeshPeeringStrategy;
|
||||
use netapp::proto::*;
|
||||
use netapp::util::parse_and_resolve_peer_addr;
|
||||
use netapp::{NetApp, NetworkKey, NodeID, NodeKey};
|
||||
|
||||
use garage_util::background::BackgroundRunner;
|
||||
use garage_util::config::Config;
|
||||
use garage_util::data::Uuid;
|
||||
use garage_util::error::*;
|
||||
use garage_util::persister::Persister;
|
||||
use garage_util::time::*;
|
||||
|
||||
use crate::consul::*;
|
||||
use crate::ring::*;
|
||||
use crate::rpc_helper::*;
|
||||
|
||||
const DISCOVERY_INTERVAL: Duration = Duration::from_secs(60);
|
||||
const STATUS_EXCHANGE_INTERVAL: Duration = Duration::from_secs(10);
|
||||
const PING_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
/// RPC endpoint used for calls related to membership
|
||||
pub const SYSTEM_RPC_PATH: &str = "garage_rpc/membership.rs/SystemRpc";
|
||||
|
||||
pub const CONNECT_ERROR_MESSAGE: &str = "Error establishing RPC connection to remote node. This can happen if the remote node is not reachable on the network, but also if the two nodes are not configured with the same rpc_secret";
|
||||
|
||||
/// RPC messages related to membership
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub enum SystemRpc {
|
||||
/// Response to successfull advertisements
|
||||
Ok,
|
||||
/// Request to connect to a specific node (in <pubkey>@<host>:<port> format)
|
||||
Connect(String),
|
||||
/// Ask other node its config. Answered with AdvertiseConfig
|
||||
PullConfig,
|
||||
/// Advertise Garage status. Answered with another AdvertiseStatus.
|
||||
/// Exchanged with every node on a regular basis.
|
||||
AdvertiseStatus(NodeStatus),
|
||||
/// Advertisement of nodes config. Sent spontanously or in response to PullConfig
|
||||
AdvertiseConfig(NetworkConfig),
|
||||
/// Get known nodes states
|
||||
GetKnownNodes,
|
||||
/// Return known nodes
|
||||
ReturnKnownNodes(Vec<KnownNodeInfo>),
|
||||
}
|
||||
|
||||
impl Rpc for SystemRpc {
|
||||
type Response = Result<SystemRpc, Error>;
|
||||
}
|
||||
|
||||
/// This node's membership manager
|
||||
pub struct System {
|
||||
/// The id of this node
|
||||
pub id: Uuid,
|
||||
|
||||
persist_config: Persister<NetworkConfig>,
|
||||
persist_peer_list: Persister<Vec<(Uuid, SocketAddr)>>,
|
||||
|
||||
local_status: ArcSwap<NodeStatus>,
|
||||
node_status: RwLock<HashMap<Uuid, (u64, NodeStatus)>>,
|
||||
|
||||
pub netapp: Arc<NetApp>,
|
||||
fullmesh: Arc<FullMeshPeeringStrategy>,
|
||||
pub rpc: RpcHelper,
|
||||
|
||||
system_endpoint: Arc<Endpoint<SystemRpc, System>>,
|
||||
|
||||
rpc_listen_addr: SocketAddr,
|
||||
rpc_public_addr: Option<SocketAddr>,
|
||||
bootstrap_peers: Vec<(NodeID, SocketAddr)>,
|
||||
consul_host: Option<String>,
|
||||
consul_service_name: Option<String>,
|
||||
replication_factor: usize,
|
||||
|
||||
/// The ring
|
||||
pub ring: watch::Receiver<Arc<Ring>>,
|
||||
update_ring: Mutex<watch::Sender<Arc<Ring>>>,
|
||||
|
||||
/// The job runner of this node
|
||||
pub background: Arc<BackgroundRunner>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NodeStatus {
|
||||
/// Hostname of the node
|
||||
pub hostname: String,
|
||||
/// Replication factor configured on the node
|
||||
pub replication_factor: usize,
|
||||
/// Configuration version
|
||||
pub config_version: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct KnownNodeInfo {
|
||||
pub id: Uuid,
|
||||
pub addr: SocketAddr,
|
||||
pub is_up: bool,
|
||||
pub last_seen_secs_ago: Option<u64>,
|
||||
pub status: NodeStatus,
|
||||
}
|
||||
|
||||
pub fn read_node_id(metadata_dir: &Path) -> Result<NodeID, Error> {
|
||||
let mut pubkey_file = metadata_dir.to_path_buf();
|
||||
pubkey_file.push("node_key.pub");
|
||||
|
||||
let mut f = std::fs::File::open(pubkey_file.as_path())?;
|
||||
let mut d = vec![];
|
||||
f.read_to_end(&mut d)?;
|
||||
if d.len() != 32 {
|
||||
return Err(Error::Message("Corrupt node_key.pub file".to_string()));
|
||||
}
|
||||
|
||||
let mut key = [0u8; 32];
|
||||
key.copy_from_slice(&d[..]);
|
||||
Ok(NodeID::from_slice(&key[..]).unwrap())
|
||||
}
|
||||
|
||||
pub fn gen_node_key(metadata_dir: &Path) -> Result<NodeKey, Error> {
|
||||
let mut key_file = metadata_dir.to_path_buf();
|
||||
key_file.push("node_key");
|
||||
if key_file.as_path().exists() {
|
||||
let mut f = std::fs::File::open(key_file.as_path())?;
|
||||
let mut d = vec![];
|
||||
f.read_to_end(&mut d)?;
|
||||
if d.len() != 64 {
|
||||
return Err(Error::Message("Corrupt node_key file".to_string()));
|
||||
}
|
||||
|
||||
let mut key = [0u8; 64];
|
||||
key.copy_from_slice(&d[..]);
|
||||
Ok(NodeKey::from_slice(&key[..]).unwrap())
|
||||
} else {
|
||||
if !metadata_dir.exists() {
|
||||
info!("Metadata directory does not exist, creating it.");
|
||||
std::fs::create_dir(&metadata_dir)?;
|
||||
}
|
||||
|
||||
info!("Generating new node key pair.");
|
||||
let (pubkey, key) = ed25519::gen_keypair();
|
||||
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mut f = std::fs::File::create(key_file.as_path())?;
|
||||
let mut perm = f.metadata()?.permissions();
|
||||
perm.set_mode(0o600);
|
||||
std::fs::set_permissions(key_file.as_path(), perm)?;
|
||||
f.write_all(&key[..])?;
|
||||
}
|
||||
|
||||
{
|
||||
let mut pubkey_file = metadata_dir.to_path_buf();
|
||||
pubkey_file.push("node_key.pub");
|
||||
let mut f2 = std::fs::File::create(pubkey_file.as_path())?;
|
||||
f2.write_all(&pubkey[..])?;
|
||||
}
|
||||
|
||||
Ok(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl System {
|
||||
/// Create this node's membership manager
|
||||
pub fn new(
|
||||
network_key: NetworkKey,
|
||||
background: Arc<BackgroundRunner>,
|
||||
replication_factor: usize,
|
||||
config: &Config,
|
||||
) -> Arc<Self> {
|
||||
let node_key =
|
||||
gen_node_key(&config.metadata_dir).expect("Unable to read or generate node ID");
|
||||
info!("Node public key: {}", hex::encode(&node_key.public_key()));
|
||||
|
||||
let persist_config = Persister::new(&config.metadata_dir, "network_config");
|
||||
let persist_peer_list = Persister::new(&config.metadata_dir, "peer_list");
|
||||
|
||||
let net_config = match persist_config.load() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
info!(
|
||||
"No valid previous network configuration stored ({}), starting fresh.",
|
||||
e
|
||||
);
|
||||
NetworkConfig::new()
|
||||
}
|
||||
};
|
||||
|
||||
let local_status = NodeStatus {
|
||||
hostname: gethostname::gethostname()
|
||||
.into_string()
|
||||
.unwrap_or_else(|_| "<invalid utf-8>".to_string()),
|
||||
replication_factor,
|
||||
config_version: net_config.version,
|
||||
};
|
||||
|
||||
let ring = Ring::new(net_config, replication_factor);
|
||||
let (update_ring, ring) = watch::channel(Arc::new(ring));
|
||||
|
||||
if let Some(addr) = config.rpc_public_addr {
|
||||
println!("{}@{}", hex::encode(&node_key.public_key()), addr);
|
||||
} else {
|
||||
println!("{}", hex::encode(&node_key.public_key()));
|
||||
}
|
||||
|
||||
let netapp = NetApp::new(network_key, node_key);
|
||||
let fullmesh = FullMeshPeeringStrategy::new(
|
||||
netapp.clone(),
|
||||
config.bootstrap_peers.clone(),
|
||||
config.rpc_public_addr,
|
||||
);
|
||||
|
||||
let system_endpoint = netapp.endpoint(SYSTEM_RPC_PATH.into());
|
||||
|
||||
let sys = Arc::new(System {
|
||||
id: netapp.id.into(),
|
||||
persist_config,
|
||||
persist_peer_list,
|
||||
local_status: ArcSwap::new(Arc::new(local_status)),
|
||||
node_status: RwLock::new(HashMap::new()),
|
||||
netapp: netapp.clone(),
|
||||
fullmesh: fullmesh.clone(),
|
||||
rpc: RpcHelper::new(netapp.id.into(), fullmesh, background.clone(), ring.clone()),
|
||||
system_endpoint,
|
||||
replication_factor,
|
||||
rpc_listen_addr: config.rpc_bind_addr,
|
||||
rpc_public_addr: config.rpc_public_addr,
|
||||
bootstrap_peers: config.bootstrap_peers.clone(),
|
||||
consul_host: config.consul_host.clone(),
|
||||
consul_service_name: config.consul_service_name.clone(),
|
||||
ring,
|
||||
update_ring: Mutex::new(update_ring),
|
||||
background,
|
||||
});
|
||||
sys.system_endpoint.set_handler(sys.clone());
|
||||
sys
|
||||
}
|
||||
|
||||
/// Perform bootstraping, starting the ping loop
|
||||
pub async fn run(self: Arc<Self>, must_exit: watch::Receiver<bool>) {
|
||||
join!(
|
||||
self.netapp
|
||||
.clone()
|
||||
.listen(self.rpc_listen_addr, None, must_exit.clone()),
|
||||
self.fullmesh.clone().run(must_exit.clone()),
|
||||
self.discovery_loop(must_exit.clone()),
|
||||
self.status_exchange_loop(must_exit.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
// ---- INTERNALS ----
|
||||
|
||||
async fn advertise_to_consul(self: Arc<Self>) -> Result<(), Error> {
|
||||
let (consul_host, consul_service_name) =
|
||||
match (&self.consul_host, &self.consul_service_name) {
|
||||
(Some(ch), Some(csn)) => (ch, csn),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
|
||||
let rpc_public_addr = match self.rpc_public_addr {
|
||||
Some(addr) => addr,
|
||||
None => {
|
||||
warn!("Not advertising to Consul because rpc_public_addr is not defined in config file.");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
publish_consul_service(
|
||||
consul_host,
|
||||
consul_service_name,
|
||||
self.netapp.id,
|
||||
&self.local_status.load_full().hostname,
|
||||
rpc_public_addr,
|
||||
)
|
||||
.await
|
||||
.err_context("Error while publishing Consul service")
|
||||
}
|
||||
|
||||
/// Save network configuration to disc
|
||||
async fn save_network_config(self: Arc<Self>) -> Result<(), Error> {
|
||||
let ring: Arc<Ring> = self.ring.borrow().clone();
|
||||
self.persist_config
|
||||
.save_async(&ring.config)
|
||||
.await
|
||||
.expect("Cannot save current cluster configuration");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_local_status(&self) {
|
||||
let mut new_si: NodeStatus = self.local_status.load().as_ref().clone();
|
||||
|
||||
let ring = self.ring.borrow();
|
||||
new_si.config_version = ring.config.version;
|
||||
self.local_status.swap(Arc::new(new_si));
|
||||
}
|
||||
|
||||
async fn handle_connect(&self, node: &str) -> Result<SystemRpc, Error> {
|
||||
let (pubkey, addrs) = parse_and_resolve_peer_addr(node).ok_or_else(|| {
|
||||
Error::Message(format!(
|
||||
"Unable to parse or resolve node specification: {}",
|
||||
node
|
||||
))
|
||||
})?;
|
||||
let mut errors = vec![];
|
||||
for ip in addrs.iter() {
|
||||
match self
|
||||
.netapp
|
||||
.clone()
|
||||
.try_connect(*ip, pubkey)
|
||||
.await
|
||||
.err_context(CONNECT_ERROR_MESSAGE)
|
||||
{
|
||||
Ok(()) => return Ok(SystemRpc::Ok),
|
||||
Err(e) => {
|
||||
errors.push((*ip, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(Error::Message(format!(
|
||||
"Could not connect to specified peers. Errors: {:?}",
|
||||
errors
|
||||
)));
|
||||
}
|
||||
|
||||
fn handle_pull_config(&self) -> SystemRpc {
|
||||
let ring = self.ring.borrow().clone();
|
||||
SystemRpc::AdvertiseConfig(ring.config.clone())
|
||||
}
|
||||
|
||||
fn handle_get_known_nodes(&self) -> SystemRpc {
|
||||
let node_status = self.node_status.read().unwrap();
|
||||
let known_nodes = self
|
||||
.fullmesh
|
||||
.get_peer_list()
|
||||
.iter()
|
||||
.map(|n| KnownNodeInfo {
|
||||
id: n.id.into(),
|
||||
addr: n.addr,
|
||||
is_up: n.is_up(),
|
||||
last_seen_secs_ago: n.last_seen.map(|t| (Instant::now() - t).as_secs()),
|
||||
status: node_status
|
||||
.get(&n.id.into())
|
||||
.cloned()
|
||||
.map(|(_, st)| st)
|
||||
.unwrap_or(NodeStatus {
|
||||
hostname: "?".to_string(),
|
||||
replication_factor: 0,
|
||||
config_version: 0,
|
||||
}),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
SystemRpc::ReturnKnownNodes(known_nodes)
|
||||
}
|
||||
|
||||
async fn handle_advertise_status(
|
||||
self: &Arc<Self>,
|
||||
from: Uuid,
|
||||
info: &NodeStatus,
|
||||
) -> Result<SystemRpc, Error> {
|
||||
let local_info = self.local_status.load();
|
||||
|
||||
if local_info.replication_factor < info.replication_factor {
|
||||
error!("Some node have a higher replication factor ({}) than this one ({}). This is not supported and might lead to bugs",
|
||||
info.replication_factor,
|
||||
local_info.replication_factor);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
if info.config_version > local_info.config_version {
|
||||
let self2 = self.clone();
|
||||
self.background.spawn_cancellable(async move {
|
||||
self2.pull_config(from).await;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
self.node_status
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(from, (now_msec(), info.clone()));
|
||||
|
||||
Ok(SystemRpc::Ok)
|
||||
}
|
||||
|
||||
async fn handle_advertise_config(
|
||||
self: Arc<Self>,
|
||||
adv: &NetworkConfig,
|
||||
) -> Result<SystemRpc, Error> {
|
||||
let update_ring = self.update_ring.lock().await;
|
||||
let ring: Arc<Ring> = self.ring.borrow().clone();
|
||||
|
||||
if adv.version > ring.config.version {
|
||||
let ring = Ring::new(adv.clone(), self.replication_factor);
|
||||
update_ring.send(Arc::new(ring))?;
|
||||
drop(update_ring);
|
||||
|
||||
let self2 = self.clone();
|
||||
let adv = adv.clone();
|
||||
self.background.spawn_cancellable(async move {
|
||||
self2
|
||||
.rpc
|
||||
.broadcast(
|
||||
&self2.system_endpoint,
|
||||
SystemRpc::AdvertiseConfig(adv),
|
||||
RequestStrategy::with_priority(PRIO_HIGH),
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
});
|
||||
self.background.spawn(self.clone().save_network_config());
|
||||
}
|
||||
|
||||
Ok(SystemRpc::Ok)
|
||||
}
|
||||
|
||||
async fn status_exchange_loop(&self, mut stop_signal: watch::Receiver<bool>) {
|
||||
while !*stop_signal.borrow() {
|
||||
let restart_at = tokio::time::sleep(STATUS_EXCHANGE_INTERVAL);
|
||||
|
||||
self.update_local_status();
|
||||
let local_status: NodeStatus = self.local_status.load().as_ref().clone();
|
||||
self.rpc
|
||||
.broadcast(
|
||||
&self.system_endpoint,
|
||||
SystemRpc::AdvertiseStatus(local_status),
|
||||
RequestStrategy::with_priority(PRIO_HIGH).with_timeout(PING_TIMEOUT),
|
||||
)
|
||||
.await;
|
||||
|
||||
select! {
|
||||
_ = restart_at.fuse() => {},
|
||||
_ = stop_signal.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discovery_loop(self: &Arc<Self>, mut stop_signal: watch::Receiver<bool>) {
|
||||
let consul_config = match (&self.consul_host, &self.consul_service_name) {
|
||||
(Some(ch), Some(csn)) => Some((ch.clone(), csn.clone())),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
while !*stop_signal.borrow() {
|
||||
let not_configured = self.ring.borrow().config.members.is_empty();
|
||||
let no_peers = self.fullmesh.get_peer_list().len() < self.replication_factor;
|
||||
let bad_peers = self
|
||||
.fullmesh
|
||||
.get_peer_list()
|
||||
.iter()
|
||||
.filter(|p| p.is_up())
|
||||
.count() != self.ring.borrow().config.members.len();
|
||||
|
||||
if not_configured || no_peers || bad_peers {
|
||||
info!("Doing a bootstrap/discovery step (not_configured: {}, no_peers: {}, bad_peers: {})", not_configured, no_peers, bad_peers);
|
||||
|
||||
let mut ping_list = self.bootstrap_peers.clone();
|
||||
|
||||
// Add peer list from list stored on disk
|
||||
if let Ok(peers) = self.persist_peer_list.load_async().await {
|
||||
ping_list.extend(peers.iter().map(|(id, addr)| ((*id).into(), *addr)))
|
||||
}
|
||||
|
||||
// Fetch peer list from Consul
|
||||
if let Some((consul_host, consul_service_name)) = &consul_config {
|
||||
match get_consul_nodes(consul_host, consul_service_name).await {
|
||||
Ok(node_list) => {
|
||||
ping_list.extend(node_list);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Could not retrieve node list from Consul: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (node_id, node_addr) in ping_list {
|
||||
tokio::spawn(
|
||||
self.netapp
|
||||
.clone()
|
||||
.try_connect(node_addr, node_id)
|
||||
.map(|r| r.err_context(CONNECT_ERROR_MESSAGE)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(e) = self.save_peer_list().await {
|
||||
warn!("Could not save peer list to file: {}", e);
|
||||
}
|
||||
|
||||
self.background.spawn(self.clone().advertise_to_consul());
|
||||
|
||||
let restart_at = tokio::time::sleep(DISCOVERY_INTERVAL);
|
||||
select! {
|
||||
_ = restart_at.fuse() => {},
|
||||
_ = stop_signal.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn save_peer_list(&self) -> Result<(), Error> {
|
||||
// Prepare new peer list to save to file
|
||||
// It is a vec of tuples (node ID as Uuid, node SocketAddr)
|
||||
let mut peer_list = self
|
||||
.fullmesh
|
||||
.get_peer_list()
|
||||
.iter()
|
||||
.map(|n| (n.id.into(), n.addr))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Before doing it, we read the current peer list file (if it exists)
|
||||
// and append it to the list we are about to save,
|
||||
// so that no peer ID gets lost in the process.
|
||||
if let Ok(mut prev_peer_list) = self.persist_peer_list.load_async().await {
|
||||
prev_peer_list.retain(|(id, _ip)| peer_list.iter().all(|(id2, _ip2)| id2 != id));
|
||||
peer_list.extend(prev_peer_list);
|
||||
}
|
||||
|
||||
// Save new peer list to file
|
||||
self.persist_peer_list.save_async(&peer_list).await
|
||||
}
|
||||
|
||||
async fn pull_config(self: Arc<Self>, peer: Uuid) {
|
||||
let resp = self
|
||||
.rpc
|
||||
.call(
|
||||
&self.system_endpoint,
|
||||
peer,
|
||||
SystemRpc::PullConfig,
|
||||
RequestStrategy::with_priority(PRIO_HIGH).with_timeout(PING_TIMEOUT),
|
||||
)
|
||||
.await;
|
||||
if let Ok(SystemRpc::AdvertiseConfig(config)) = resp {
|
||||
let _: Result<_, _> = self.handle_advertise_config(&config).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EndpointHandler<SystemRpc> for System {
|
||||
async fn handle(self: &Arc<Self>, msg: &SystemRpc, from: NodeID) -> Result<SystemRpc, Error> {
|
||||
match msg {
|
||||
SystemRpc::Connect(node) => self.handle_connect(node).await,
|
||||
SystemRpc::PullConfig => Ok(self.handle_pull_config()),
|
||||
SystemRpc::AdvertiseStatus(adv) => self.handle_advertise_status(from.into(), adv).await,
|
||||
SystemRpc::AdvertiseConfig(adv) => self.clone().handle_advertise_config(adv).await,
|
||||
SystemRpc::GetKnownNodes => Ok(self.handle_get_known_nodes()),
|
||||
_ => Err(Error::BadRpc("Unexpected RPC message".to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
use core::future::Future;
|
||||
use core::task::{Context, Poll};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::{fs, io};
|
||||
|
||||
use futures_util::future::*;
|
||||
use hyper::client::connect::Connection;
|
||||
use hyper::client::HttpConnector;
|
||||
use hyper::service::Service;
|
||||
use hyper::Uri;
|
||||
use hyper_rustls::MaybeHttpsStream;
|
||||
use rustls::internal::pemfile;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls::TlsConnector;
|
||||
use webpki::DNSNameRef;
|
||||
|
||||
use garage_util::error::Error;
|
||||
|
||||
pub fn load_certs(filename: &str) -> Result<Vec<rustls::Certificate>, Error> {
|
||||
let certfile = fs::File::open(&filename)?;
|
||||
let mut reader = io::BufReader::new(certfile);
|
||||
|
||||
let certs = pemfile::certs(&mut reader).map_err(|_| {
|
||||
Error::Message(format!(
|
||||
"Could not deecode certificates from file: {}",
|
||||
filename
|
||||
))
|
||||
})?;
|
||||
|
||||
if certs.is_empty() {
|
||||
return Err(Error::Message(format!(
|
||||
"Invalid certificate file: {}",
|
||||
filename
|
||||
)));
|
||||
}
|
||||
Ok(certs)
|
||||
}
|
||||
|
||||
pub fn load_private_key(filename: &str) -> Result<rustls::PrivateKey, Error> {
|
||||
let keydata = fs::read_to_string(filename)?;
|
||||
|
||||
let mut buf1 = keydata.as_bytes();
|
||||
let rsa_keys = pemfile::rsa_private_keys(&mut buf1).unwrap_or_default();
|
||||
|
||||
let mut buf2 = keydata.as_bytes();
|
||||
let pkcs8_keys = pemfile::pkcs8_private_keys(&mut buf2).unwrap_or_default();
|
||||
|
||||
let mut keys = rsa_keys;
|
||||
keys.extend(pkcs8_keys.into_iter());
|
||||
|
||||
if keys.len() != 1 {
|
||||
return Err(Error::Message(format!(
|
||||
"Invalid private key file: {} ({} private keys)",
|
||||
filename,
|
||||
keys.len()
|
||||
)));
|
||||
}
|
||||
Ok(keys[0].clone())
|
||||
}
|
||||
|
||||
// ---- AWFUL COPYPASTA FROM HYPER-RUSTLS connector.rs
|
||||
// ---- ALWAYS USE `garage` AS HOSTNAME FOR TLS VERIFICATION
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HttpsConnectorFixedDnsname<T> {
|
||||
http: T,
|
||||
tls_config: Arc<rustls::ClientConfig>,
|
||||
fixed_dnsname: &'static str,
|
||||
}
|
||||
|
||||
type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
impl HttpsConnectorFixedDnsname<HttpConnector> {
|
||||
pub fn new(mut tls_config: rustls::ClientConfig, fixed_dnsname: &'static str) -> Self {
|
||||
let mut http = HttpConnector::new();
|
||||
http.enforce_http(false);
|
||||
tls_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
Self {
|
||||
http,
|
||||
tls_config: Arc::new(tls_config),
|
||||
fixed_dnsname,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service<Uri> for HttpsConnectorFixedDnsname<T>
|
||||
where
|
||||
T: Service<Uri>,
|
||||
T::Response: Connection + AsyncRead + AsyncWrite + Send + Unpin + 'static,
|
||||
T::Future: Send + 'static,
|
||||
T::Error: Into<BoxError>,
|
||||
{
|
||||
type Response = MaybeHttpsStream<T::Response>;
|
||||
type Error = BoxError;
|
||||
|
||||
#[allow(clippy::type_complexity)]
|
||||
type Future =
|
||||
Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<T::Response>, BoxError>> + Send>>;
|
||||
|
||||
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
match self.http.poll_ready(cx) {
|
||||
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
|
||||
Poll::Ready(Err(e)) => Poll::Ready(Err(e.into())),
|
||||
Poll::Pending => Poll::Pending,
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, dst: Uri) -> Self::Future {
|
||||
let is_https = dst.scheme_str() == Some("https");
|
||||
|
||||
if !is_https {
|
||||
let connecting_future = self.http.call(dst);
|
||||
|
||||
let f = async move {
|
||||
let tcp = connecting_future.await.map_err(Into::into)?;
|
||||
|
||||
Ok(MaybeHttpsStream::Http(tcp))
|
||||
};
|
||||
f.boxed()
|
||||
} else {
|
||||
let cfg = self.tls_config.clone();
|
||||
let connecting_future = self.http.call(dst);
|
||||
|
||||
let dnsname =
|
||||
DNSNameRef::try_from_ascii_str(self.fixed_dnsname).expect("Invalid fixed dnsname");
|
||||
|
||||
let f = async move {
|
||||
let tcp = connecting_future.await.map_err(Into::into)?;
|
||||
let connector = TlsConnector::from(cfg);
|
||||
let tls = connector
|
||||
.connect(dnsname, tcp)
|
||||
.await
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
Ok(MaybeHttpsStream::Https(tls))
|
||||
};
|
||||
f.boxed()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage_table"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -13,9 +13,10 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_rpc = { version = "0.3.0", path = "../rpc" }
|
||||
garage_util = { version = "0.3.0", path = "../util" }
|
||||
garage_rpc = { version = "0.4.0", path = "../rpc" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
|
||||
async-trait = "0.1.7"
|
||||
bytes = "1.0"
|
||||
hexdump = "0.1"
|
||||
log = "0.4"
|
||||
@@ -30,4 +31,3 @@ serde_bytes = "0.11"
|
||||
futures = "0.3"
|
||||
futures-util = "0.3"
|
||||
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
|
||||
|
||||
|
||||
@@ -103,7 +103,7 @@ where
|
||||
}
|
||||
/// Get a reference to the value assigned to a key
|
||||
pub fn get(&self, k: &K) -> Option<&V> {
|
||||
match self.vals.binary_search_by(|(k2, _, _)| k2.cmp(&k)) {
|
||||
match self.vals.binary_search_by(|(k2, _, _)| k2.cmp(k)) {
|
||||
Ok(i) => Some(&self.vals[i].2),
|
||||
Err(_) => None,
|
||||
}
|
||||
@@ -132,14 +132,14 @@ where
|
||||
{
|
||||
fn merge(&mut self, other: &Self) {
|
||||
for (k, ts2, v2) in other.vals.iter() {
|
||||
match self.vals.binary_search_by(|(k2, _, _)| k2.cmp(&k)) {
|
||||
match self.vals.binary_search_by(|(k2, _, _)| k2.cmp(k)) {
|
||||
Ok(i) => {
|
||||
let (_, ts1, _v1) = &self.vals[i];
|
||||
if ts2 > ts1 {
|
||||
self.vals[i].1 = *ts2;
|
||||
self.vals[i].2 = v2.clone();
|
||||
} else if ts1 == ts2 {
|
||||
self.vals[i].2.merge(&v2);
|
||||
self.vals[i].2.merge(v2);
|
||||
}
|
||||
}
|
||||
Err(i) => {
|
||||
|
||||
@@ -49,7 +49,7 @@ where
|
||||
|
||||
/// Get a reference to the value assigned to a key
|
||||
pub fn get(&self, k: &K) -> Option<&V> {
|
||||
match self.vals.binary_search_by(|(k2, _)| k2.cmp(&k)) {
|
||||
match self.vals.binary_search_by(|(k2, _)| k2.cmp(k)) {
|
||||
Ok(i) => Some(&self.vals[i].1),
|
||||
Err(_) => None,
|
||||
}
|
||||
@@ -76,9 +76,9 @@ where
|
||||
{
|
||||
fn merge(&mut self, other: &Self) {
|
||||
for (k, v2) in other.vals.iter() {
|
||||
match self.vals.binary_search_by(|(k2, _)| k2.cmp(&k)) {
|
||||
match self.vals.binary_search_by(|(k2, _)| k2.cmp(k)) {
|
||||
Ok(i) => {
|
||||
self.vals[i].1.merge(&v2);
|
||||
self.vals[i].1.merge(v2);
|
||||
}
|
||||
Err(i) => {
|
||||
self.vals.insert(i, (k.clone(), v2.clone()));
|
||||
|
||||
+4
-3
@@ -9,9 +9,10 @@ use tokio::sync::Notify;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::*;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::system::System;
|
||||
|
||||
use crate::crdt::Crdt;
|
||||
use crate::gc::GcTodoEntry;
|
||||
use crate::replication::*;
|
||||
use crate::schema::*;
|
||||
|
||||
@@ -54,7 +55,7 @@ where
|
||||
.expect("Unable to open DB Merkle TODO tree");
|
||||
|
||||
let gc_todo = db
|
||||
.open_tree(&format!("{}:gc_todo", name))
|
||||
.open_tree(&format!("{}:gc_todo_v2", name))
|
||||
.expect("Unable to open DB tree");
|
||||
|
||||
Arc::new(Self {
|
||||
@@ -176,7 +177,7 @@ where
|
||||
let pk_hash = Hash::try_from(&tree_key[..32]).unwrap();
|
||||
let nodes = self.replication.write_nodes(&pk_hash);
|
||||
if nodes.first() == Some(&self.system.id) {
|
||||
self.gc_todo.insert(&tree_key, new_bytes_hash.as_slice())?;
|
||||
GcTodoEntry::new(tree_key, new_bytes_hash).save(&self.gc_todo)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+222
-81
@@ -1,7 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryInto;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_bytes::ByteBuf;
|
||||
|
||||
@@ -11,11 +13,11 @@ use futures_util::future::*;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
use garage_util::error::*;
|
||||
use garage_util::time::*;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::rpc_client::*;
|
||||
use garage_rpc::rpc_server::*;
|
||||
use garage_rpc::system::System;
|
||||
use garage_rpc::*;
|
||||
|
||||
use crate::data::*;
|
||||
use crate::replication::*;
|
||||
@@ -24,11 +26,16 @@ use crate::schema::*;
|
||||
const TABLE_GC_BATCH_SIZE: usize = 1024;
|
||||
const TABLE_GC_RPC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub struct TableGc<F: TableSchema, R: TableReplication> {
|
||||
// GC delay for table entries: 1 day (24 hours)
|
||||
// (the delay before the entry is added in the GC todo list
|
||||
// and the moment the garbage collection actually happens)
|
||||
const TABLE_GC_DELAY: Duration = Duration::from_secs(24 * 3600);
|
||||
|
||||
pub(crate) struct TableGc<F: TableSchema + 'static, R: TableReplication + 'static> {
|
||||
system: Arc<System>,
|
||||
data: Arc<TableData<F, R>>,
|
||||
|
||||
rpc_client: Arc<RpcClient<GcRpc>>,
|
||||
endpoint: Arc<Endpoint<GcRpc, Self>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -38,28 +45,27 @@ enum GcRpc {
|
||||
Ok,
|
||||
}
|
||||
|
||||
impl RpcMessage for GcRpc {}
|
||||
impl Rpc for GcRpc {
|
||||
type Response = Result<GcRpc, Error>;
|
||||
}
|
||||
|
||||
impl<F, R> TableGc<F, R>
|
||||
where
|
||||
F: TableSchema + 'static,
|
||||
R: TableReplication + 'static,
|
||||
{
|
||||
pub(crate) fn launch(
|
||||
system: Arc<System>,
|
||||
data: Arc<TableData<F, R>>,
|
||||
rpc_server: &mut RpcServer,
|
||||
) -> Arc<Self> {
|
||||
let rpc_path = format!("table_{}/gc", data.name);
|
||||
let rpc_client = system.rpc_client::<GcRpc>(&rpc_path);
|
||||
pub(crate) fn launch(system: Arc<System>, data: Arc<TableData<F, R>>) -> Arc<Self> {
|
||||
let endpoint = system
|
||||
.netapp
|
||||
.endpoint(format!("garage_table/gc.rs/Rpc:{}", data.name));
|
||||
|
||||
let gc = Arc::new(Self {
|
||||
system: system.clone(),
|
||||
data: data.clone(),
|
||||
rpc_client,
|
||||
endpoint,
|
||||
});
|
||||
|
||||
gc.register_handler(rpc_server, rpc_path);
|
||||
gc.endpoint.set_handler(gc.clone());
|
||||
|
||||
let gc1 = gc.clone();
|
||||
system.background.spawn_worker(
|
||||
@@ -73,63 +79,100 @@ where
|
||||
async fn gc_loop(self: Arc<Self>, mut must_exit: watch::Receiver<bool>) {
|
||||
while !*must_exit.borrow() {
|
||||
match self.gc_loop_iter().await {
|
||||
Ok(true) => {
|
||||
Ok(None) => {
|
||||
// Stuff was done, loop immediately
|
||||
continue;
|
||||
}
|
||||
Ok(false) => {
|
||||
// Nothing was done, sleep for some time (below)
|
||||
Ok(Some(wait_delay)) => {
|
||||
// Nothing was done, wait specified delay.
|
||||
select! {
|
||||
_ = tokio::time::sleep(wait_delay).fuse() => {},
|
||||
_ = must_exit.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("({}) Error doing GC: {}", self.data.name, e);
|
||||
}
|
||||
}
|
||||
select! {
|
||||
_ = tokio::time::sleep(Duration::from_secs(10)).fuse() => {},
|
||||
_ = must_exit.changed().fuse() => {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn gc_loop_iter(&self) -> Result<bool, Error> {
|
||||
async fn gc_loop_iter(&self) -> Result<Option<Duration>, Error> {
|
||||
let now = now_msec();
|
||||
|
||||
let mut entries = vec![];
|
||||
let mut excluded = vec![];
|
||||
|
||||
for item in self.data.gc_todo.iter() {
|
||||
let (k, vhash) = item?;
|
||||
// List entries in the GC todo list
|
||||
// These entries are put there when a tombstone is inserted in the table
|
||||
// (see update_entry in data.rs)
|
||||
for entry_kv in self.data.gc_todo.iter() {
|
||||
let (k, vhash) = entry_kv?;
|
||||
let mut todo_entry = GcTodoEntry::parse(&k, &vhash);
|
||||
|
||||
if todo_entry.deletion_time() > now {
|
||||
if entries.is_empty() && excluded.is_empty() {
|
||||
// If the earliest entry in the todo list shouldn't yet be processed,
|
||||
// return a duration to wait in the loop
|
||||
return Ok(Some(Duration::from_millis(
|
||||
todo_entry.deletion_time() - now,
|
||||
)));
|
||||
} else {
|
||||
// Otherwise we have some entries to process, do a normal iteration.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let vhash = Hash::try_from(&vhash[..]).unwrap();
|
||||
|
||||
let v_opt = self
|
||||
// Check if the tombstone is still the current value of the entry.
|
||||
// If not, we don't actually want to GC it, and we will remove it
|
||||
// from the gc_todo table later (below).
|
||||
todo_entry.value = self
|
||||
.data
|
||||
.store
|
||||
.get(&k[..])?
|
||||
.filter(|v| blake2sum(&v[..]) == vhash);
|
||||
.filter(|v| blake2sum(&v[..]) == vhash)
|
||||
.map(|v| v.to_vec());
|
||||
|
||||
if let Some(v) = v_opt {
|
||||
entries.push((ByteBuf::from(k.to_vec()), vhash, ByteBuf::from(v.to_vec())));
|
||||
if todo_entry.value.is_some() {
|
||||
entries.push(todo_entry);
|
||||
if entries.len() >= TABLE_GC_BATCH_SIZE {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
excluded.push((k, vhash));
|
||||
excluded.push(todo_entry);
|
||||
}
|
||||
}
|
||||
|
||||
for (k, vhash) in excluded {
|
||||
self.todo_remove_if_equal(&k[..], vhash)?;
|
||||
// Remove from gc_todo entries for tombstones where we have
|
||||
// detected that the current value has changed and
|
||||
// is no longer a tombstone.
|
||||
for entry in excluded {
|
||||
entry.remove_if_equal(&self.data.gc_todo)?;
|
||||
}
|
||||
|
||||
// Remaining in `entries` is the list of entries we want to GC,
|
||||
// and for which they are still currently tombstones in the table.
|
||||
|
||||
if entries.is_empty() {
|
||||
// Nothing to do in this iteration
|
||||
return Ok(false);
|
||||
// Nothing to do in this iteration (no entries present)
|
||||
// Wait for a default delay of 60 seconds
|
||||
return Ok(Some(Duration::from_secs(60)));
|
||||
}
|
||||
|
||||
debug!("({}) GC: doing {} items", self.data.name, entries.len());
|
||||
|
||||
// Split entries to GC by the set of nodes on which they are stored.
|
||||
// Here we call them partitions but they are not exactly
|
||||
// the same as partitions as defined in the ring: those partitions
|
||||
// are defined by the first 8 bits of the hash, but two of these
|
||||
// partitions can be stored on the same set of nodes.
|
||||
// Here we detect when entries are stored on the same set of nodes:
|
||||
// even if they are not in the same 8-bit partition, we can still
|
||||
// handle them together.
|
||||
let mut partitions = HashMap::new();
|
||||
for (k, vhash, v) in entries {
|
||||
let pkh = Hash::try_from(&k[..32]).unwrap();
|
||||
for entry in entries {
|
||||
let pkh = Hash::try_from(&entry.key[..32]).unwrap();
|
||||
let mut nodes = self.data.replication.write_nodes(&pkh);
|
||||
nodes.retain(|x| *x != self.system.id);
|
||||
nodes.sort();
|
||||
@@ -137,9 +180,12 @@ where
|
||||
if !partitions.contains_key(&nodes) {
|
||||
partitions.insert(nodes.clone(), vec![]);
|
||||
}
|
||||
partitions.get_mut(&nodes).unwrap().push((k, vhash, v));
|
||||
partitions.get_mut(&nodes).unwrap().push(entry);
|
||||
}
|
||||
|
||||
// For each set of nodes that contains some items,
|
||||
// ensure they are aware of the tombstone status, and once they
|
||||
// are, instruct them to delete the entries.
|
||||
let resps = join_all(
|
||||
partitions
|
||||
.into_iter()
|
||||
@@ -147,6 +193,8 @@ where
|
||||
)
|
||||
.await;
|
||||
|
||||
// Collect errors and return a single error value even if several
|
||||
// errors occurred.
|
||||
let mut errs = vec![];
|
||||
for resp in resps {
|
||||
if let Err(e) = resp {
|
||||
@@ -155,7 +203,7 @@ where
|
||||
}
|
||||
|
||||
if errs.is_empty() {
|
||||
Ok(true)
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(Error::Message(
|
||||
errs.into_iter()
|
||||
@@ -163,78 +211,98 @@ where
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "),
|
||||
))
|
||||
.err_context("in try_send_and_delete in table GC:")
|
||||
}
|
||||
}
|
||||
|
||||
async fn try_send_and_delete(
|
||||
&self,
|
||||
nodes: Vec<Uuid>,
|
||||
items: Vec<(ByteBuf, Hash, ByteBuf)>,
|
||||
mut items: Vec<GcTodoEntry>,
|
||||
) -> Result<(), Error> {
|
||||
let n_items = items.len();
|
||||
|
||||
// Strategy: we first send all of the values to the remote nodes,
|
||||
// to ensure that they are aware of the tombstone state,
|
||||
// and that the previous state was correctly overwritten
|
||||
// (if they have a newer state that overrides the tombstone, that's fine).
|
||||
// Second, once everyone is at least at the tombstone state,
|
||||
// we instruct everyone to delete the tombstone IF that is still their current state.
|
||||
// If they are now at a different state, it means that that state overrides the
|
||||
// tombstone in the CRDT lattice, and it will be propagated back to us at some point
|
||||
// (either just a regular update that hasn't reached us yet, or later when the
|
||||
// table is synced).
|
||||
|
||||
// Here, we store in updates all of the tombstones to send for step 1,
|
||||
// and in deletes the list of keys and hashes of value for step 2.
|
||||
let mut updates = vec![];
|
||||
let mut deletes = vec![];
|
||||
for (k, vhash, v) in items {
|
||||
updates.push(v);
|
||||
deletes.push((k, vhash));
|
||||
for item in items.iter_mut() {
|
||||
updates.push(ByteBuf::from(item.value.take().unwrap()));
|
||||
deletes.push((ByteBuf::from(item.key.clone()), item.value_hash));
|
||||
}
|
||||
|
||||
self.rpc_client
|
||||
// Step 1: ensure everyone is at least at tombstone in CRDT lattice
|
||||
// Here the quorum is nodes.len(): we cannot tolerate even a single failure,
|
||||
// otherwise old values before the tombstone might come back in the data.
|
||||
// GC'ing is not a critical function of the system, so it's not a big
|
||||
// deal if we can't do it right now.
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
&nodes[..],
|
||||
GcRpc::Update(updates),
|
||||
RequestStrategy::with_quorum(nodes.len()).with_timeout(TABLE_GC_RPC_TIMEOUT),
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_quorum(nodes.len())
|
||||
.with_timeout(TABLE_GC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.err_context("GC: send tombstones")?;
|
||||
|
||||
info!(
|
||||
"({}) GC: {} items successfully pushed, will try to delete.",
|
||||
self.data.name, n_items
|
||||
);
|
||||
|
||||
self.rpc_client
|
||||
// Step 2: delete tombstones everywhere.
|
||||
// Here we also fail if even a single node returns a failure:
|
||||
// it means that the garbage collection wasn't completed and has
|
||||
// to be retried later.
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
&nodes[..],
|
||||
GcRpc::DeleteIfEqualHash(deletes.clone()),
|
||||
RequestStrategy::with_quorum(nodes.len()).with_timeout(TABLE_GC_RPC_TIMEOUT),
|
||||
GcRpc::DeleteIfEqualHash(deletes),
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_quorum(nodes.len())
|
||||
.with_timeout(TABLE_GC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.err_context("GC: remote delete tombstones")?;
|
||||
|
||||
for (k, vhash) in deletes {
|
||||
self.data.delete_if_equal_hash(&k[..], vhash)?;
|
||||
self.todo_remove_if_equal(&k[..], vhash)?;
|
||||
// GC has been successfull for all of these entries.
|
||||
// We now remove them all from our local table and from the GC todo list.
|
||||
for item in items {
|
||||
self.data
|
||||
.delete_if_equal_hash(&item.key[..], item.value_hash)
|
||||
.err_context("GC: local delete tombstones")?;
|
||||
item.remove_if_equal(&self.data.gc_todo)
|
||||
.err_context("GC: remove from todo list after successfull GC")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn todo_remove_if_equal(&self, key: &[u8], vhash: Hash) -> Result<(), Error> {
|
||||
let _ = self
|
||||
.data
|
||||
.gc_todo
|
||||
.compare_and_swap::<_, _, Vec<u8>>(key, Some(vhash), None)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- RPC HANDLER ----
|
||||
|
||||
fn register_handler(self: &Arc<Self>, rpc_server: &mut RpcServer, path: String) {
|
||||
let self2 = self.clone();
|
||||
rpc_server.add_handler::<GcRpc, _, _>(path, move |msg, _addr| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle_rpc(&msg).await }
|
||||
});
|
||||
|
||||
let self2 = self.clone();
|
||||
self.rpc_client
|
||||
.set_local_handler(self.system.id, move |msg| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle_rpc(&msg).await }
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle_rpc(self: &Arc<Self>, message: &GcRpc) -> Result<GcRpc, Error> {
|
||||
#[async_trait]
|
||||
impl<F, R> EndpointHandler<GcRpc> for TableGc<F, R>
|
||||
where
|
||||
F: TableSchema + 'static,
|
||||
R: TableReplication + 'static,
|
||||
{
|
||||
async fn handle(self: &Arc<Self>, message: &GcRpc, _from: NodeID) -> Result<GcRpc, Error> {
|
||||
match message {
|
||||
GcRpc::Update(items) => {
|
||||
self.data.update_many(items)?;
|
||||
@@ -243,7 +311,6 @@ where
|
||||
GcRpc::DeleteIfEqualHash(items) => {
|
||||
for (key, vhash) in items.iter() {
|
||||
self.data.delete_if_equal_hash(&key[..], *vhash)?;
|
||||
self.todo_remove_if_equal(&key[..], *vhash)?;
|
||||
}
|
||||
Ok(GcRpc::Ok)
|
||||
}
|
||||
@@ -251,3 +318,77 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An entry stored in the gc_todo Sled tree associated with the table
|
||||
/// Contains helper function for parsing, saving, and removing
|
||||
/// such entry in Sled
|
||||
///
|
||||
/// Format of an entry:
|
||||
/// - key = 8 bytes: timestamp of tombstone
|
||||
/// (used to implement GC delay)
|
||||
/// n bytes: key in the main data table
|
||||
/// - value = hash of the table entry to delete (the tombstone)
|
||||
/// for verification purpose, because we don't want to delete
|
||||
/// things that aren't tombstones
|
||||
pub(crate) struct GcTodoEntry {
|
||||
tombstone_timestamp: u64,
|
||||
key: Vec<u8>,
|
||||
value_hash: Hash,
|
||||
value: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl GcTodoEntry {
|
||||
/// Creates a new GcTodoEntry (not saved in Sled) from its components:
|
||||
/// the key of an entry in the table, and the hash of the associated
|
||||
/// serialized value
|
||||
pub(crate) fn new(key: Vec<u8>, value_hash: Hash) -> Self {
|
||||
Self {
|
||||
tombstone_timestamp: now_msec(),
|
||||
key,
|
||||
value_hash,
|
||||
value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a GcTodoEntry from a (k, v) pair stored in the gc_todo tree
|
||||
pub(crate) fn parse(sled_k: &[u8], sled_v: &[u8]) -> Self {
|
||||
Self {
|
||||
tombstone_timestamp: u64::from_be_bytes(sled_k[0..8].try_into().unwrap()),
|
||||
key: sled_k[8..].to_vec(),
|
||||
value_hash: Hash::try_from(sled_v).unwrap(),
|
||||
value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves the GcTodoEntry in the gc_todo tree
|
||||
pub(crate) fn save(&self, gc_todo_tree: &sled::Tree) -> Result<(), Error> {
|
||||
gc_todo_tree.insert(self.todo_table_key(), self.value_hash.as_slice())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the GcTodoEntry from the gc_todo tree if the
|
||||
/// hash of the serialized value is the same here as in the tree.
|
||||
/// This is usefull to remove a todo entry only under the condition
|
||||
/// that it has not changed since the time it was read, i.e.
|
||||
/// what we have to do is still the same
|
||||
pub(crate) fn remove_if_equal(&self, gc_todo_tree: &sled::Tree) -> Result<(), Error> {
|
||||
let _ = gc_todo_tree.compare_and_swap::<_, _, Vec<u8>>(
|
||||
&self.todo_table_key()[..],
|
||||
Some(self.value_hash),
|
||||
None,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn todo_table_key(&self) -> Vec<u8> {
|
||||
[
|
||||
&u64::to_be_bytes(self.tombstone_timestamp)[..],
|
||||
&self.key[..],
|
||||
]
|
||||
.concat()
|
||||
}
|
||||
|
||||
fn deletion_time(&self) -> u64 {
|
||||
self.tombstone_timestamp + TABLE_GC_DELAY.as_millis() as u64
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -167,7 +167,7 @@ where
|
||||
// Calculate an update to apply to this node
|
||||
// This update is an Option<_>, so that it is None if the update is a no-op
|
||||
// and we can thus skip recalculating and re-storing everything
|
||||
let mutate = match self.read_node_txn(tx, &key)? {
|
||||
let mutate = match self.read_node_txn(tx, key)? {
|
||||
MerkleNode::Empty => new_vhash.map(|vhv| MerkleNode::Leaf(k.to_vec(), vhv)),
|
||||
MerkleNode::Intermediate(mut children) => {
|
||||
let key2 = key.next_key(khash);
|
||||
@@ -270,7 +270,7 @@ where
|
||||
};
|
||||
|
||||
if let Some(new_node) = mutate {
|
||||
let hash = self.put_node_txn(tx, &key, &new_node)?;
|
||||
let hash = self.put_node_txn(tx, key, &new_node)?;
|
||||
Ok(Some(hash))
|
||||
} else {
|
||||
Ok(None)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::system::System;
|
||||
use garage_util::data::*;
|
||||
|
||||
use crate::replication::*;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use garage_rpc::ring::*;
|
||||
|
||||
use garage_util::data::*;
|
||||
|
||||
/// Trait to describe how a table shall be replicated
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::system::System;
|
||||
use garage_util::data::*;
|
||||
|
||||
use crate::replication::*;
|
||||
@@ -27,7 +27,7 @@ pub struct TableShardedReplication {
|
||||
impl TableReplication for TableShardedReplication {
|
||||
fn read_nodes(&self, hash: &Hash) -> Vec<Uuid> {
|
||||
let ring = self.system.ring.borrow();
|
||||
ring.get_nodes(&hash, self.replication_factor)
|
||||
ring.get_nodes(hash, self.replication_factor)
|
||||
}
|
||||
fn read_quorum(&self) -> usize {
|
||||
self.read_quorum
|
||||
@@ -35,7 +35,7 @@ impl TableReplication for TableShardedReplication {
|
||||
|
||||
fn write_nodes(&self, hash: &Hash) -> Vec<Uuid> {
|
||||
let ring = self.system.ring.borrow();
|
||||
ring.get_nodes(&hash, self.replication_factor)
|
||||
ring.get_nodes(hash, self.replication_factor)
|
||||
}
|
||||
fn write_quorum(&self) -> usize {
|
||||
self.write_quorum
|
||||
|
||||
+53
-38
@@ -2,6 +2,7 @@ use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::select;
|
||||
use futures_util::future::*;
|
||||
use futures_util::stream::*;
|
||||
@@ -13,10 +14,9 @@ use tokio::sync::{mpsc, watch};
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::rpc_client::*;
|
||||
use garage_rpc::rpc_server::*;
|
||||
use garage_rpc::system::System;
|
||||
use garage_rpc::*;
|
||||
|
||||
use crate::data::*;
|
||||
use crate::merkle::*;
|
||||
@@ -28,13 +28,13 @@ const TABLE_SYNC_RPC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
// Do anti-entropy every 10 minutes
|
||||
const ANTI_ENTROPY_INTERVAL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
pub struct TableSyncer<F: TableSchema, R: TableReplication> {
|
||||
pub struct TableSyncer<F: TableSchema + 'static, R: TableReplication + 'static> {
|
||||
system: Arc<System>,
|
||||
data: Arc<TableData<F, R>>,
|
||||
merkle: Arc<MerkleUpdater<F, R>>,
|
||||
|
||||
todo: Mutex<SyncTodo>,
|
||||
rpc_client: Arc<RpcClient<SyncRpc>>,
|
||||
endpoint: Arc<Endpoint<SyncRpc, Self>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -47,7 +47,9 @@ pub(crate) enum SyncRpc {
|
||||
Ok,
|
||||
}
|
||||
|
||||
impl RpcMessage for SyncRpc {}
|
||||
impl Rpc for SyncRpc {
|
||||
type Response = Result<SyncRpc, Error>;
|
||||
}
|
||||
|
||||
struct SyncTodo {
|
||||
todo: Vec<TodoPartition>,
|
||||
@@ -72,10 +74,10 @@ where
|
||||
system: Arc<System>,
|
||||
data: Arc<TableData<F, R>>,
|
||||
merkle: Arc<MerkleUpdater<F, R>>,
|
||||
rpc_server: &mut RpcServer,
|
||||
) -> Arc<Self> {
|
||||
let rpc_path = format!("table_{}/sync", data.name);
|
||||
let rpc_client = system.rpc_client::<SyncRpc>(&rpc_path);
|
||||
let endpoint = system
|
||||
.netapp
|
||||
.endpoint(format!("garage_table/sync.rs/Rpc:{}", data.name));
|
||||
|
||||
let todo = SyncTodo { todo: vec![] };
|
||||
|
||||
@@ -84,10 +86,10 @@ where
|
||||
data: data.clone(),
|
||||
merkle,
|
||||
todo: Mutex::new(todo),
|
||||
rpc_client,
|
||||
endpoint,
|
||||
});
|
||||
|
||||
syncer.register_handler(rpc_server, rpc_path);
|
||||
syncer.endpoint.set_handler(syncer.clone());
|
||||
|
||||
let (busy_tx, busy_rx) = mpsc::unbounded_channel();
|
||||
|
||||
@@ -112,21 +114,6 @@ where
|
||||
syncer
|
||||
}
|
||||
|
||||
fn register_handler(self: &Arc<Self>, rpc_server: &mut RpcServer, path: String) {
|
||||
let self2 = self.clone();
|
||||
rpc_server.add_handler::<SyncRpc, _, _>(path, move |msg, _addr| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle_rpc(&msg).await }
|
||||
});
|
||||
|
||||
let self2 = self.clone();
|
||||
self.rpc_client
|
||||
.set_local_handler(self.system.id, move |msg| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle_rpc(&msg).await }
|
||||
});
|
||||
}
|
||||
|
||||
async fn watcher_task(
|
||||
self: Arc<Self>,
|
||||
mut must_exit: watch::Receiver<bool>,
|
||||
@@ -279,7 +266,7 @@ where
|
||||
let nodes = self
|
||||
.data
|
||||
.replication
|
||||
.write_nodes(&begin)
|
||||
.write_nodes(begin)
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
if nodes.contains(&self.system.id) {
|
||||
@@ -321,11 +308,15 @@ where
|
||||
) -> Result<(), Error> {
|
||||
let values = items.iter().map(|(_k, v)| v.clone()).collect::<Vec<_>>();
|
||||
|
||||
self.rpc_client
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
nodes,
|
||||
SyncRpc::Items(values),
|
||||
RequestStrategy::with_quorum(nodes.len()).with_timeout(TABLE_SYNC_RPC_TIMEOUT),
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_quorum(nodes.len())
|
||||
.with_timeout(TABLE_SYNC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -378,11 +369,14 @@ where
|
||||
// Check if they have the same root checksum
|
||||
// If so, do nothing.
|
||||
let root_resp = self
|
||||
.rpc_client
|
||||
.system
|
||||
.rpc
|
||||
.call(
|
||||
&self.endpoint,
|
||||
who,
|
||||
SyncRpc::RootCkHash(partition.partition, root_ck_hash),
|
||||
TABLE_SYNC_RPC_TIMEOUT,
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_timeout(TABLE_SYNC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -430,8 +424,15 @@ where
|
||||
// Get Merkle node for this tree position at remote node
|
||||
// and compare it with local node
|
||||
let remote_node = match self
|
||||
.rpc_client
|
||||
.call(who, SyncRpc::GetNode(key.clone()), TABLE_SYNC_RPC_TIMEOUT)
|
||||
.system
|
||||
.rpc
|
||||
.call(
|
||||
&self.endpoint,
|
||||
who,
|
||||
SyncRpc::GetNode(key.clone()),
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_timeout(TABLE_SYNC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?
|
||||
{
|
||||
SyncRpc::Node(_, node) => node,
|
||||
@@ -492,8 +493,15 @@ where
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let rpc_resp = self
|
||||
.rpc_client
|
||||
.call(who, SyncRpc::Items(values), TABLE_SYNC_RPC_TIMEOUT)
|
||||
.system
|
||||
.rpc
|
||||
.call(
|
||||
&self.endpoint,
|
||||
who,
|
||||
SyncRpc::Items(values),
|
||||
RequestStrategy::with_priority(PRIO_BACKGROUND)
|
||||
.with_timeout(TABLE_SYNC_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
if let SyncRpc::Ok = rpc_resp {
|
||||
Ok(())
|
||||
@@ -504,10 +512,17 @@ where
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ======= SYNCHRONIZATION PROCEDURE -- RECEIVER SIDE ======
|
||||
// ======= SYNCHRONIZATION PROCEDURE -- RECEIVER SIDE ======
|
||||
|
||||
async fn handle_rpc(self: &Arc<Self>, message: &SyncRpc) -> Result<SyncRpc, Error> {
|
||||
#[async_trait]
|
||||
impl<F, R> EndpointHandler<SyncRpc> for TableSyncer<F, R>
|
||||
where
|
||||
F: TableSchema + 'static,
|
||||
R: TableReplication + 'static,
|
||||
{
|
||||
async fn handle(self: &Arc<Self>, message: &SyncRpc, _from: NodeID) -> Result<SyncRpc, Error> {
|
||||
match message {
|
||||
SyncRpc::RootCkHash(range, h) => {
|
||||
let (_root_ck_key, root_ck) = self.get_root_ck(*range)?;
|
||||
@@ -515,7 +530,7 @@ where
|
||||
Ok(SyncRpc::RootCkDifferent(hash != *h))
|
||||
}
|
||||
SyncRpc::GetNode(k) => {
|
||||
let node = self.merkle.read_node(&k)?;
|
||||
let node = self.merkle.read_node(k)?;
|
||||
Ok(SyncRpc::Node(k.clone(), node))
|
||||
}
|
||||
SyncRpc::Items(items) => {
|
||||
|
||||
+58
-45
@@ -2,6 +2,7 @@ use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use futures::stream::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_bytes::ByteBuf;
|
||||
@@ -9,9 +10,8 @@ use serde_bytes::ByteBuf;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::Error;
|
||||
|
||||
use garage_rpc::membership::System;
|
||||
use garage_rpc::rpc_client::*;
|
||||
use garage_rpc::rpc_server::*;
|
||||
use garage_rpc::system::System;
|
||||
use garage_rpc::*;
|
||||
|
||||
use crate::crdt::Crdt;
|
||||
use crate::data::*;
|
||||
@@ -23,12 +23,12 @@ use crate::sync::*;
|
||||
|
||||
const TABLE_RPC_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
pub struct Table<F: TableSchema, R: TableReplication> {
|
||||
pub struct Table<F: TableSchema + 'static, R: TableReplication + 'static> {
|
||||
pub system: Arc<System>,
|
||||
pub data: Arc<TableData<F, R>>,
|
||||
pub merkle_updater: Arc<MerkleUpdater<F, R>>,
|
||||
pub syncer: Arc<TableSyncer<F, R>>,
|
||||
rpc_client: Arc<RpcClient<TableRpc<F>>>,
|
||||
endpoint: Arc<Endpoint<TableRpc<F>, Self>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -44,7 +44,9 @@ pub(crate) enum TableRpc<F: TableSchema> {
|
||||
Update(Vec<Arc<ByteBuf>>),
|
||||
}
|
||||
|
||||
impl<F: TableSchema> RpcMessage for TableRpc<F> {}
|
||||
impl<F: TableSchema> Rpc for TableRpc<F> {
|
||||
type Response = Result<TableRpc<F>, Error>;
|
||||
}
|
||||
|
||||
impl<F, R> Table<F, R>
|
||||
where
|
||||
@@ -59,32 +61,27 @@ where
|
||||
system: Arc<System>,
|
||||
db: &sled::Db,
|
||||
name: String,
|
||||
rpc_server: &mut RpcServer,
|
||||
) -> Arc<Self> {
|
||||
let rpc_path = format!("table_{}", name);
|
||||
let rpc_client = system.rpc_client::<TableRpc<F>>(&rpc_path);
|
||||
let endpoint = system
|
||||
.netapp
|
||||
.endpoint(format!("garage_table/table.rs/Rpc:{}", name));
|
||||
|
||||
let data = TableData::new(system.clone(), name, instance, replication, db);
|
||||
|
||||
let merkle_updater = MerkleUpdater::launch(&system.background, data.clone());
|
||||
|
||||
let syncer = TableSyncer::launch(
|
||||
system.clone(),
|
||||
data.clone(),
|
||||
merkle_updater.clone(),
|
||||
rpc_server,
|
||||
);
|
||||
TableGc::launch(system.clone(), data.clone(), rpc_server);
|
||||
let syncer = TableSyncer::launch(system.clone(), data.clone(), merkle_updater.clone());
|
||||
TableGc::launch(system.clone(), data.clone());
|
||||
|
||||
let table = Arc::new(Self {
|
||||
system,
|
||||
data,
|
||||
merkle_updater,
|
||||
syncer,
|
||||
rpc_client,
|
||||
endpoint,
|
||||
});
|
||||
|
||||
table.clone().register_handler(rpc_server, rpc_path);
|
||||
table.endpoint.set_handler(table.clone());
|
||||
|
||||
table
|
||||
}
|
||||
@@ -97,11 +94,14 @@ where
|
||||
let e_enc = Arc::new(ByteBuf::from(rmp_to_vec_all_named(e)?));
|
||||
let rpc = TableRpc::<F>::Update(vec![e_enc]);
|
||||
|
||||
self.rpc_client
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
&who[..],
|
||||
rpc,
|
||||
RequestStrategy::with_quorum(self.data.replication.write_quorum())
|
||||
RequestStrategy::with_priority(PRIO_NORMAL)
|
||||
.with_quorum(self.data.replication.write_quorum())
|
||||
.with_timeout(TABLE_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
@@ -123,7 +123,16 @@ where
|
||||
let call_futures = call_list.drain().map(|(node, entries)| async move {
|
||||
let rpc = TableRpc::<F>::Update(entries);
|
||||
|
||||
let resp = self.rpc_client.call(node, rpc, TABLE_RPC_TIMEOUT).await?;
|
||||
let resp = self
|
||||
.system
|
||||
.rpc
|
||||
.call(
|
||||
&self.endpoint,
|
||||
node,
|
||||
rpc,
|
||||
RequestStrategy::with_priority(PRIO_NORMAL).with_timeout(TABLE_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
Ok::<_, Error>((node, resp))
|
||||
});
|
||||
let mut resps = call_futures.collect::<FuturesUnordered<_>>();
|
||||
@@ -152,11 +161,14 @@ where
|
||||
|
||||
let rpc = TableRpc::<F>::ReadEntry(partition_key.clone(), sort_key.clone());
|
||||
let resps = self
|
||||
.rpc_client
|
||||
.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
&who[..],
|
||||
rpc,
|
||||
RequestStrategy::with_quorum(self.data.replication.read_quorum())
|
||||
RequestStrategy::with_priority(PRIO_NORMAL)
|
||||
.with_quorum(self.data.replication.read_quorum())
|
||||
.with_timeout(TABLE_RPC_TIMEOUT)
|
||||
.interrupt_after_quorum(true),
|
||||
)
|
||||
@@ -208,11 +220,14 @@ where
|
||||
let rpc = TableRpc::<F>::ReadRange(partition_key.clone(), begin_sort_key, filter, limit);
|
||||
|
||||
let resps = self
|
||||
.rpc_client
|
||||
.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
&who[..],
|
||||
rpc,
|
||||
RequestStrategy::with_quorum(self.data.replication.read_quorum())
|
||||
RequestStrategy::with_priority(PRIO_NORMAL)
|
||||
.with_quorum(self.data.replication.read_quorum())
|
||||
.with_timeout(TABLE_RPC_TIMEOUT)
|
||||
.interrupt_after_quorum(true),
|
||||
)
|
||||
@@ -263,34 +278,32 @@ where
|
||||
|
||||
async fn repair_on_read(&self, who: &[Uuid], what: F::E) -> Result<(), Error> {
|
||||
let what_enc = Arc::new(ByteBuf::from(rmp_to_vec_all_named(&what)?));
|
||||
self.rpc_client
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
&self.endpoint,
|
||||
who,
|
||||
TableRpc::<F>::Update(vec![what_enc]),
|
||||
RequestStrategy::with_quorum(who.len()).with_timeout(TABLE_RPC_TIMEOUT),
|
||||
RequestStrategy::with_priority(PRIO_NORMAL)
|
||||
.with_quorum(who.len())
|
||||
.with_timeout(TABLE_RPC_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// =============== HANDLERS FOR RPC OPERATIONS (SERVER SIDE) ==============
|
||||
|
||||
fn register_handler(self: Arc<Self>, rpc_server: &mut RpcServer, path: String) {
|
||||
let self2 = self.clone();
|
||||
rpc_server.add_handler::<TableRpc<F>, _, _>(path, move |msg, _addr| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle(&msg).await }
|
||||
});
|
||||
|
||||
let self2 = self.clone();
|
||||
self.rpc_client
|
||||
.set_local_handler(self.system.id, move |msg| {
|
||||
let self2 = self2.clone();
|
||||
async move { self2.handle(&msg).await }
|
||||
});
|
||||
}
|
||||
|
||||
async fn handle(self: &Arc<Self>, msg: &TableRpc<F>) -> Result<TableRpc<F>, Error> {
|
||||
#[async_trait]
|
||||
impl<F, R> EndpointHandler<TableRpc<F>> for Table<F, R>
|
||||
where
|
||||
F: TableSchema + 'static,
|
||||
R: TableReplication + 'static,
|
||||
{
|
||||
async fn handle(
|
||||
self: &Arc<Self>,
|
||||
msg: &TableRpc<F>,
|
||||
_from: NodeID,
|
||||
) -> Result<TableRpc<F>, Error> {
|
||||
match msg {
|
||||
TableRpc::ReadEntry(key, sort_key) => {
|
||||
let value = self.data.read_entry(key, sort_key)?;
|
||||
|
||||
+4
-3
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "garage_util"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
@@ -32,7 +32,8 @@ toml = "0.5"
|
||||
futures = "0.3"
|
||||
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
|
||||
|
||||
#netapp = { version = "0.3.0", git = "https://git.deuxfleurs.fr/lx/netapp" }
|
||||
netapp = "0.3.0"
|
||||
|
||||
http = "0.2"
|
||||
hyper = "0.14"
|
||||
rustls = "0.19"
|
||||
webpki = "0.21"
|
||||
|
||||
+24
-43
@@ -3,8 +3,12 @@ use std::io::Read;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde::de::Error as SerdeError;
|
||||
use serde::{de, Deserialize};
|
||||
|
||||
use netapp::util::parse_and_resolve_peer_addr;
|
||||
use netapp::NodeID;
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
/// Represent the whole configuration
|
||||
@@ -26,24 +30,22 @@ pub struct Config {
|
||||
// (we can add more aliases for this later)
|
||||
pub replication_mode: String,
|
||||
|
||||
/// RPC secret key: 32 bytes hex encoded
|
||||
pub rpc_secret: String,
|
||||
|
||||
/// Address to bind for RPC
|
||||
pub rpc_bind_addr: SocketAddr,
|
||||
/// Public IP address of this node
|
||||
pub rpc_public_addr: Option<SocketAddr>,
|
||||
|
||||
/// Bootstrap peers RPC address
|
||||
#[serde(deserialize_with = "deserialize_vec_addr")]
|
||||
pub bootstrap_peers: Vec<SocketAddr>,
|
||||
/// Consule host to connect to to discover more peers
|
||||
#[serde(deserialize_with = "deserialize_vec_addr", default)]
|
||||
pub bootstrap_peers: Vec<(NodeID, SocketAddr)>,
|
||||
/// Consul host to connect to to discover more peers
|
||||
pub consul_host: Option<String>,
|
||||
/// Consul service name to use
|
||||
pub consul_service_name: Option<String>,
|
||||
|
||||
/// Configuration for RPC TLS
|
||||
pub rpc_tls: Option<TlsConfig>,
|
||||
|
||||
/// Max number of concurrent RPC request
|
||||
#[serde(default = "default_max_concurrent_rpc_requests")]
|
||||
pub max_concurrent_rpc_requests: usize,
|
||||
|
||||
/// Sled cache size, in bytes
|
||||
#[serde(default = "default_sled_cache_capacity")]
|
||||
pub sled_cache_capacity: u64,
|
||||
@@ -59,17 +61,6 @@ pub struct Config {
|
||||
pub s3_web: WebConfig,
|
||||
}
|
||||
|
||||
/// Configuration for RPC TLS
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
pub struct TlsConfig {
|
||||
/// Path to certificate autority used for all nodes
|
||||
pub ca_cert: String,
|
||||
/// Path to public certificate for this node
|
||||
pub node_cert: String,
|
||||
/// Path to private key for this node
|
||||
pub node_key: String,
|
||||
}
|
||||
|
||||
/// Configuration for S3 api
|
||||
#[derive(Deserialize, Debug, Clone)]
|
||||
pub struct ApiConfig {
|
||||
@@ -96,9 +87,6 @@ fn default_sled_cache_capacity() -> u64 {
|
||||
fn default_sled_flush_every_ms() -> u64 {
|
||||
2000
|
||||
}
|
||||
fn default_max_concurrent_rpc_requests() -> usize {
|
||||
12
|
||||
}
|
||||
fn default_block_size() -> usize {
|
||||
1048576
|
||||
}
|
||||
@@ -115,27 +103,20 @@ pub fn read_config(config_file: PathBuf) -> Result<Config, Error> {
|
||||
Ok(toml::from_str(&config)?)
|
||||
}
|
||||
|
||||
fn deserialize_vec_addr<'de, D>(deserializer: D) -> Result<Vec<SocketAddr>, D::Error>
|
||||
fn deserialize_vec_addr<'de, D>(deserializer: D) -> Result<Vec<(NodeID, SocketAddr)>, D::Error>
|
||||
where
|
||||
D: de::Deserializer<'de>,
|
||||
{
|
||||
use std::net::ToSocketAddrs;
|
||||
let mut ret = vec![];
|
||||
|
||||
Ok(<Vec<&str>>::deserialize(deserializer)?
|
||||
.iter()
|
||||
.filter_map(|&name| {
|
||||
name.to_socket_addrs()
|
||||
.map(|iter| (name, iter))
|
||||
.map_err(|_| warn!("Error resolving \"{}\"", name))
|
||||
.ok()
|
||||
})
|
||||
.map(|(name, iter)| {
|
||||
let v = iter.collect::<Vec<_>>();
|
||||
if v.is_empty() {
|
||||
warn!("Error resolving \"{}\"", name)
|
||||
}
|
||||
v
|
||||
})
|
||||
.flatten()
|
||||
.collect())
|
||||
for peer in <Vec<&str>>::deserialize(deserializer)? {
|
||||
let (pubkey, addrs) = parse_and_resolve_peer_addr(peer).ok_or_else(|| {
|
||||
D::Error::custom(format!("Unable to parse or resolve peer: {}", peer))
|
||||
})?;
|
||||
for ip in addrs {
|
||||
ret.push((pubkey, ip));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ret)
|
||||
}
|
||||
|
||||
@@ -87,6 +87,18 @@ impl FixedBytes32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<netapp::NodeID> for FixedBytes32 {
|
||||
fn from(node_id: netapp::NodeID) -> FixedBytes32 {
|
||||
FixedBytes32::try_from(node_id.as_ref()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FixedBytes32> for netapp::NodeID {
|
||||
fn from(bytes: FixedBytes32) -> netapp::NodeID {
|
||||
netapp::NodeID::from_slice(bytes.as_slice()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32 bytes UUID
|
||||
pub type Uuid = FixedBytes32;
|
||||
/// A 256 bit cryptographic hash, can be sha256 or blake2 depending on provenance
|
||||
|
||||
+93
-36
@@ -1,35 +1,13 @@
|
||||
//! Module containing error types used in Garage
|
||||
use err_derive::Error;
|
||||
use hyper::StatusCode;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
|
||||
use err_derive::Error;
|
||||
|
||||
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
use crate::data::*;
|
||||
|
||||
/// RPC related errors
|
||||
#[derive(Debug, Error)]
|
||||
pub enum RpcError {
|
||||
#[error(display = "Node is down: {:?}.", _0)]
|
||||
NodeDown(Uuid),
|
||||
|
||||
#[error(display = "Timeout: {}", _0)]
|
||||
Timeout(#[error(source)] tokio::time::error::Elapsed),
|
||||
|
||||
#[error(display = "HTTP error: {}", _0)]
|
||||
Http(#[error(source)] http::Error),
|
||||
|
||||
#[error(display = "Hyper error: {}", _0)]
|
||||
Hyper(#[error(source)] hyper::Error),
|
||||
|
||||
#[error(display = "Messagepack encode error: {}", _0)]
|
||||
RmpEncode(#[error(source)] rmp_serde::encode::Error),
|
||||
|
||||
#[error(display = "Messagepack decode error: {}", _0)]
|
||||
RmpDecode(#[error(source)] rmp_serde::decode::Error),
|
||||
|
||||
#[error(display = "Too many errors: {:?}", _0)]
|
||||
TooManyErrors(Vec<String>),
|
||||
}
|
||||
|
||||
/// Regroup all Garage errors
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
@@ -45,11 +23,8 @@ pub enum Error {
|
||||
#[error(display = "Invalid HTTP header value: {}", _0)]
|
||||
HttpHeader(#[error(source)] http::header::ToStrError),
|
||||
|
||||
#[error(display = "TLS error: {}", _0)]
|
||||
Tls(#[error(source)] rustls::TLSError),
|
||||
|
||||
#[error(display = "PKI error: {}", _0)]
|
||||
Pki(#[error(source)] webpki::Error),
|
||||
#[error(display = "Netapp error: {}", _0)]
|
||||
Netapp(#[error(source)] netapp::error::Error),
|
||||
|
||||
#[error(display = "Sled error: {}", _0)]
|
||||
Sled(#[error(source)] sled::Error),
|
||||
@@ -66,11 +41,23 @@ pub enum Error {
|
||||
#[error(display = "Tokio join error: {}", _0)]
|
||||
TokioJoin(#[error(source)] tokio::task::JoinError),
|
||||
|
||||
#[error(display = "RPC call error: {}", _0)]
|
||||
Rpc(#[error(source)] RpcError),
|
||||
#[error(display = "Tokio semaphore acquire error: {}", _0)]
|
||||
TokioSemAcquire(#[error(source)] tokio::sync::AcquireError),
|
||||
|
||||
#[error(display = "Remote error: {} (status code {})", _0, _1)]
|
||||
RemoteError(String, StatusCode),
|
||||
#[error(display = "Remote error: {}", _0)]
|
||||
RemoteError(String),
|
||||
|
||||
#[error(display = "Timeout")]
|
||||
Timeout,
|
||||
|
||||
#[error(
|
||||
display = "Could not reach quorum of {}. {} of {} request succeeded, others returned errors: {:?}",
|
||||
_0,
|
||||
_1,
|
||||
_2,
|
||||
_3
|
||||
)]
|
||||
Quorum(usize, usize, usize, Vec<String>),
|
||||
|
||||
#[error(display = "Bad RPC: {}", _0)]
|
||||
BadRpc(String),
|
||||
@@ -102,3 +89,73 @@ impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
|
||||
Error::Message("MPSC send error".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a str> for Error {
|
||||
fn from(v: &'a str) -> Error {
|
||||
Error::Message(v.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Error {
|
||||
fn from(v: String) -> Error {
|
||||
Error::Message(v)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ErrorContext<T, E> {
|
||||
fn err_context<C: std::borrow::Borrow<str>>(self, ctx: C) -> Result<T, Error>;
|
||||
}
|
||||
|
||||
impl<T, E> ErrorContext<T, E> for Result<T, E>
|
||||
where
|
||||
E: std::fmt::Display,
|
||||
{
|
||||
#[inline]
|
||||
fn err_context<C: std::borrow::Borrow<str>>(self, ctx: C) -> Result<T, Error> {
|
||||
match self {
|
||||
Ok(x) => Ok(x),
|
||||
Err(e) => Err(Error::Message(format!("{}\n{}", ctx.borrow(), e))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Custom serialization for our error type, for use in RPC.
|
||||
// Errors are serialized as a string of their Display representation.
|
||||
// Upon deserialization, they all become a RemoteError with the
|
||||
// given representation.
|
||||
|
||||
impl Serialize for Error {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.serialize_str(&format!("{}", self))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Error {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_string(ErrorVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct ErrorVisitor;
|
||||
|
||||
impl<'de> Visitor<'de> for ErrorVisitor {
|
||||
type Value = Error;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(formatter, "a string that represents an error value")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, error_msg: &str) -> Result<Self::Value, E> {
|
||||
Ok(Error::RemoteError(error_msg.to_string()))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, error_msg: String) -> Result<Self::Value, E> {
|
||||
Ok(Error::RemoteError(error_msg))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,3 +9,5 @@ pub mod data;
|
||||
pub mod error;
|
||||
pub mod persister;
|
||||
pub mod time;
|
||||
pub mod token_bucket;
|
||||
pub mod tranquilizer;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user