mirror of
https://github.com/deuxfleurs-org/garage.git
synced 2026-08-13 23:56:53 +00:00
Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4b369347c0 | |||
| 224c89ad6e | |||
| 7c2037ba87 | |||
| c4ac8835d3 | |||
| ccce75bc25 | |||
| 7f26ed55cd | |||
| 8811bb08e6 | |||
| 85b2e4ca29 | |||
| c94406f428 | |||
| 53888995bd | |||
| f0893b904d | |||
| 396fe4c702 | |||
| 02158ee666 | |||
| 57df9c6e2d | |||
| 9c58ec28d3 | |||
| cdeb5b4dbb | |||
| 100aad8bf4 | |||
| 80a87929b0 | |||
| 76d21be1b9 | |||
| 1928f59d54 | |||
| 323514be15 | |||
| ad8d5139cf | |||
| 08b1e8a7ea | |||
| ad7ab31411 | |||
| 74a7a550eb | |||
| cc255d46cd | |||
| 8e25a37f0e | |||
| e342db19aa | |||
| f3405b6378 | |||
| 860ccf2811 | |||
| 9df7559446 | |||
| a97467075d | |||
| 9d7535c3f5 | |||
| da6efb4b23 |
Generated
+9
-8
@@ -379,7 +379,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes 1.1.0",
|
||||
@@ -408,7 +408,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_api"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes 1.1.0",
|
||||
@@ -426,6 +426,7 @@ dependencies = [
|
||||
"http-range",
|
||||
"httpdate 0.3.2",
|
||||
"hyper",
|
||||
"idna",
|
||||
"log",
|
||||
"md-5",
|
||||
"percent-encoding",
|
||||
@@ -439,7 +440,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_model"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -461,7 +462,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_rpc"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
@@ -478,6 +479,7 @@ dependencies = [
|
||||
"rand",
|
||||
"rmp-serde 0.15.5",
|
||||
"serde",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
@@ -485,7 +487,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_table"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"bytes 1.1.0",
|
||||
@@ -505,7 +507,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_util"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"blake2",
|
||||
"chrono",
|
||||
@@ -529,7 +531,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "garage_web"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"err-derive 0.3.0",
|
||||
"futures",
|
||||
@@ -539,7 +541,6 @@ dependencies = [
|
||||
"garage_util",
|
||||
"http",
|
||||
"hyper",
|
||||
"idna",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
@@ -40,13 +40,13 @@ in
|
||||
{
|
||||
cargo2nixVersion = "0.9.0";
|
||||
workspace = {
|
||||
garage_util = rustPackages.unknown.garage_util."0.4.0";
|
||||
garage_rpc = rustPackages.unknown.garage_rpc."0.4.0";
|
||||
garage_table = rustPackages.unknown.garage_table."0.4.0";
|
||||
garage_model = rustPackages.unknown.garage_model."0.4.0";
|
||||
garage_api = rustPackages.unknown.garage_api."0.4.0";
|
||||
garage_web = rustPackages.unknown.garage_web."0.4.0";
|
||||
garage = rustPackages.unknown.garage."0.4.0";
|
||||
garage_util = rustPackages.unknown.garage_util."0.5.0";
|
||||
garage_rpc = rustPackages.unknown.garage_rpc."0.5.0";
|
||||
garage_table = rustPackages.unknown.garage_table."0.5.0";
|
||||
garage_model = rustPackages.unknown.garage_model."0.5.0";
|
||||
garage_api = rustPackages.unknown.garage_api."0.5.0";
|
||||
garage_web = rustPackages.unknown.garage_web."0.5.0";
|
||||
garage = rustPackages.unknown.garage."0.5.0";
|
||||
};
|
||||
"registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.18" = overridableMkRustCrate (profileName: rec {
|
||||
name = "aho-corasick";
|
||||
@@ -246,7 +246,7 @@ in
|
||||
registry = "registry+https://github.com/rust-lang/crates.io-index";
|
||||
src = fetchCratesIo { inherit name version; sha256 = "95059428f66df56b63431fdb4e1947ed2190586af5c5a8a8b71122bdf5a7f469"; };
|
||||
dependencies = {
|
||||
${ if hostPlatform.config == "aarch64-apple-darwin" || hostPlatform.parsed.cpu.name == "aarch64" && hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.103" { inherit profileName; };
|
||||
${ if hostPlatform.parsed.cpu.name == "aarch64" && hostPlatform.parsed.kernel.name == "linux" || hostPlatform.config == "aarch64-apple-darwin" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.103" { inherit profileName; };
|
||||
};
|
||||
});
|
||||
|
||||
@@ -606,9 +606,9 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/garage");
|
||||
dependencies = {
|
||||
@@ -616,12 +616,12 @@ in
|
||||
bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.1.0" { inherit profileName; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.17" { inherit profileName; };
|
||||
garage_api = rustPackages."unknown".garage_api."0.4.0" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.4.0" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.4.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_web = rustPackages."unknown".garage_web."0.4.0" { inherit profileName; };
|
||||
garage_api = rustPackages."unknown".garage_api."0.5.0" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.5.0" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.5.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.5.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
garage_web = rustPackages."unknown".garage_web."0.5.0" { inherit profileName; };
|
||||
git_version = rustPackages."registry+https://github.com/rust-lang/crates.io-index".git-version."0.3.5" { inherit profileName; };
|
||||
hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
|
||||
sodiumoxide = rustPackages."registry+https://github.com/rust-lang/crates.io-index".kuska-sodiumoxide."0.2.5-0" { inherit profileName; };
|
||||
@@ -638,9 +638,9 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_api."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_api."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_api";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/api");
|
||||
dependencies = {
|
||||
@@ -651,15 +651,16 @@ in
|
||||
err_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".err-derive."0.3.0" { profileName = "__noProfile"; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.17" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.4.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.5.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.5.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
|
||||
hmac = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hmac."0.10.1" { inherit profileName; };
|
||||
http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.5" { inherit profileName; };
|
||||
http_range = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http-range."0.1.4" { inherit profileName; };
|
||||
httpdate = rustPackages."registry+https://github.com/rust-lang/crates.io-index".httpdate."0.3.2" { inherit profileName; };
|
||||
hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.13" { inherit profileName; };
|
||||
idna = rustPackages."registry+https://github.com/rust-lang/crates.io-index".idna."0.2.3" { inherit profileName; };
|
||||
log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.14" { inherit profileName; };
|
||||
md5 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".md-5."0.9.1" { inherit profileName; };
|
||||
percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.1.0" { inherit profileName; };
|
||||
@@ -672,9 +673,9 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_model."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_model."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_model";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/model");
|
||||
dependencies = {
|
||||
@@ -682,9 +683,9 @@ in
|
||||
async_trait = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.51" { profileName = "__noProfile"; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.17" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.4.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.5.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.5.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
|
||||
log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.14" { inherit profileName; };
|
||||
netapp = rustPackages."registry+https://github.com/rust-lang/crates.io-index".netapp."0.3.0" { inherit profileName; };
|
||||
@@ -697,9 +698,9 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_rpc."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_rpc."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_rpc";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/rpc");
|
||||
dependencies = {
|
||||
@@ -708,7 +709,7 @@ in
|
||||
bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.1.0" { inherit profileName; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.17" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
gethostname = rustPackages."registry+https://github.com/rust-lang/crates.io-index".gethostname."0.2.1" { inherit profileName; };
|
||||
hex = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" { inherit profileName; };
|
||||
hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.13" { inherit profileName; };
|
||||
@@ -718,15 +719,16 @@ in
|
||||
rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.4" { inherit profileName; };
|
||||
rmp_serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rmp-serde."0.15.5" { inherit profileName; };
|
||||
serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.130" { inherit profileName; };
|
||||
serde_bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_bytes."0.11.5" { inherit profileName; };
|
||||
serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.68" { inherit profileName; };
|
||||
tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.12.0" { inherit profileName; };
|
||||
tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.7" { inherit profileName; };
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_table."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_table."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_table";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/table");
|
||||
dependencies = {
|
||||
@@ -734,8 +736,8 @@ in
|
||||
bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.1.0" { inherit profileName; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.17" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_rpc = rustPackages."unknown".garage_rpc."0.5.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
hexdump = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hexdump."0.1.1" { inherit profileName; };
|
||||
log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.14" { inherit profileName; };
|
||||
rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.4" { inherit profileName; };
|
||||
@@ -747,9 +749,9 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_util."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_util."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_util";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/util");
|
||||
dependencies = {
|
||||
@@ -774,21 +776,20 @@ in
|
||||
};
|
||||
});
|
||||
|
||||
"unknown".garage_web."0.4.0" = overridableMkRustCrate (profileName: rec {
|
||||
"unknown".garage_web."0.5.0" = overridableMkRustCrate (profileName: rec {
|
||||
name = "garage_web";
|
||||
version = "0.4.0";
|
||||
version = "0.5.0";
|
||||
registry = "unknown";
|
||||
src = fetchCrateLocal (workspaceSrc + "/src/web");
|
||||
dependencies = {
|
||||
err_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".err-derive."0.3.0" { profileName = "__noProfile"; };
|
||||
futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures."0.3.17" { inherit profileName; };
|
||||
garage_api = rustPackages."unknown".garage_api."0.4.0" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.4.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.4.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.4.0" { inherit profileName; };
|
||||
garage_api = rustPackages."unknown".garage_api."0.5.0" { inherit profileName; };
|
||||
garage_model = rustPackages."unknown".garage_model."0.5.0" { inherit profileName; };
|
||||
garage_table = rustPackages."unknown".garage_table."0.5.0" { inherit profileName; };
|
||||
garage_util = rustPackages."unknown".garage_util."0.5.0" { inherit profileName; };
|
||||
http = rustPackages."registry+https://github.com/rust-lang/crates.io-index".http."0.2.5" { inherit profileName; };
|
||||
hyper = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.13" { inherit profileName; };
|
||||
idna = rustPackages."registry+https://github.com/rust-lang/crates.io-index".idna."0.2.3" { inherit profileName; };
|
||||
log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.14" { inherit profileName; };
|
||||
percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.1.0" { inherit profileName; };
|
||||
};
|
||||
|
||||
@@ -3,10 +3,18 @@ Garage [
|
||||
|
||||
Our main use case is to provide a distributed storage layer for small-scale self hosted services such as [Deuxfleurs](https://deuxfleurs.fr).
|
||||
|
||||
**[Go to the documentation](https://garagehq.deuxfleurs.fr)**
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
Testing
|
||||
-------
|
||||
|
||||
How are we going to test that our replication method works correctly?
|
||||
We will have to introduce lots of dummy data and then add/remove nodes many times.
|
||||
|
||||
|
||||
Attaining S3 compatibility
|
||||
--------------------------
|
||||
|
||||
- test multipart uploads
|
||||
- get ranges
|
||||
|
||||
- fix sync not working in some cases ? (when starting from empty?)
|
||||
|
||||
- api_server following the S3 semantics for head/get/put/list/delete: verify more that it works as intended
|
||||
- PUT requests: verify content-md5 if provided
|
||||
- possibly other necessary endpoints ?
|
||||
|
||||
|
||||
Lower priority
|
||||
--------------
|
||||
|
||||
- less a priority: hinted handoff
|
||||
- repair: re-propagate block ref table to rc
|
||||
- FIXME in rpc_server when garage shuts down and futures can be interrupted
|
||||
(tokio::spawn should be replaced by a new function background::spawn_joinable)
|
||||
+13
-4
@@ -5,34 +5,43 @@
|
||||
- [Quick start](./quick_start/index.md)
|
||||
|
||||
- [Cookbook](./cookbook/index.md)
|
||||
- [Multi-node deployment](./cookbook/real_world.md)
|
||||
- [Building from source](./cookbook/from_source.md)
|
||||
- [Integration with systemd](./cookbook/systemd.md)
|
||||
- [Configuring a gateway node](./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)
|
||||
- [Repositories (Docker, Nix, Git...)](./connect/repositories.md)
|
||||
- [CLI tools (rclone, awscli, mc...)](./connect/cli.md)
|
||||
- [Backups (restic, duplicity...)](./connect/backup.md)
|
||||
- [Your code (PHP, JS, Go...)](./connect/code.md)
|
||||
- [FUSE (s3fs, goofys, s3backer...)](./connect/fs.md)
|
||||
|
||||
|
||||
- [Reference Manual](./reference_manual/index.md)
|
||||
- [Garage configuration file](./reference_manual/configuration.md)
|
||||
- [Cluster layout management](./reference_manual/layout.md)
|
||||
- [Garage CLI](./reference_manual/cli.md)
|
||||
- [S3 compatibility status](./reference_manual/s3_compatibility.md)
|
||||
|
||||
- [Design](./design/index.md)
|
||||
- [Related Work](./design/related_work.md)
|
||||
- [Goals and use Cases](./design/goals.md)
|
||||
- [Related work](./design/related_work.md)
|
||||
- [Internals](./design/internals.md)
|
||||
|
||||
- [Development](./development/index.md)
|
||||
- [Setup your environment](./development/devenv.md)
|
||||
- [Development scripts](./development/scripts.md)
|
||||
- [Release process](./development/release_process.md)
|
||||
- [Miscellaneous notes](./development/miscellaneous_notes.md)
|
||||
|
||||
- [Working Documents](./working_documents/index.md)
|
||||
- [Load Balancing Data](./working_documents/load_balancing.md)
|
||||
- [S3 compatibility target](./working_documents/compatibility_target.md)
|
||||
- [Load balancing data](./working_documents/load_balancing.md)
|
||||
- [Migrating from 0.3 to 0.4](./working_documents/migration_04.md)
|
||||
- [Design draft](./working_documents/design_draft.md)
|
||||
|
||||
+106
-33
@@ -253,35 +253,7 @@ Make sure you (will) have a corresponding DNS entry for them.
|
||||
|
||||
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.
|
||||
For our example, we will use nginx:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
# In production you should use TLS instead of plain HTTP
|
||||
listen [::]:80;
|
||||
|
||||
server_name peertube-video.web.garage peertube-playlist.web.garage;
|
||||
|
||||
location / {
|
||||
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 request to Garage
|
||||
# as it does not know how to interpret them.
|
||||
# Instead, we simply answers 200.
|
||||
if ($request_method !~ ^(GET|HEAD)$ ) {
|
||||
return 200;
|
||||
}
|
||||
|
||||
# If your do not have a Garage instance on the reverse proxy, change the URL here.
|
||||
proxy_pass http://127.0.0.1:3902;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
}
|
||||
```
|
||||
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.
|
||||
|
||||
@@ -346,13 +318,114 @@ https://docs.joinmastodon.org/admin/config/#cdn
|
||||
|
||||
## Matrix
|
||||
|
||||
### synapse-s3-storage-provider
|
||||
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.
|
||||
|
||||
https://github.com/matrix-org/synapse-s3-storage-provider
|
||||
### synapse-s3-storage-provider (synapse only)
|
||||
|
||||
### matrix-media-repo
|
||||
Supposing you have a working synapse installation, you can add the module with pip:
|
||||
|
||||
https://github.com/turt2live/matrix-media-repo
|
||||
```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
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# Backups (restic, duplicity...)
|
||||
|
||||
Backups are essential for disaster recovery but they are not trivial to manage.
|
||||
Using Garage as your backup target will enable you to scale your storage as needed while ensuring high availability.
|
||||
|
||||
## Borg Backup
|
||||
|
||||
Borg Backup is very popular among the backup tools but it is not yet compatible with the S3 API.
|
||||
We recommend using any other tool listed in this guide because they are all compatible with the S3 API.
|
||||
If you still want to use Borg, you can use it with `rclone mount`.
|
||||
|
||||
|
||||
|
||||
## Restic
|
||||
|
||||
*External links:* [Restic Documentation > Amazon S3](https://restic.readthedocs.io/en/stable/030_preparing_a_new_repo.html#amazon-s3)
|
||||
|
||||
## Duplicity
|
||||
|
||||
*External links:* [Duplicity > man](https://duplicity.gitlab.io/duplicity-web/vers8/duplicity.1.html) (scroll to "URL Format" and "A note on Amazon S3")
|
||||
|
||||
## Duplicati
|
||||
|
||||
*External links:* [Duplicati Documentation > Storage Providers](https://github.com/kees-z/DuplicatiDocs/blob/master/docs/05-storage-providers.md#s3-compatible)
|
||||
|
||||
## knoxite
|
||||
|
||||
*External links:* [Knoxite Documentation > Storage Backends](https://knoxite.com/docs/storage-backends/#amazon-s3)
|
||||
|
||||
## kopia
|
||||
|
||||
*External links:* [Kopia Documentation > Repositories](https://kopia.io/docs/repositories/#amazon-s3)
|
||||
|
||||
@@ -90,10 +90,10 @@ aws s3 cp s3/my_files/cpuinfo.txt /tmp/cpuinfo.txt
|
||||
|
||||
## `rclone`
|
||||
|
||||
`rclone` can be configured using the interactive assistant invoked using `rclone configure`.
|
||||
`rclone` can be configured using the interactive assistant invoked using `rclone config`.
|
||||
|
||||
You can also configure `rclone` by writing directly its configuration file.
|
||||
Here is a template `rclone.ini` configuration file:
|
||||
Here is a template `rclone.ini` configuration file (mine is located at `~/.config/rclone/rclone.conf`):
|
||||
|
||||
```ini
|
||||
[garage]
|
||||
@@ -109,9 +109,25 @@ acl = private
|
||||
bucket_acl = private
|
||||
```
|
||||
|
||||
## Cyberduck
|
||||
Now you can run:
|
||||
|
||||
TODO
|
||||
```bash
|
||||
# list buckets
|
||||
rclone lsd garage:
|
||||
|
||||
# list objects of a bucket aggregated in directories
|
||||
rclone lsd garage:my-bucket
|
||||
|
||||
# copy from your filesystem to garage
|
||||
echo hello world > /tmp/hello.txt
|
||||
rclone copy /tmp/hello.txt garage:my-bucket/
|
||||
|
||||
# copy from garage to your filesystem
|
||||
rclone copy garage:quentin.divers/hello.txt .
|
||||
|
||||
# see all available subcommands
|
||||
rclone help
|
||||
```
|
||||
|
||||
## `s3cmd`
|
||||
|
||||
@@ -123,5 +139,28 @@ access_key = <access key>
|
||||
secret_key = <secret key>
|
||||
host_base = <endpoint without http(s)://>
|
||||
host_bucket = <same as host_base>
|
||||
use_https = False | True
|
||||
use_https = <False or True>
|
||||
```
|
||||
|
||||
And use it as follow:
|
||||
|
||||
```bash
|
||||
# List buckets
|
||||
s3cmd ls
|
||||
|
||||
# s3cmd objects inside a bucket
|
||||
s3cmd ls s3://my-bucket
|
||||
|
||||
# copy from your filesystem to garage
|
||||
echo hello world > /tmp/hello.txt
|
||||
s3cmd put /tmp/hello.txt s3://my-bucket/
|
||||
|
||||
# copy from garage to your filesystem
|
||||
s3cmd get s3://my-bucket/hello.txt hello.txt
|
||||
```
|
||||
|
||||
## Cyberduck & duck
|
||||
|
||||
TODO
|
||||
|
||||
|
||||
|
||||
@@ -1 +1,79 @@
|
||||
# Your code (PHP, JS, Go...)
|
||||
|
||||
If you are developping a new application, you may want to use Garage to store your user's media.
|
||||
|
||||
The S3 API that Garage uses is a standard REST API, so as long as you can make HTTP requests,
|
||||
you can query it. You can check the [S3 REST API Reference](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Operations_Amazon_Simple_Storage_Service.html) from Amazon to learn more.
|
||||
|
||||
Developping your own wrapper around the REST API is time consuming and complicated.
|
||||
Instead, there are some libraries already avalaible.
|
||||
|
||||
Some of them are maintained by Amazon, some by Minio, others by the community.
|
||||
|
||||
## PHP
|
||||
|
||||
- Amazon aws-sdk-php
|
||||
- [Installation](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_installation.html)
|
||||
- [Reference](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-s3-2006-03-01.html)
|
||||
- [Example](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html)
|
||||
|
||||
## Javascript
|
||||
|
||||
- Minio SDK
|
||||
- [Reference](https://docs.min.io/docs/javascript-client-api-reference.html)
|
||||
|
||||
- Amazon aws-sdk-js
|
||||
- [Installation](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started.html)
|
||||
- [Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html)
|
||||
- [Example](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html)
|
||||
|
||||
## Golang
|
||||
|
||||
- Minio minio-go-sdk
|
||||
- [Reference](https://docs.min.io/docs/golang-client-api-reference.html)
|
||||
|
||||
- Amazon aws-sdk-go-v2
|
||||
- [Installation](https://aws.github.io/aws-sdk-go-v2/docs/getting-started/)
|
||||
- [Reference](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3)
|
||||
- [Example](https://aws.github.io/aws-sdk-go-v2/docs/code-examples/s3/putobject/)
|
||||
|
||||
## Python
|
||||
|
||||
- Minio SDK
|
||||
- [Reference](https://docs.min.io/docs/python-client-api-reference.html)
|
||||
|
||||
- Amazon boto3
|
||||
- [Installation](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)
|
||||
- [Reference](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html)
|
||||
- [Example](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html)
|
||||
|
||||
## Java
|
||||
|
||||
- Minio SDK
|
||||
- [Reference](https://docs.min.io/docs/java-client-api-reference.html)
|
||||
|
||||
- Amazon aws-sdk-java
|
||||
- [Installation](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html)
|
||||
- [Reference](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html)
|
||||
- [Example](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/examples-s3-objects.html)
|
||||
|
||||
## Rust
|
||||
|
||||
- Amazon aws-rust-sdk
|
||||
- [Github](https://github.com/awslabs/aws-sdk-rust)
|
||||
|
||||
## .NET
|
||||
|
||||
- Minio SDK
|
||||
- [Reference](https://docs.min.io/docs/dotnet-client-api-reference.html)
|
||||
|
||||
- Amazon aws-dotnet-sdk
|
||||
|
||||
## C++
|
||||
|
||||
- Amazon aws-cpp-sdk
|
||||
|
||||
## Haskell
|
||||
|
||||
- Minio SDK
|
||||
- [Reference](https://docs.min.io/docs/haskell-client-api-reference.html)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# FUSE (s3fs, goofys, s3backer...)
|
||||
|
||||
**WARNING! Garage is not POSIX compatible.
|
||||
Mounting S3 buckets as filesystems will not provide POSIX compatibility.
|
||||
If you are not careful, you will lose or corrupt your data.**
|
||||
|
||||
Do not use these FUSE filesystems to store any database files (eg. MySQL, Postgresql, Mongo or sqlite),
|
||||
any daemon cache (dovecot, openldap, gitea, etc.),
|
||||
and more generally any software that use locking, advanced filesystems features or make any synchronisation assumption.
|
||||
Ideally, avoid these solutions at all for any serious or production use.
|
||||
|
||||
## rclone mount
|
||||
|
||||
rclone uses the same configuration when used [in CLI](/connect/cli.html) and mount mode.
|
||||
We suppose you have the following entry in your `rclone.ini` (mine is located in `~/.config/rclone/rclone.conf`):
|
||||
|
||||
```toml
|
||||
[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
|
||||
```
|
||||
|
||||
Then you can mount and access any bucket as follow:
|
||||
|
||||
```bash
|
||||
# mount the bucket
|
||||
mkdir /tmp/my-bucket
|
||||
rclone mount --daemon garage:my-bucket /tmp/my-bucket
|
||||
|
||||
# set your working directory to the bucket
|
||||
cd /tmp/my-bucket
|
||||
|
||||
# create a file
|
||||
echo hello world > hello.txt
|
||||
|
||||
# access the file
|
||||
cat hello.txt
|
||||
|
||||
# unmount the bucket
|
||||
cd
|
||||
fusermount -u /tmp/my-bucket
|
||||
```
|
||||
|
||||
*External link:* [rclone documentation > rclone mount](https://rclone.org/commands/rclone_mount/)
|
||||
|
||||
## s3fs
|
||||
|
||||
*External link:* [s3fs github > README.md](https://github.com/s3fs-fuse/s3fs-fuse#examples)
|
||||
|
||||
## goofys
|
||||
|
||||
*External link:* [goofys github > README.md](https://github.com/kahing/goofys#usage)
|
||||
|
||||
## s3backer
|
||||
|
||||
*External link:* [s3backer github > manpage](https://github.com/archiecobbs/s3backer/wiki/ManPage)
|
||||
|
||||
## csi-s3
|
||||
|
||||
*External link:* [csi-s3 Github > README.md](https://github.com/ctrox/csi-s3)
|
||||
@@ -1,7 +1,19 @@
|
||||
# Connect it to
|
||||
# Connect it to...
|
||||
|
||||
To configure an S3 client to interact with Garage, you will need the following
|
||||
parameters:
|
||||
Garage implements the Amazon S3 protocol, which makes it compatible with many existing software programs.
|
||||
|
||||
In particular, you will find here instructions to connect it with:
|
||||
|
||||
- [web applications](./apps.md)
|
||||
- [website hosting](./websites.md)
|
||||
- [software repositories](./repositories.md)
|
||||
- [CLI tools](./cli.md)
|
||||
- [your own code](./code.md)
|
||||
|
||||
### Generic instructions
|
||||
|
||||
To configure S3-compatible software to interact with Garage,
|
||||
you will need the following parameters:
|
||||
|
||||
- An **API endpoint**: this corresponds to the HTTP or HTTPS address
|
||||
used to contact the Garage server. When runing Garage locally this will usually
|
||||
@@ -27,12 +39,3 @@ provided that you follow the following guidelines:
|
||||
If this is not configured explicitly, clients usually try to talk to region `us-east-1`.
|
||||
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 clients per category:
|
||||
|
||||
- [Apps](./apps.md)
|
||||
- [Websites](./websites.md)
|
||||
- [Repositories](./repositories.md)
|
||||
- [CLI tools](./cli.md)
|
||||
- [Your code](./code.md)
|
||||
|
||||
|
||||
@@ -1 +1,169 @@
|
||||
# Repositories (Docker, Nix...)
|
||||
# Repositories (Docker, Nix, Git...)
|
||||
|
||||
Whether you need to store and serve binary packages or source code, you may want to deploy a tool referred as a repository or registry.
|
||||
Garage can also help you serve this content.
|
||||
|
||||
## Gitea
|
||||
|
||||
You can use Garage with Gitea to store your [git LFS](https://git-lfs.github.com/) data, your users' avatar, and their attachements.
|
||||
You can configure a different target for each data type (check `[lfs]` and `[attachment]` sections of the Gitea documentation) and you can provide a default one through the `[storage]` section.
|
||||
|
||||
Let's start by creating a key and a bucket (your key id and secret will be needed later, keep them somewhere):
|
||||
|
||||
```bash
|
||||
garage key new --name gitea-key
|
||||
garage bucket create gitea
|
||||
garage bucket allow gitea --read --write --key gitea-key
|
||||
```
|
||||
|
||||
Then you can edit your configuration (by default `/etc/gitea/conf/app.ini`):
|
||||
|
||||
```ini
|
||||
[storage]
|
||||
STORAGE_TYPE=minio
|
||||
MINIO_ENDPOINT=localhost:3900
|
||||
MINIO_ACCESS_KEY_ID=GKxxx
|
||||
MINIO_SECRET_ACCESS_KEY=xxxx
|
||||
MINIO_BUCKET=gitea
|
||||
MINIO_LOCATION=garage
|
||||
MINIO_USE_SSL=false
|
||||
```
|
||||
|
||||
You can also pass this configuration through environment variables:
|
||||
|
||||
```bash
|
||||
GITEA__storage__STORAGE_TYPE=minio
|
||||
GITEA__storage__MINIO_ENDPOINT=localhost:3900
|
||||
GITEA__storage__MINIO_ACCESS_KEY_ID=GKxxx
|
||||
GITEA__storage__MINIO_SECRET_ACCESS_KEY=xxxx
|
||||
GITEA__storage__MINIO_BUCKET=gitea
|
||||
GITEA__storage__MINIO_LOCATION=garage
|
||||
GITEA__storage__MINIO_USE_SSL=false
|
||||
```
|
||||
|
||||
Then restart your gitea instance and try to upload a custom avatar.
|
||||
If it worked, you should see some content in your gitea bucket (you must configure your `aws` command before):
|
||||
|
||||
```
|
||||
$ aws s3 ls s3://gitea/avatars/
|
||||
2021-11-10 12:35:47 190034 616ba79ae2b84f565c33d72c2ec50861
|
||||
```
|
||||
|
||||
|
||||
*External link:* [Gitea Documentation > Configuration Cheat Sheet](https://docs.gitea.io/en-us/config-cheat-sheet/)
|
||||
|
||||
## Gitlab
|
||||
|
||||
*External link:* [Gitlab Documentation > Object storage](https://docs.gitlab.com/ee/administration/object_storage.html)
|
||||
|
||||
|
||||
## Private NPM Registry (Verdacio)
|
||||
|
||||
*External link:* [Verdaccio Github Repository > aws-storage plugin](https://github.com/verdaccio/verdaccio/tree/master/packages/plugins/aws-storage)
|
||||
|
||||
## Docker
|
||||
|
||||
Not yet compatible, follow [#103](https://git.deuxfleurs.fr/Deuxfleurs/garage/issues/103).
|
||||
|
||||
*External link:* [Docker Documentation > Registry storage drivers > S3 storage driver](https://docs.docker.com/registry/storage-drivers/s3/)
|
||||
|
||||
## Nix
|
||||
|
||||
Nix has no repository in its terminology: instead, it breaks down this concept in 2 parts: binary cache and channel.
|
||||
|
||||
**A channel** is a set of `.nix` definitions that generate definitions for all the software you want to serve.
|
||||
|
||||
Because we do not want all our clients to compile all these derivations by themselves,
|
||||
we can compile them once and then serve them as part of our **binary cache**.
|
||||
|
||||
It is possible to use a **binary cache** without a channel, you only need to serve your nix definitions
|
||||
through another support, like a git repository.
|
||||
|
||||
As a first step, we will need to create a bucket on Garage and enabling website access on it:
|
||||
|
||||
```bash
|
||||
garage key new --name nix-key
|
||||
garage bucket create nix.example.com
|
||||
garage bucket allow nix.example.com --read --write --key nix-key
|
||||
garage bucket website nix.example.com --allow
|
||||
```
|
||||
|
||||
If you need more information about exposing buckets as websites on Garage,
|
||||
check [Exposing buckets as websites](/cookbook/exposing_websites.html)
|
||||
and [Configuring a reverse proxy](/cookbook/reverse_proxy.html).
|
||||
|
||||
Next, we want to check that our bucket works:
|
||||
|
||||
```bash
|
||||
echo nix repo > /tmp/index.html
|
||||
mc cp /tmp/index.html garage/nix/
|
||||
rm /tmp/index.html
|
||||
|
||||
curl https://nix.example.com
|
||||
# output: nix repo
|
||||
```
|
||||
|
||||
### Binary cache
|
||||
|
||||
To serve binaries as part of your cache, you need to sign them with a key specific to nix.
|
||||
You can generate the keypair as follow:
|
||||
|
||||
```bash
|
||||
nix-store --generate-binary-cache-key <name> cache-priv-key.pem cache-pub-key.pem
|
||||
```
|
||||
|
||||
You can then manually sign the packages of your store with the following command:
|
||||
|
||||
```bash
|
||||
nix sign-paths --all -k cache-priv-key.pem
|
||||
```
|
||||
|
||||
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/cache-priv-key.pem
|
||||
```
|
||||
|
||||
Now that your content is signed, you can copy a derivation to your cache.
|
||||
For example, if you want to copy a specific derivation of your store:
|
||||
|
||||
```bash
|
||||
nix copy /nix/store/wadmyilr414n7bimxysbny876i2vlm5r-bash-5.1-p8 --to 's3://nix?endpoint=garage.example.com®ion=garage'
|
||||
```
|
||||
|
||||
*Note that if you have not signed your packages, you can append to the end of your S3 URL `&secret-key=/etc/nix/cache-priv-key.pem`.*
|
||||
|
||||
Sometimes you don't want to hardcode this store path in your script.
|
||||
Let suppose that you are working on a codebase that you build with `nix-build`, you can then run:
|
||||
|
||||
```bash
|
||||
nix copy $(nix-build) --to 's3://nix?endpoint=garage.example.com®ion=garage'
|
||||
```
|
||||
|
||||
*This command works because the only thing that `nix-build` outputs on stdout is the paths of the built derivations in your nix store.*
|
||||
|
||||
You can include your derivation dependencies:
|
||||
|
||||
```bash
|
||||
nix copy $(nix-store -qR $(nix-build)) --to 's3://nix?endpoint=garage.example.com®ion=garage'
|
||||
```
|
||||
|
||||
Now, your binary cache stores your derivation and all its dependencies.
|
||||
Just inform your users that they must update their `nix.conf` file with the following lines:
|
||||
|
||||
```toml
|
||||
substituters = https://cache.nixos.org https://nix.example.com
|
||||
trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= nix.example.com:eTGL6kvaQn6cDR/F9lDYUIP9nCVR/kkshYfLDJf1yKs=
|
||||
```
|
||||
|
||||
*You must re-add cache.nixorg.org because redeclaring these keys override the previous configuration instead of extending it.*
|
||||
|
||||
Now, when your clients will run `nix-build` or any command that generates a derivation for which a hash is already present
|
||||
on the binary cache, the client will download the result from the cache instead of compiling it, saving lot of time and CPU!
|
||||
|
||||
|
||||
### Channels
|
||||
|
||||
Channels additionnaly serve Nix definitions, ie. a `.nix` file referencing
|
||||
all the derivations you want to serve.
|
||||
|
||||
@@ -1 +1,78 @@
|
||||
# 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 build and deploy your website:
|
||||
|
||||
```bsh
|
||||
hugo
|
||||
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,39 @@
|
||||
# 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 eases 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 layout assign --gateway --tag gw1 <node_id>
|
||||
garage layout show # review the changes you are making
|
||||
garage layout apply # once satisfied, apply the changes
|
||||
```
|
||||
|
||||
Then use `http://localhost:3900` when a S3 endpoint is required:
|
||||
|
||||
```bash
|
||||
aws --endpoint-url http://127.0.0.1:3900 s3 ls
|
||||
```
|
||||
|
||||
If a newly added gateway node seems to not be working, do a full table resync to ensure that bucket and key list are correctly propagated:
|
||||
|
||||
```bash
|
||||
garage repair -a --yes tables
|
||||
```
|
||||
@@ -4,22 +4,23 @@ A cookbook, when you cook, is a collection of recipes.
|
||||
Similarly, Garage's cookbook contains a collection of recipes that are known to works well!
|
||||
This chapter could also be referred as "Tutorials" or "Best practices".
|
||||
|
||||
- **[Deploying Garage](real_world.md):** This page will walk you through all of the necessary
|
||||
- **[Multi-node deployment](real_world.md):** This page will walk you through all of the necessary
|
||||
steps to deploy Garage in a real-world setting.
|
||||
|
||||
- **[Configuring S3 clients](clients.md):** This page will explain how to configure
|
||||
popular S3 clients to interact with a Garage server.
|
||||
|
||||
- **[Hosting a website](website.md):** This page explains how to use Garage
|
||||
to host a static website.
|
||||
|
||||
- **[Recovering from failures](recovering.md):** Garage's first selling point is resilience
|
||||
to hardware failures. This section explains how to recover from such a failure in the
|
||||
best possible way.
|
||||
|
||||
- **[Building from source](from_source.md):** This page explains how to build Garage from
|
||||
source in case a binary is not provided for your architecture, or if you want to
|
||||
hack with us!
|
||||
|
||||
- **[Starting with Systemd](from_source.md):** This page explains how to run Garage
|
||||
- **[Integration with Systemd](systemd.md):** This page explains how to run Garage
|
||||
as a Systemd service (instead of as a Docker container).
|
||||
|
||||
- **[Configuring a gateway node](gateways.md):** This page explains how to run a gateway node in a Garage cluster, i.e. a Garage node that doesn't store data but accelerates access to data present on the other nodes.
|
||||
|
||||
- **[Hosting a website](exposing_websites.md):** This page explains how to use Garage
|
||||
to host a static website.
|
||||
|
||||
- **[Configuring a reverse-proxy](reverse_proxy.md):** This page explains how to configure a reverse-proxy to add TLS support to your S3 api endpoint.
|
||||
|
||||
- **[Recovering from failures](recovering.md):** Garage's first selling point is resilience
|
||||
to hardware failures. This section explains how to recover from such a failure in the
|
||||
best possible way.
|
||||
|
||||
@@ -41,15 +41,15 @@ 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).
|
||||
Our docker image is currently named `dxflrs/amd64_garage` and is stored on the [Docker Hub](https://hub.docker.com/r/dxflrs/amd64_garage/tags?page=1&ordering=last_updated).
|
||||
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).
|
||||
to check [the most recent versions on the Docker Hub](https://hub.docker.com/r/dxflrs/amd64_garage/tags?page=1&ordering=last_updated).
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
sudo docker pull lxpz/garage_amd64:v0.4.0
|
||||
sudo docker pull dxflrs/amd64_garage:v0.4.0
|
||||
```
|
||||
|
||||
## Deploying and configuring Garage
|
||||
@@ -78,9 +78,12 @@ rpc_bind_addr = "[::]:3901"
|
||||
rpc_public_addr = "<this node's public IP>:3901"
|
||||
rpc_secret = "<RPC secret>"
|
||||
|
||||
bootstrap_peers = []
|
||||
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
api_bind_addr = "[::]:3900"
|
||||
root_domain = ".s3.garage"
|
||||
|
||||
[s3_web]
|
||||
bind_addr = "[::]:3902"
|
||||
@@ -141,7 +144,7 @@ At this point, nodes are not yet talking to one another.
|
||||
Your output should therefore look like follows:
|
||||
|
||||
```
|
||||
Mercury$ garage node-id
|
||||
Mercury$ garage status
|
||||
==== HEALTHY NODES ====
|
||||
ID Hostname Address Tag Zone Capacity
|
||||
563e1ac825ee3323… Mercury [fc00:1::1]:3901 NO ROLE ASSIGNED
|
||||
@@ -154,14 +157,14 @@ 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`.
|
||||
run `garage node id`.
|
||||
This will print keys as follows:
|
||||
|
||||
```bash
|
||||
Mercury$ garage node-id
|
||||
Mercury$ garage node id
|
||||
563e1ac825ee3323aa441e72c26d1030d6d4414aeb3dd25287c531e7fc2bc95d@[fc00:1::1]:3901
|
||||
|
||||
Venus$ garage node-id
|
||||
Venus$ garage node id
|
||||
86f0f26ae4afbd59aaf9cfb059eefac844951efd5b8caeec0d53f4ed6c85f332@[fc00:1::2]:3901
|
||||
|
||||
etc.
|
||||
@@ -188,20 +191,22 @@ ID Hostname Address Tag Zone Capa
|
||||
212f7572f0c89da9… Mars [fc00:F::1]:3901 NO ROLE ASSIGNED
|
||||
```
|
||||
|
||||
## Giving roles to nodes
|
||||
## Creating a cluster layout
|
||||
|
||||
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.
|
||||
This information is called the **cluster layout** and consists
|
||||
of a role that is assigned to each active cluster node.
|
||||
|
||||
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` | `563e` | `par1` |
|
||||
| Paris | Venus | 2 To | `4` | `86f0` | `par1` |
|
||||
| London | Earth | 2 To | `4` | `6814` | `lon1` |
|
||||
| Brussels | Mars | 1.5 To | `3` | `212f` | `bru1` |
|
||||
| Paris | Mercury | 1 To | `10` | `563e` | `par1` |
|
||||
| Paris | Venus | 2 To | `20` | `86f0` | `par1` |
|
||||
| London | Earth | 2 To | `20` | `6814` | `lon1` |
|
||||
| Brussels | Mars | 1.5 To | `15` | `212f` | `bru1` |
|
||||
|
||||
#### Node identifiers
|
||||
|
||||
@@ -236,13 +241,9 @@ in order to provide high availability despite failure of a zone.
|
||||
|
||||
Garage reasons on an abstract metric about disk storage that is named the *capacity* of a node.
|
||||
The capacity configured in Garage must be proportional to the disk space dedicated to the node.
|
||||
Due to the way the Garage allocation algorithm works, capacity values must
|
||||
be **integers**, and must be **as small as possible**, for instance with
|
||||
1 representing the size of your smallest server.
|
||||
|
||||
Here we chose that 1 unit of capacity = 0.5 To, so that we can express servers of size
|
||||
1 To and 2 To, as wel as the intermediate size 1.5 To, with the integer values 2, 4 and
|
||||
3 respectively (see table above).
|
||||
Capacity values must be **integers** but can be given any signification.
|
||||
Here we chose that 1 unit of capacity = 100 GB.
|
||||
|
||||
Note that the amount of data stored by Garage on each server may not be strictly proportional to
|
||||
its capacity value, as Garage will priorize having 3 copies of data in different zones,
|
||||
@@ -254,13 +255,29 @@ 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:
|
||||
|
||||
```bash
|
||||
garage layout assign -z par1 -c 10 -t mercury 563e
|
||||
garage layout assign -z par1 -c 20 -t venus 86f0
|
||||
garage layout assign -z lon1 -c 20 -t earth 6814
|
||||
garage layout assign -z bru1 -c 15 -t mars 212f
|
||||
```
|
||||
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
|
||||
|
||||
At this point, the changes in the cluster layout have not yet been applied.
|
||||
To show the new layout that will be applied, call:
|
||||
|
||||
```bash
|
||||
garage layout show
|
||||
```
|
||||
|
||||
Once you are satisfied with your new layout, apply it with:
|
||||
|
||||
```bash
|
||||
garage layout apply
|
||||
```
|
||||
|
||||
**WARNING:** if you want to use the layout modification commands in a script,
|
||||
make sure to read [this page](/reference_manual/layout.html) first.
|
||||
|
||||
|
||||
## Using your Garage cluster
|
||||
|
||||
@@ -269,5 +286,5 @@ 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`).
|
||||
|
||||
Configuring an S3 client to interact with Garage is covered
|
||||
[in the next section](clients.md).
|
||||
Configuring S3-compatible applicatiosn to interact with Garage
|
||||
is covered in the [Integrations](/connect/index.html) section.
|
||||
|
||||
@@ -28,8 +28,10 @@ and you should instead use one of the methods detailed in the next sections.
|
||||
|
||||
Removing a node is done with the following command:
|
||||
|
||||
```
|
||||
garage node remove --yes <node_id>
|
||||
```bash
|
||||
garage layout remove <node_id>
|
||||
garage layout show # review the changes you are making
|
||||
garage layout apply # once satisfied, apply the changes
|
||||
```
|
||||
|
||||
(you can get the `node_id` of the failed node by running `garage status`)
|
||||
@@ -50,7 +52,7 @@ We just need to tell Garage to get back all the data blocks and store them on th
|
||||
First, set up a new HDD to store Garage's data directory on the failed node, and restart Garage using
|
||||
the existing configuration. Then, run:
|
||||
|
||||
```
|
||||
```bash
|
||||
garage repair -a --yes blocks
|
||||
```
|
||||
|
||||
@@ -58,7 +60,7 @@ This will re-synchronize blocks of data that are missing to the new HDD, reading
|
||||
|
||||
You can check on the advancement of this process by doing the following command:
|
||||
|
||||
```
|
||||
```bash
|
||||
garage stats -a
|
||||
```
|
||||
|
||||
@@ -94,9 +96,11 @@ The ID of the lost node should be shown in `garage status` in the section for di
|
||||
|
||||
Then, replace the broken node by the new one, using:
|
||||
|
||||
```
|
||||
garage node configure --replace <old_node_id> \
|
||||
-c <capacity> -z <zone> -t <node_tag> <new_node_id>
|
||||
```bash
|
||||
garage layout assign <new_node_id> --replace <old_node_id> \
|
||||
-c <capacity> -z <zone> -t <node_tag>
|
||||
garage layout show # review the changes you are making
|
||||
garage layout apply # once satisfied, apply the changes
|
||||
```
|
||||
|
||||
Garage will then start synchronizing all required data on the new node.
|
||||
|
||||
@@ -1 +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,53 @@
|
||||
# Goals and use cases
|
||||
|
||||
## Goals and non-goals
|
||||
|
||||
Garage is a lightweight geo-distributed data store that implements the
|
||||
[Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html)
|
||||
object storage protocole. It enables applications to store large blobs such
|
||||
as pictures, video, images, documents, etc., in a redundant multi-node
|
||||
setting. S3 is versatile enough to also be used to publish a static
|
||||
website.
|
||||
|
||||
Garage is an opinionated object storage solutoin, we focus on the following **desirable properties**:
|
||||
|
||||
- **Self-contained & lightweight**: works everywhere and integrates well in existing environments to target [hyperconverged infrastructures](https://en.wikipedia.org/wiki/Hyper-converged_infrastructure).
|
||||
- **Highly resilient**: highly resilient to network failures, network latency, disk failures, sysadmin failures.
|
||||
- **Simple**: simple to understand, simple to operate, simple to debug.
|
||||
- **Internet enabled**: made for multi-sites (eg. datacenters, offices, households, etc.) interconnected through regular Internet connections.
|
||||
|
||||
We also noted that the pursuit of some other goals are detrimental to our initial goals.
|
||||
The following has been identified as **non-goals** (if these points matter to you, you should not use Garage):
|
||||
|
||||
- **Extreme performances**: high performances constrain a lot the design and the infrastructure; we seek performances through minimalism only.
|
||||
- **Feature extensiveness**: we do not plan to add additional features compared to the ones provided by the S3 API.
|
||||
- **Storage optimizations**: erasure coding or any other coding technique both increase the difficulty of placing data and synchronizing; we limit ourselves to duplication.
|
||||
- **POSIX/Filesystem compatibility**: we do not aim at being POSIX compatible or to emulate any kind of filesystem. Indeed, in a distributed environment, such synchronizations are translated in network messages that impose severe constraints on the deployment.
|
||||
|
||||
## Use-cases
|
||||
|
||||
*Are you also using Garage in your organization? [Open a PR](https://git.deuxfleurs.fr/Deuxfleurs/garage) to add your use case here!*
|
||||
|
||||
### Deuxfleurs
|
||||
|
||||
[Deuxfleurs](https://deuxfleurs.fr) is an experimental non-profit hosting
|
||||
organization that develops Garage. Deuxfleurs is focused on building highly
|
||||
available infrastructure through redundancy in multiple geographical
|
||||
locations. They use Garage themselves for the following tasks:
|
||||
|
||||
- Hosting of [main website](https://deuxfleurs.fr), [this website](https://garagehq.deuxfleurs.fr), as well as the personal website of many of the members of the organization
|
||||
|
||||
- As a [Matrix media backend](https://github.com/matrix-org/synapse-s3-storage-provider)
|
||||
|
||||
- To store personal data and shared documents through [Bagage](https://git.deuxfleurs.fr/Deuxfleurs/bagage), a homegrown WebDav-to-S3 proxy
|
||||
|
||||
- In the Drone continuous integration platform to store task logs
|
||||
|
||||
- As a Nix binary cache
|
||||
|
||||
- As a backup target using `rclone`
|
||||
|
||||
The Deuxfleurs Garage cluster is a multi-site cluster currently composed of
|
||||
4 nodes in 2 physical locations. In the future it will be expanded to at
|
||||
least 3 physical locations to fully exploit Garage's potential for high
|
||||
availability.
|
||||
@@ -1,5 +1,26 @@
|
||||
# Design
|
||||
|
||||
The design section helps you to see Garage from a "big picture" perspective.
|
||||
It will allow you to understand if Garage is a good fit for you,
|
||||
how to better use it, how to contribute to it, what can Garage could and could not do, etc.
|
||||
The design section helps you to see Garage from a "big picture"
|
||||
perspective. It will allow you to understand if Garage is a good fit for
|
||||
you, how to better use it, how to contribute to it, what can Garage could
|
||||
and could not do, etc.
|
||||
|
||||
- **[Goals and use cases](goals.md):** This page explains why Garage was concieved and what practical use cases it targets.
|
||||
|
||||
- **[Related work](related_work.md):** This pages presents the theoretical background on which Garage is built, and describes other software storage solutions and why they didn't work for us.
|
||||
|
||||
- **[Internals](internals.md):** This page enters into more details on how Garage manages data internally.
|
||||
|
||||
## Talks
|
||||
|
||||
We love to talk and hear about Garage, that's why we keep a log here:
|
||||
|
||||
- [(fr, 2021-11-13, video) Garage : Mille et une façons de stocker vos données](https://video.tedomum.net/w/moYKcv198dyMrT8hCS5jz9) and [slides (html)](https://rfid.deuxfleurs.fr/presentations/2021-11-13/garage/) - during [RFID#1](https://rfid.deuxfleurs.fr/programme/2021-11-13/) event
|
||||
|
||||
- [(en, 2021-04-28) Distributed object storage is centralised](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2021-04-28_spirals-team/talk.pdf)
|
||||
|
||||
- [(fr, 2020-12-02) Garage : jouer dans la cour des grands quand on est un hébergeur associatif](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2020-12-02_wide-team/talk.pdf)
|
||||
|
||||
*Did you write or talk about Garage? [Open a pull request](https://git.deuxfleurs.fr/Deuxfleurs/garage/) to add a link here!*
|
||||
|
||||
|
||||
|
||||
@@ -1,158 +1,98 @@
|
||||
**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 (see [this paper](https://dl.acm.org/doi/abs/10.1145/1323293.1294281) and [that paper](https://www.usenix.org/conference/nsdi16/technical-sessions/presentation/eisenbud))
|
||||
|
||||
**Objects:**
|
||||
- CRDTs (see [this paper](https://link.springer.com/chapter/10.1007/978-3-642-24550-3_29))
|
||||
|
||||
- *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...*
|
||||
In the meantime, you can find some information at the following links:
|
||||
|
||||
**Blocks:**
|
||||
- [this presentation (in French)](https://git.deuxfleurs.fr/Deuxfleurs/garage/src/branch/main/doc/talks/2020-12-02_wide-team/talk.pdf)
|
||||
|
||||
- *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)
|
||||
- [an old design draft](/working_documents/design_draft.md)
|
||||
|
||||
|
||||
#### 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,4 +1,4 @@
|
||||
# Related Work
|
||||
# Related work
|
||||
|
||||
## Context
|
||||
|
||||
@@ -41,14 +41,35 @@ There were many attempts in research too. I am only thinking to [LBFS](https://p
|
||||
|
||||
## Existing software
|
||||
|
||||
**[Pithos](https://github.com/exoscale/pithos) :**
|
||||
**[MinIO](https://min.io/):** MinIO shares our *Self-contained & lightweight* goal but selected two of our non-goals: *Storage optimizations* through erasure coding and *POSIX/Filesystem compatibility* through strong consistency.
|
||||
However, by pursuing these two non-goals, MinIO do not reach our desirable properties.
|
||||
Firstly, it fails on the *Simple* property: due to the erasure coding, MinIO has severe limitations on how drives can be added or deleted from a cluster.
|
||||
Secondly, it fails on the *Internet enabled* property: due to its strong consistency, MinIO is latency sensitive.
|
||||
Furthermore, MinIO has no knowledge of "sites" and thus can not distribute data to minimize the failure of a given site.
|
||||
|
||||
**[Openstack Swift](https://docs.openstack.org/swift/latest/):**
|
||||
OpenStack Swift at least fails on the *Self-contained & lightweight* goal.
|
||||
Starting it requires around 8GB of RAM, which is too much especially in an hyperconverged infrastructure.
|
||||
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.
|
||||
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.
|
||||
|
||||
**[Pithos](https://github.com/exoscale/pithos):**
|
||||
Pithos has been abandonned and should probably not used yet, in the following we explain why we did not pick their design.
|
||||
Pithos was relying as a S3 proxy in front of Cassandra (and was working with Scylla DB too).
|
||||
From its designers' mouth, storing data in Cassandra has shown its limitations justifying the project abandonment.
|
||||
They built a closed-source version 2 that does not store blobs in the database (only metadata) but did not communicate further on it.
|
||||
We considered there v2's design but concluded that it does not fit both our *Self-contained & lightweight* and *Simple* properties. It makes the development, the deployment and the operations more complicated while reducing the flexibility.
|
||||
|
||||
**[IPFS](https://ipfs.io/) :**
|
||||
**[Riak CS](https://docs.riak.com/riak/cs/2.1.1/index.html):**
|
||||
*Not written yet*
|
||||
|
||||
**[IPFS](https://ipfs.io/):**
|
||||
*Not written yet*
|
||||
|
||||
## Specific research papers
|
||||
|
||||
@@ -2,3 +2,13 @@
|
||||
|
||||
Now that you are a Garage expert, you want to enhance it, you are in the right place!
|
||||
We discuss here how to hack on Garage, how we manage its development, etc.
|
||||
|
||||
## Rust API (docs.rs)
|
||||
If you encounter a specific bug in Garage or plan to patch it, you may jump directly to the source code's documentation!
|
||||
|
||||
- [garage\_api](https://docs.rs/garage_api/latest/garage_api/) - contains the S3 standard API endpoint
|
||||
- [garage\_model](https://docs.rs/garage_model/latest/garage_model/) - contains Garage's model built on the table abstraction
|
||||
- [garage\_rpc](https://docs.rs/garage_rpc/latest/garage_rpc/) - contains Garage's federation protocol
|
||||
- [garage\_table](https://docs.rs/garage_table/latest/garage_table/) - contains core Garage's CRDT datatypes
|
||||
- [garage\_util](https://docs.rs/garage_util/latest/garage_util/) - contains garage helpers
|
||||
- [garage\_web](https://docs.rs/garage_web/latest/garage_web/) - contains the S3 website endpoint
|
||||
|
||||
@@ -13,42 +13,6 @@ We have a simple [PR on cargo2nix](https://github.com/cargo2nix/cargo2nix/pull/2
|
||||
|
||||
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"
|
||||
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 1.4 MiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 310 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 35 KiB |
+41
-69
@@ -12,96 +12,68 @@
|
||||
]
|
||||
</p>
|
||||
|
||||
```
|
||||
This very website is hosted using Garage. In other words: the doc is the PoC!
|
||||
```
|
||||
|
||||
# The Garage Geo-Distributed Data Store
|
||||
# Data resiliency for everyone
|
||||
|
||||
Garage is a lightweight geo-distributed data store.
|
||||
It comes from the observation that despite numerous object stores
|
||||
many people have broken data management policies (backup/replication on a single site or none at all).
|
||||
To promote better data management policies, we focused on the following **desirable properties**:
|
||||
Garage is an **open-source** distributed **storage service** you can **self-host** to fullfill many needs:
|
||||
|
||||
- **Self-contained & lightweight**: works everywhere and integrates well in existing environments to target [hyperconverged infrastructures](https://en.wikipedia.org/wiki/Hyper-converged_infrastructure).
|
||||
- **Highly resilient**: highly resilient to network failures, network latency, disk failures, sysadmin failures.
|
||||
- **Simple**: simple to understand, simple to operate, simple to debug.
|
||||
- **Internet enabled**: made for multi-sites (eg. datacenters, offices, households, etc.) interconnected through regular Internet connections.
|
||||
<p align="center" style="text-align:center; margin-bottom: 5rem;">
|
||||
<img alt="Summary of the possible usages with a related icon: host a website, store media and backup target" src="img/usage.svg" />
|
||||
</p>
|
||||
|
||||
We also noted that the pursuit of some other goals are detrimental to our initial goals.
|
||||
The following has been identified as **non-goals** (if these points matter to you, you should not use Garage):
|
||||
<p align="center" style="text-align:center; margin-bottom: 5rem;">
|
||||
<a href="/design/use_cases.html">⮞ learn more about use cases ⮜</a>
|
||||
</p>
|
||||
|
||||
- **Extreme performances**: high performances constrain a lot the design and the infrastructure; we seek performances through minimalism only.
|
||||
- **Feature extensiveness**: complete implementation of the S3 API or any other API to make garage a drop-in replacement is not targeted as it could lead to decisions impacting our desirable properties.
|
||||
- **Storage optimizations**: erasure coding or any other coding technique both increase the difficulty of placing data and synchronizing; we limit ourselves to duplication.
|
||||
- **POSIX/Filesystem compatibility**: we do not aim at being POSIX compatible or to emulate any kind of filesystem. Indeed, in a distributed environment, such synchronizations are translated in network messages that impose severe constraints on the deployment.
|
||||
Garage implements the **[Amazon S3 API](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html)** and thus is already **compatible** with many applications:
|
||||
|
||||
## Supported and planned protocols
|
||||
<p align="center" style="text-align:center; margin-bottom: 8rem;">
|
||||
<img alt="Garage is already compatible with Nextcloud, Mastodon, Matrix Synapse, Cyberduck, RClone and Peertube" src="img/software.svg" />
|
||||
</p>
|
||||
|
||||
Garage speaks (or will speak) the following protocols:
|
||||
<p align="center" style="text-align:center; margin-bottom: 5rem;">
|
||||
<a href="/connect/index.html">⮞ learn more about integrations ⮜</a>
|
||||
</p>
|
||||
|
||||
- [S3](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html) - *SUPPORTED* - Enable applications to store large blobs such as pictures, video, images, documents, etc. S3 is versatile enough to also be used to publish a static website.
|
||||
- [IMAP](https://github.com/go-pluto/pluto) - *PLANNED* - email storage is quite complex to get good performances.
|
||||
To keep performances optimal, most IMAP servers only support on-disk storage.
|
||||
We plan to add logic to Garage to make it a viable solution for email storage.
|
||||
- *More to come*
|
||||
|
||||
## Use Cases
|
||||
Garage provides **data resiliency** by **replicating** data 3x over **distant** servers:
|
||||
|
||||
**[Deuxfleurs](https://deuxfleurs.fr):** Garage is used by Deuxfleurs which is a non-profit hosting organization.
|
||||
Especially, it is used to host their main website, this documentation and some of its members' blogs.
|
||||
Additionally, Garage is used as a [backend for Nextcloud](https://docs.nextcloud.com/server/20/admin_manual/configuration_files/primary_storage.html).
|
||||
Deuxfleurs also plans to use Garage as their [Matrix's media backend](https://github.com/matrix-org/synapse-s3-storage-provider) and as the backend of [OCIS](https://github.com/owncloud/ocis).
|
||||
<p align="center" style="text-align:center; margin-bottom: 5rem;">
|
||||
<img alt="An example deployment on a map with servers in 5 zones: UK, France, Belgium, Germany and Switzerland. Each chunk of data is replicated in 3 of these 5 zones." src="img/map.svg" />
|
||||
</p>
|
||||
|
||||
*Are you using Garage? [Open a pull request](https://git.deuxfleurs.fr/Deuxfleurs/garage/) to add your organization here!*
|
||||
<p align="center" style="text-align:center; margin-bottom: 5rem;">
|
||||
<a href="/design/index.html">⮞ learn more about our design ⮜</a>
|
||||
</p>
|
||||
|
||||
## Comparison to existing software
|
||||
Did you notice that *this website* is hosted and served by Garage?
|
||||
|
||||
**[MinIO](https://min.io/):** MinIO shares our *Self-contained & lightweight* goal but selected two of our non-goals: *Storage optimizations* through erasure coding and *POSIX/Filesystem compatibility* through strong consistency.
|
||||
However, by pursuing these two non-goals, MinIO do not reach our desirable properties.
|
||||
Firstly, it fails on the *Simple* property: due to the erasure coding, MinIO has severe limitations on how drives can be added or deleted from a cluster.
|
||||
Secondly, it fails on the *Internet enabled* property: due to its strong consistency, MinIO is latency sensitive.
|
||||
Furthermore, MinIO has no knowledge of "sites" and thus can not distribute data to minimize the failure of a given site.
|
||||
## Keeping requirements low
|
||||
|
||||
**[Openstack Swift](https://docs.openstack.org/swift/latest/):**
|
||||
OpenStack Swift at least fails on the *Self-contained & lightweight* goal.
|
||||
Starting it requires around 8GB of RAM, which is too much especially in an hyperconverged infrastructure.
|
||||
We also do not classify Swift as *Simple*.
|
||||
We worked hard to keep requirements as low as possible as we target the largest possible public.
|
||||
|
||||
**[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.
|
||||
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.
|
||||
* **CPU:** any x86\_64 CPU from the last 10 years, ARMv7 or ARMv8.
|
||||
* **RAM:** 1GB
|
||||
* **Disk Space:** at least 16GB
|
||||
* **Network:** 200ms or less, 50 Mbps or more
|
||||
* **Heterogeneous hardware:** build a cluster with whatever second-hand machines are available
|
||||
|
||||
*More comparisons are available in our [Related Work](design/related_work.md) chapter.*
|
||||
*For the network, as we do not use consensus algorithms like Paxos or Raft, Garage is not as latency sensitive.*
|
||||
*Thanks to Rust and its zero-cost abstractions, we keep CPU and memory low.*
|
||||
|
||||
## Other Resources
|
||||
## Built on the shoulder of giants
|
||||
|
||||
This website is not the only source of information about Garage!
|
||||
We reference here other places on the Internet where you can learn more about Garage.
|
||||
- [Dynamo: Amazon’s Highly Available Key-value Store ](https://dl.acm.org/doi/abs/10.1145/1323293.1294281) by DeCandia et al.
|
||||
- [Conflict-Free Replicated Data Types](https://link.springer.com/chapter/10.1007/978-3-642-24550-3_29) by Shapiro et al.
|
||||
- [Maglev: A Fast and Reliable Software Network Load Balancer](https://www.usenix.org/conference/nsdi16/technical-sessions/presentation/eisenbud) by Eisenbud et al.
|
||||
|
||||
### Rust API (docs.rs)
|
||||
## Talks
|
||||
|
||||
If you encounter a specific bug in Garage or plan to patch it, you may jump directly to the source code's documentation!
|
||||
- [(fr, 2021-11-13, video) Garage : Mille et une façons de stocker vos données](https://video.tedomum.net/w/moYKcv198dyMrT8hCS5jz9) and [slides (html)](https://rfid.deuxfleurs.fr/presentations/2021-11-13/garage/) - during [RFID#1](https://rfid.deuxfleurs.fr/programme/2021-11-13/) event
|
||||
|
||||
- [garage\_api](https://docs.rs/garage_api/latest/garage_api/) - contains the S3 standard API endpoint
|
||||
- [garage\_model](https://docs.rs/garage_model/latest/garage_model/) - contains Garage's model built on the table abstraction
|
||||
- [garage\_rpc](https://docs.rs/garage_rpc/latest/garage_rpc/) - contains Garage's federation protocol
|
||||
- [garage\_table](https://docs.rs/garage_table/latest/garage_table/) - contains core Garage's CRDT datatypes
|
||||
- [garage\_util](https://docs.rs/garage_util/latest/garage_util/) - contains garage helpers
|
||||
- [garage\_web](https://docs.rs/garage_web/latest/garage_web/) - contains the S3 website endpoint
|
||||
- [(en, 2021-04-28, pdf) Distributed object storage is centralised](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2021-04-28_spirals-team/talk.pdf)
|
||||
|
||||
### Talks
|
||||
|
||||
We love to talk and hear about Garage, that's why we keep a log here:
|
||||
|
||||
- [(en, 2021-04-28) Distributed object storage is centralised](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2021-04-28_spirals-team/talk.pdf)
|
||||
|
||||
- [(fr, 2020-12-02) Garage : jouer dans la cour des grands quand on est un hébergeur associatif](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2020-12-02_wide-team/talk.pdf)
|
||||
|
||||
*Did you write or talk about Garage? [Open a pull request](https://git.deuxfleurs.fr/Deuxfleurs/garage/) to add a link here!*
|
||||
- [(fr, 2020-12-02, pdf) Garage : jouer dans la cour des grands quand on est un hébergeur associatif](https://git.deuxfleurs.fr/Deuxfleurs/garage/raw/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2020-12-02_wide-team/talk.pdf)
|
||||
|
||||
## Community
|
||||
|
||||
@@ -113,7 +85,7 @@ 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
|
||||
# Sponsors and 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.
|
||||
|
||||
|
||||
@@ -6,22 +6,23 @@ and how to interact with it.
|
||||
|
||||
Our goal is to introduce you to Garage's workflows.
|
||||
Following this guide is recommended before moving on to
|
||||
[configuring a real-world deployment](../cookbook/real_world.md).
|
||||
[configuring a multi-node cluster](../cookbook/real_world.md).
|
||||
|
||||
Note that this kind of deployment should not be used in production, as it provides
|
||||
no redundancy for your data!
|
||||
Note that this kind of deployment should not be used in production,
|
||||
as it provides no redundancy for your data!
|
||||
|
||||
## Get a binary
|
||||
|
||||
Download the latest Garage binary from the release pages on our repository:
|
||||
|
||||
<https://git.deuxfleurs.fr/Deuxfleurs/garage/releases>
|
||||
<https://garagehq.deuxfleurs.fr/_releases.html>
|
||||
|
||||
Place this binary somewhere in your `$PATH` so that you can invoke the `garage`
|
||||
command directly (for instance you can copy the binary in `/usr/local/bin`
|
||||
or in `~/.local/bin`).
|
||||
|
||||
If a binary of the last version is not available for your architecture,
|
||||
or if you want a build customized for your system,
|
||||
you can [build Garage from source](../cookbook/from_source.md).
|
||||
|
||||
|
||||
@@ -48,6 +49,7 @@ bootstrap_peers = []
|
||||
[s3_api]
|
||||
s3_region = "garage"
|
||||
api_bind_addr = "[::]:3900"
|
||||
root_domain = ".s3.garage"
|
||||
|
||||
[s3_web]
|
||||
bind_addr = "[::]:3902"
|
||||
@@ -108,9 +110,9 @@ ID Hostname Address Tag Zone Capacit
|
||||
563e1ac825ee3323… linuxbox 127.0.0.1:3901 NO ROLE ASSIGNED
|
||||
```
|
||||
|
||||
## Configuring your Garage node
|
||||
## Creating a cluster layout
|
||||
|
||||
Configuring the nodes in a Garage deployment means informing Garage
|
||||
Creating a cluster layout for a Garage deployment means informing Garage
|
||||
of the disk space available on each node of the cluster
|
||||
as well as the zone (e.g. datacenter) each machine is located in.
|
||||
|
||||
@@ -118,14 +120,18 @@ For our test deployment, we are using only one node. The way in which we configu
|
||||
it does not matter, you can simply write:
|
||||
|
||||
```bash
|
||||
garage node configure -z dc1 -c 1 <node_id>
|
||||
garage layout assign -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 563e`.
|
||||
For instance here you could write just `garage layout assign -z dc1 -c 1 563e`.
|
||||
|
||||
The layout then has to be applied to the cluster, using:
|
||||
|
||||
```bash
|
||||
garage layout apply
|
||||
```
|
||||
|
||||
|
||||
## Creating buckets and keys
|
||||
@@ -196,7 +202,7 @@ Now that we have a bucket and a key, we need to give permissions to the key on t
|
||||
```
|
||||
garage bucket allow \
|
||||
--read \
|
||||
--write
|
||||
--write \
|
||||
nextcloud-bucket \
|
||||
--key nextcloud-app-key
|
||||
```
|
||||
@@ -269,5 +275,5 @@ The following tools can also be used to send and recieve files from/to Garage:
|
||||
- [Cyberduck](https://cyberduck.io/)
|
||||
- [`s3cmd`](https://s3tools.org/s3cmd)
|
||||
|
||||
Refer to the ["configuring clients"](../cookbook/clients.md) page to learn how to configure
|
||||
these clients to interact with a Garage server.
|
||||
Refer to the ["Integrations" section](../connect/index.md) to learn how to
|
||||
configure application and command line utilities to integrate with Garage.
|
||||
|
||||
@@ -30,6 +30,7 @@ sled_flush_every_ms = 2000
|
||||
[s3_api]
|
||||
api_bind_addr = "[::]:3900"
|
||||
s3_region = "garage"
|
||||
root_domain = ".s3.garage"
|
||||
|
||||
[s3_web]
|
||||
bind_addr = "[::]:3902"
|
||||
@@ -132,9 +133,9 @@ These peer identifiers have the following syntax:
|
||||
|
||||
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
|
||||
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
|
||||
key will be returned by `garage node id` and you will have to add the IP
|
||||
yourself.
|
||||
|
||||
#### `consul_host` and `consul_service_name`
|
||||
@@ -176,6 +177,15 @@ Garage will accept S3 API calls that are targetted to the S3 region defined here
|
||||
API calls targetted to other regions will fail with a AuthorizationHeaderMalformed error
|
||||
message that redirects the client to the correct region.
|
||||
|
||||
#### `root_domain`
|
||||
|
||||
The optionnal suffix to access bucket using vhost-style in addition to path-style request.
|
||||
Note path-style requests are always enabled, whether or not vhost-style is configured.
|
||||
Configuring vhost-style S3 required a wildcard DNS entry, and possibly a wildcard TLS certificate,
|
||||
but might be required by softwares not supporting path-style requests.
|
||||
|
||||
If `root_domain` is `s3.garage.eu`, a bucket called `my-bucket` can be interacted with
|
||||
using the hostname `my-bucket.s3.garage.eu`.
|
||||
|
||||
## The `[s3_web]` section
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Creating and updating a cluster layout
|
||||
|
||||
The cluster layout in Garage is a table that assigns to each node a role in
|
||||
the cluster. The role of a node in Garage can either be a storage node with
|
||||
a certain capacity, or a gateway node that does not store data and is only
|
||||
used as an API entry point for faster cluster access.
|
||||
An introduction to building cluster layouts can be found in the [production deployment](/cookbook/real_world.md) page.
|
||||
|
||||
## How cluster layouts work in Garage
|
||||
|
||||
In Garage, a cluster layout is composed of the following components:
|
||||
|
||||
- a table of roles assigned to nodes
|
||||
- a version number
|
||||
|
||||
Garage nodes will always use the cluster layout with the highest version number.
|
||||
|
||||
Garage nodes also maintain and synchronize between them a set of proposed role
|
||||
changes that haven't yet been applied. These changes will be applied (or
|
||||
canceled) in the next version of the layout
|
||||
|
||||
The following commands insert modifications to the set of proposed role changes
|
||||
for the next layout version (but they do not create the new layout immediately):
|
||||
|
||||
```bash
|
||||
garage layout assign [...]
|
||||
garage layout remove [...]
|
||||
```
|
||||
|
||||
The following command can be used to inspect the layout that is currently set in the cluster
|
||||
and the changes proposed for the next layout version, if any:
|
||||
|
||||
```bash
|
||||
garage layout show
|
||||
```
|
||||
|
||||
The following commands create a new layout with the specified version number,
|
||||
that either takes into account the proposed changes or cancels them:
|
||||
|
||||
```bash
|
||||
garage layout apply --version <new_version_number>
|
||||
garage layout revert --version <new_version_number>
|
||||
```
|
||||
|
||||
The version number of the new layout to create must be 1 + the version number
|
||||
of the previous layout that existed in the cluster. The `apply` and `revert`
|
||||
commands will fail otherwise.
|
||||
|
||||
## Warnings about Garage cluster layout management
|
||||
|
||||
**Warning: never make several calls to `garage layout apply` or `garage layout
|
||||
revert` with the same value of the `--version` flag. Doing so can lead to the
|
||||
creation of several different layouts with the same version number, in which
|
||||
case your Garage cluster will become inconsistent until fixed.** If a call to
|
||||
`garage layout apply` or `garage layout revert` has failed and `garage layout
|
||||
show` indicates that a new layout with the given version number has not been
|
||||
set in the cluster, then it is fine to call the command again with the same
|
||||
version number.
|
||||
|
||||
If you are using the `garage` CLI by typing individual commands in your
|
||||
shell, you shouldn't have much issues as long as you run commands one after
|
||||
the other and take care of checking the output of `garage layout show`
|
||||
before applying any changes.
|
||||
|
||||
If you are using the `garage` CLI to script layout changes, follow the following recommendations:
|
||||
|
||||
- Make all of your `garage` CLI calls to the same RPC host. Do not use the
|
||||
`garage` CLI to connect to individual nodes to send them each a piece of the
|
||||
layout changes you are making, as the changes propagate asynchronously
|
||||
between nodes and might not all be taken into account at the time when the
|
||||
new layout is applied.
|
||||
|
||||
- **Only call `garage layout apply` once**, and call it **strictly after** all
|
||||
of the `layout assign` and `layout remove` commands have returned.
|
||||
@@ -0,0 +1,105 @@
|
||||
# S3 compatibility target
|
||||
|
||||
If there is a specific S3 functionnality you have a need for, feel free to open
|
||||
a PR to put the corresponding endpoints higher in the list. Please explain
|
||||
your motivations for doing so in the PR message.
|
||||
|
||||
| Priority | Endpoints |
|
||||
| -------------------------- | --------- |
|
||||
| **S-tier** (high priority) | |
|
||||
| | HeadBucket |
|
||||
| | GetBucketLocation |
|
||||
| | *CreateBucket* |
|
||||
| | *DeleteBucket* |
|
||||
| | ListBuckets |
|
||||
| | ListObjects |
|
||||
| | ListObjectsV2 |
|
||||
| | HeadObject |
|
||||
| | GetObject |
|
||||
| | PutObject |
|
||||
| | CopyObject |
|
||||
| | DeleteObject |
|
||||
| | DeleteObjects |
|
||||
| | CreateMultipartUpload |
|
||||
| | CompleteMultipartUpload |
|
||||
| | AbortMultipartUpload |
|
||||
| | UploadPart |
|
||||
| | *ListMultipartUploads* |
|
||||
| | *ListParts* |
|
||||
| **A-tier** (will implement) | |
|
||||
| | *GetBucketCors* |
|
||||
| | *PutBucketCors* |
|
||||
| | *DeleteBucketCors* |
|
||||
| | *UploadPartCopy* |
|
||||
| | *GetBucketWebsite* |
|
||||
| | *PutBucketWebsite* |
|
||||
| | *DeleteBucketWebsite* |
|
||||
| ~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
||||
| **B-tier** | |
|
||||
| | GetBucketAcl |
|
||||
| | PutBucketAcl |
|
||||
| | GetObjectLockConfiguration |
|
||||
| | PutObjectLockConfiguration |
|
||||
| | GetObjectRetention |
|
||||
| | PutObjectRetention |
|
||||
| | GetObjectLegalHold |
|
||||
| | PutObjectLegalHold |
|
||||
| **C-tier** | |
|
||||
| | GetBucketVersioning |
|
||||
| | PutBucketVersioning |
|
||||
| | ListObjectVersions |
|
||||
| | GetObjectAcl |
|
||||
| | PutObjectAcl |
|
||||
| **garbage-tier** | |
|
||||
| | DeleteBucketEncryption |
|
||||
| | DeleteBucketAnalyticsConfiguration |
|
||||
| | DeleteBucketIntelligentTieringConfiguration |
|
||||
| | DeleteBucketInventoryConfiguration |
|
||||
| | DeleteBucketLifecycle |
|
||||
| | DeleteBucketMetricsConfiguration |
|
||||
| | DeleteBucketOwnershipControls |
|
||||
| | DeleteBucketPolicy |
|
||||
| | DeleteBucketReplication |
|
||||
| | DeleteBucketTagging |
|
||||
| | DeleteObjectTagging |
|
||||
| | DeletePublicAccessBlock |
|
||||
| | GetBucketAccelerateConfiguration |
|
||||
| | GetBucketAnalyticsConfiguration |
|
||||
| | GetBucketEncryption |
|
||||
| | GetBucketIntelligentTieringConfiguration |
|
||||
| | GetBucketInventoryConfiguration |
|
||||
| | GetBucketLifecycleConfiguration |
|
||||
| | GetBucketLogging |
|
||||
| | GetBucketMetricsConfiguration |
|
||||
| | GetBucketNotificationConfiguration |
|
||||
| | GetBucketOwnershipControls |
|
||||
| | GetBucketPolicy |
|
||||
| | GetBucketPolicyStatus |
|
||||
| | GetBucketReplication |
|
||||
| | GetBucketRequestPayment |
|
||||
| | GetBucketTagging |
|
||||
| | GetObjectTagging |
|
||||
| | GetObjectTorrent |
|
||||
| | GetPublicAccessBlock |
|
||||
| | ListBucketAnalyticsConfigurations |
|
||||
| | ListBucketIntelligentTieringConfigurations |
|
||||
| | ListBucketInventoryConfigurations |
|
||||
| | ListBucketMetricsConfigurations |
|
||||
| | PutBucketAccelerateConfiguration |
|
||||
| | PutBucketAnalyticsConfiguration |
|
||||
| | PutBucketEncryption |
|
||||
| | PutBucketIntelligentTieringConfiguration |
|
||||
| | PutBucketInventoryConfiguration |
|
||||
| | PutBucketLifecycleConfiguration |
|
||||
| | PutBucketLogging |
|
||||
| | PutBucketMetricsConfiguration |
|
||||
| | PutBucketNotificationConfiguration |
|
||||
| | PutBucketOwnershipControls |
|
||||
| | PutBucketPolicy |
|
||||
| | PutBucketReplication |
|
||||
| | PutBucketRequestPayment |
|
||||
| | PutBucketTagging |
|
||||
| | PutObjectTagging |
|
||||
| | PutPublicAccessBlock |
|
||||
| | RestoreObject |
|
||||
| | SelectObjectContent |
|
||||
@@ -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,5 +1,7 @@
|
||||
# Load Balancing Data (planned for version 0.2)
|
||||
|
||||
**This is being yet improved in release 0.5. The working document has not been updated yet, it still only applies to Garage 0.2 through 0.4.**
|
||||
|
||||
I have conducted a quick study of different methods to load-balance data over different Garage nodes using consistent hashing.
|
||||
|
||||
## Requirements
|
||||
|
||||
-83
@@ -1,83 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -xe
|
||||
|
||||
cd $(dirname $0)
|
||||
|
||||
mkdir -p pki
|
||||
cd pki
|
||||
|
||||
# Create a certificate authority that both the client side and the server side of
|
||||
# the RPC protocol will use to authenticate the other side.
|
||||
if [ ! -f garage-ca.key ]; then
|
||||
echo "Generating Garage CA keys..."
|
||||
openssl genpkey -algorithm ED25519 -out garage-ca.key
|
||||
openssl req -x509 -new -nodes -key garage-ca.key -sha256 -days 3650 -out garage-ca.crt -subj "/C=FR/O=Garage"
|
||||
fi
|
||||
|
||||
|
||||
# Generate a certificate that can be used either as a server certificate
|
||||
# or a client certificate. This is what the RPC client and server will use
|
||||
# to prove that they are authenticated by the CA.
|
||||
if [ ! -f garage.crt ]; then
|
||||
echo "Generating Garage agent keys..."
|
||||
if [ ! -f garage.key ]; then
|
||||
openssl genpkey -algorithm ED25519 -out garage.key
|
||||
fi
|
||||
openssl req -new -sha256 -key garage.key -subj "/C=FR/O=Garage/CN=garage" \
|
||||
-out garage.csr
|
||||
openssl req -in garage.csr -noout -text
|
||||
openssl x509 -req -in garage.csr \
|
||||
-extensions v3_req \
|
||||
-extfile <(cat <<EOF
|
||||
[req]
|
||||
distinguished_name = req_distinguished_name
|
||||
req_extensions = v3_req
|
||||
prompt = no
|
||||
|
||||
[req_distinguished_name]
|
||||
C = FR
|
||||
O = Garage
|
||||
CN = garage
|
||||
|
||||
[v3_req]
|
||||
keyUsage = keyEncipherment, dataEncipherment
|
||||
extendedKeyUsage = serverAuth, clientAuth
|
||||
subjectAltName = @alt_names
|
||||
[alt_names]
|
||||
DNS.1 = garage
|
||||
EOF
|
||||
) \
|
||||
-CA garage-ca.crt -CAkey garage-ca.key -CAcreateserial \
|
||||
-out garage.crt -days 365
|
||||
fi
|
||||
|
||||
# Client-only certificate used for the CLI
|
||||
if [ ! -f garage-client.crt ]; then
|
||||
echo "Generating Garage client keys..."
|
||||
if [ ! -f garage-client.key ]; then
|
||||
openssl genpkey -algorithm ED25519 -out garage-client.key
|
||||
fi
|
||||
openssl req -new -sha256 -key garage-client.key -subj "/C=FR/O=Garage" \
|
||||
-out garage-client.csr
|
||||
openssl req -in garage-client.csr -noout -text
|
||||
openssl x509 -req -in garage-client.csr \
|
||||
-extensions v3_req \
|
||||
-extfile <(cat <<EOF
|
||||
[req]
|
||||
distinguished_name = req_distinguished_name
|
||||
req_extensions = v3_req
|
||||
prompt = no
|
||||
|
||||
[req_distinguished_name]
|
||||
C = FR
|
||||
O = Garage
|
||||
|
||||
[v3_req]
|
||||
keyUsage = keyEncipherment, dataEncipherment
|
||||
extendedKeyUsage = clientAuth
|
||||
EOF
|
||||
) \
|
||||
-CA garage-ca.crt -CAkey garage-ca.key -CAcreateserial \
|
||||
-out garage-client.crt -days 365
|
||||
fi
|
||||
@@ -47,6 +47,10 @@ EOF
|
||||
|
||||
echo -en "$LABEL configuration written to $CONF_PATH\n"
|
||||
|
||||
(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
|
||||
|
||||
if [ -z "$SKIP_HTTPS" ]; then
|
||||
echo -en "$LABEL Starting dummy HTTPS reverse proxy\n"
|
||||
mkdir -p /tmp/garagessl
|
||||
@@ -62,14 +66,10 @@ if [ -z "$SKIP_HTTPS" ]; then
|
||||
socat openssl-listen:4443,reuseaddr,fork,cert=/tmp/garagessl/test.pem,verify=0 tcp4-connect:localhost:3911 &
|
||||
fi
|
||||
|
||||
(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)
|
||||
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
|
||||
|
||||
@@ -25,6 +25,7 @@ garage -c /tmp/config.1.toml status \
|
||||
| grep 'NO ROLE' \
|
||||
| grep -Po '^[0-9a-f]+' \
|
||||
| while read id; do
|
||||
garage -c /tmp/config.1.toml node configure -z dc1 -c 1 $id
|
||||
garage -c /tmp/config.1.toml layout assign $id -z dc1 -c 1
|
||||
done
|
||||
|
||||
garage -c /tmp/config.1.toml layout apply --version 1
|
||||
|
||||
+18
-3
@@ -116,15 +116,30 @@ if [ -z "$SKIP_AWS" ]; then
|
||||
echo "🧪 Website Testing"
|
||||
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 ]
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3921/ ` == 404 ]
|
||||
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 ]
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3921/ ` == 200 ]
|
||||
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 ]
|
||||
[ `curl -s -o /dev/null -w "%{http_code}" --header "Host: eprouvette.garage.tld" http://127.0.0.1:3921/ ` == 404 ]
|
||||
aws s3 rm s3://eprouvette/index.html
|
||||
rm /tmp/garage-index.html
|
||||
fi
|
||||
|
||||
if [ -z "$SKIP_AWS" ]; then
|
||||
echo "🪣 Test bucket logic "
|
||||
AWS_ACCESS_KEY_ID=`cat /tmp/garage.s3 |cut -d' ' -f1`
|
||||
[ $(aws s3 ls | wc -l) == 1 ]
|
||||
garage -c /tmp/config.1.toml bucket create seau
|
||||
garage -c /tmp/config.1.toml bucket allow --read seau --key $AWS_ACCESS_KEY_ID
|
||||
[ $(aws s3 ls | wc -l) == 2 ]
|
||||
garage -c /tmp/config.1.toml bucket deny --read seau --key $AWS_ACCESS_KEY_ID
|
||||
[ $(aws s3 ls | wc -l) == 1 ]
|
||||
garage -c /tmp/config.1.toml bucket allow --read seau --key $AWS_ACCESS_KEY_ID
|
||||
[ $(aws s3 ls | wc -l) == 2 ]
|
||||
garage -c /tmp/config.1.toml bucket delete --yes seau
|
||||
[ $(aws s3 ls | wc -l) == 1 ]
|
||||
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`
|
||||
|
||||
+6
-4
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_api"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "S3 API server crate for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
@@ -13,9 +14,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.4.0", path = "../model" }
|
||||
garage_table = { version = "0.4.0", path = "../table" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
garage_model = { version = "0.5.0", path = "../model" }
|
||||
garage_table = { version = "0.5.0", path = "../table" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
|
||||
base64 = "0.13"
|
||||
bytes = "1.0"
|
||||
@@ -24,6 +25,7 @@ crypto-mac = "0.10"
|
||||
err-derive = "0.3"
|
||||
hex = "0.4"
|
||||
hmac = "0.10"
|
||||
idna = "0.2"
|
||||
log = "0.4"
|
||||
md-5 = "0.9"
|
||||
sha2 = "0.9"
|
||||
|
||||
+205
-161
@@ -1,11 +1,11 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::future::Future;
|
||||
use hyper::header;
|
||||
use hyper::server::conn::AddrStream;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, Request, Response, Server};
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
|
||||
use garage_util::error::Error as GarageError;
|
||||
|
||||
@@ -14,12 +14,14 @@ use garage_model::garage::Garage;
|
||||
use crate::error::*;
|
||||
use crate::signature::check_signature;
|
||||
|
||||
use crate::helpers::*;
|
||||
use crate::s3_bucket::*;
|
||||
use crate::s3_copy::*;
|
||||
use crate::s3_delete::*;
|
||||
use crate::s3_get::*;
|
||||
use crate::s3_list::*;
|
||||
use crate::s3_put::*;
|
||||
use crate::s3_router::{Authorization, Endpoint};
|
||||
|
||||
/// Run the S3 API server
|
||||
pub async fn run_api_server(
|
||||
@@ -63,10 +65,15 @@ async fn handler(
|
||||
}
|
||||
Err(e) => {
|
||||
let body: Body = Body::from(e.aws_xml(&garage.config.s3_api.s3_region, uri.path()));
|
||||
let http_error = Response::builder()
|
||||
let mut http_error_builder = Response::builder()
|
||||
.status(e.http_status_code())
|
||||
.header("Content-Type", "application/xml")
|
||||
.body(body)?;
|
||||
.header("Content-Type", "application/xml");
|
||||
|
||||
if let Some(header_map) = http_error_builder.headers_mut() {
|
||||
e.add_headers(header_map)
|
||||
}
|
||||
|
||||
let http_error = http_error_builder.body(body)?;
|
||||
|
||||
if e.http_status_code().is_server_error() {
|
||||
warn!("Response: error {}, {}", e.http_status_code(), e);
|
||||
@@ -79,179 +86,197 @@ async fn handler(
|
||||
}
|
||||
|
||||
async fn handler_inner(garage: Arc<Garage>, req: Request<Body>) -> Result<Response<Body>, Error> {
|
||||
let path = req.uri().path().to_string();
|
||||
let path = percent_encoding::percent_decode_str(&path).decode_utf8()?;
|
||||
let (api_key, content_sha256) = check_signature(&garage, &req).await?;
|
||||
if path == "/" {
|
||||
return handle_list_buckets(&api_key);
|
||||
}
|
||||
|
||||
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),
|
||||
let authority = req
|
||||
.headers()
|
||||
.get(header::HOST)
|
||||
.ok_or_else(|| Error::BadRequest("HOST header required".to_owned()))?
|
||||
.to_str()?;
|
||||
|
||||
let host = authority_to_host(authority)?;
|
||||
|
||||
let bucket = garage
|
||||
.config
|
||||
.s3_api
|
||||
.root_domain
|
||||
.as_ref()
|
||||
.and_then(|root_domain| host_to_bucket(&host, root_domain));
|
||||
|
||||
let endpoint = Endpoint::from_request(&req, bucket.map(ToOwned::to_owned))?;
|
||||
let allowed = match endpoint.authorization_type() {
|
||||
Authorization::None => true,
|
||||
Authorization::Read(bucket) => api_key.allow_read(bucket),
|
||||
Authorization::Write(bucket) => api_key.allow_write(bucket),
|
||||
};
|
||||
|
||||
if !allowed {
|
||||
return Err(Error::Forbidden(
|
||||
"Operation is not allowed for this key.".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut params = HashMap::new();
|
||||
if let Some(query) = req.uri().query() {
|
||||
let query_pairs = url::form_urlencoded::parse(query.as_bytes());
|
||||
for (key, val) in query_pairs {
|
||||
params.insert(key.to_lowercase(), val.to_string());
|
||||
match endpoint {
|
||||
Endpoint::ListBuckets => handle_list_buckets(&api_key),
|
||||
Endpoint::HeadObject { bucket, key, .. } => handle_head(garage, &req, &bucket, &key).await,
|
||||
Endpoint::GetObject { bucket, key, .. } => handle_get(garage, &req, &bucket, &key).await,
|
||||
Endpoint::UploadPart {
|
||||
bucket,
|
||||
key,
|
||||
part_number,
|
||||
upload_id,
|
||||
} => {
|
||||
handle_put_part(
|
||||
garage,
|
||||
req,
|
||||
&bucket,
|
||||
&key,
|
||||
part_number,
|
||||
&upload_id,
|
||||
content_sha256,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(key) = key {
|
||||
match *req.method() {
|
||||
Method::HEAD => {
|
||||
// HeadObject query
|
||||
Ok(handle_head(garage, &req, bucket, key).await?)
|
||||
Endpoint::CopyObject { bucket, key } => {
|
||||
let copy_source = req.headers().get("x-amz-copy-source").unwrap().to_str()?;
|
||||
let copy_source = percent_encoding::percent_decode_str(copy_source).decode_utf8()?;
|
||||
let (source_bucket, source_key) = parse_bucket_key(©_source, None)?;
|
||||
if !api_key.allow_read(source_bucket) {
|
||||
return Err(Error::Forbidden(format!(
|
||||
"Reading from bucket {} not allowed for this key",
|
||||
source_bucket
|
||||
)));
|
||||
}
|
||||
Method::GET => {
|
||||
// GetObject query
|
||||
Ok(handle_get(garage, &req, bucket, key).await?)
|
||||
}
|
||||
Method::PUT => {
|
||||
if params.contains_key(&"partnumber".to_string())
|
||||
&& params.contains_key(&"uploadid".to_string())
|
||||
{
|
||||
// UploadPart query
|
||||
let part_number = params.get("partnumber").unwrap();
|
||||
let upload_id = params.get("uploadid").unwrap();
|
||||
Ok(handle_put_part(
|
||||
garage,
|
||||
req,
|
||||
let source_key = source_key.ok_or_bad_request("No source key specified")?;
|
||||
handle_copy(garage, &req, &bucket, &key, source_bucket, source_key).await
|
||||
}
|
||||
Endpoint::PutObject { bucket, key } => {
|
||||
handle_put(garage, req, &bucket, &key, content_sha256).await
|
||||
}
|
||||
Endpoint::AbortMultipartUpload {
|
||||
bucket,
|
||||
key,
|
||||
upload_id,
|
||||
} => handle_abort_multipart_upload(garage, &bucket, &key, &upload_id).await,
|
||||
Endpoint::DeleteObject { bucket, key, .. } => handle_delete(garage, &bucket, &key).await,
|
||||
Endpoint::CreateMultipartUpload { bucket, key } => {
|
||||
handle_create_multipart_upload(garage, &req, &bucket, &key).await
|
||||
}
|
||||
Endpoint::CompleteMultipartUpload {
|
||||
bucket,
|
||||
key,
|
||||
upload_id,
|
||||
} => {
|
||||
handle_complete_multipart_upload(garage, req, &bucket, &key, &upload_id, content_sha256)
|
||||
.await
|
||||
}
|
||||
Endpoint::CreateBucket { bucket } => {
|
||||
debug!(
|
||||
"Body: {}",
|
||||
std::str::from_utf8(&hyper::body::to_bytes(req.into_body()).await?)
|
||||
.unwrap_or("<invalid utf8>")
|
||||
);
|
||||
let empty_body: Body = Body::from(vec![]);
|
||||
let response = Response::builder()
|
||||
.header("Location", format!("/{}", bucket))
|
||||
.body(empty_body)
|
||||
.unwrap();
|
||||
Ok(response)
|
||||
}
|
||||
Endpoint::HeadBucket { .. } => {
|
||||
let empty_body: Body = Body::from(vec![]);
|
||||
let response = Response::builder().body(empty_body).unwrap();
|
||||
Ok(response)
|
||||
}
|
||||
Endpoint::DeleteBucket { .. } => Err(Error::Forbidden(
|
||||
"Cannot delete buckets using S3 api, please talk to Garage directly".into(),
|
||||
)),
|
||||
Endpoint::GetBucketLocation { .. } => handle_get_bucket_location(garage),
|
||||
Endpoint::GetBucketVersioning { .. } => handle_get_bucket_versioning(),
|
||||
Endpoint::ListObjects {
|
||||
bucket,
|
||||
delimiter,
|
||||
encoding_type,
|
||||
marker,
|
||||
max_keys,
|
||||
prefix,
|
||||
} => {
|
||||
handle_list(
|
||||
garage,
|
||||
&ListObjectsQuery {
|
||||
is_v2: false,
|
||||
bucket,
|
||||
delimiter: delimiter.map(|d| d.to_string()),
|
||||
max_keys: max_keys.unwrap_or(1000),
|
||||
prefix: prefix.unwrap_or_default(),
|
||||
marker,
|
||||
continuation_token: None,
|
||||
start_after: None,
|
||||
urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
Endpoint::ListObjectsV2 {
|
||||
bucket,
|
||||
delimiter,
|
||||
encoding_type,
|
||||
max_keys,
|
||||
prefix,
|
||||
continuation_token,
|
||||
start_after,
|
||||
list_type,
|
||||
..
|
||||
} => {
|
||||
if list_type == "2" {
|
||||
handle_list(
|
||||
garage,
|
||||
&ListObjectsQuery {
|
||||
is_v2: true,
|
||||
bucket,
|
||||
key,
|
||||
part_number,
|
||||
upload_id,
|
||||
content_sha256,
|
||||
)
|
||||
.await?)
|
||||
} else if req.headers().contains_key("x-amz-copy-source") {
|
||||
// CopyObject query
|
||||
let copy_source = req.headers().get("x-amz-copy-source").unwrap().to_str()?;
|
||||
let copy_source =
|
||||
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) {
|
||||
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?)
|
||||
} else {
|
||||
// PutObject query
|
||||
Ok(handle_put(garage, req, bucket, key, content_sha256).await?)
|
||||
}
|
||||
delimiter: delimiter.map(|d| d.to_string()),
|
||||
max_keys: max_keys.unwrap_or(1000),
|
||||
prefix: prefix.unwrap_or_default(),
|
||||
marker: None,
|
||||
continuation_token,
|
||||
start_after,
|
||||
urlencode_resp: encoding_type.map(|e| e == "url").unwrap_or(false),
|
||||
},
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
Err(Error::BadRequest(format!(
|
||||
"Invalid endpoint: list-type={}",
|
||||
list_type
|
||||
)))
|
||||
}
|
||||
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?)
|
||||
} else {
|
||||
// DeleteObject query
|
||||
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?)
|
||||
} 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,
|
||||
upload_id,
|
||||
content_sha256,
|
||||
)
|
||||
.await?)
|
||||
} else {
|
||||
Err(Error::BadRequest(
|
||||
"Not a CreateMultipartUpload call, what is it?".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
_ => Err(Error::BadRequest("Invalid method".to_string())),
|
||||
}
|
||||
} else {
|
||||
match *req.method() {
|
||||
Method::PUT => {
|
||||
// CreateBucket
|
||||
// If we're here, the bucket already exists, so just answer ok
|
||||
debug!(
|
||||
"Body: {}",
|
||||
std::str::from_utf8(&hyper::body::to_bytes(req.into_body()).await?)
|
||||
.unwrap_or("<invalid utf8>")
|
||||
);
|
||||
let empty_body: Body = Body::from(vec![]);
|
||||
let response = Response::builder()
|
||||
.header("Location", format!("/{}", bucket))
|
||||
.body(empty_body)
|
||||
.unwrap();
|
||||
Ok(response)
|
||||
}
|
||||
Method::HEAD => {
|
||||
// HeadBucket
|
||||
let empty_body: Body = Body::from(vec![]);
|
||||
let response = Response::builder().body(empty_body).unwrap();
|
||||
Ok(response)
|
||||
}
|
||||
Method::DELETE => {
|
||||
// DeleteBucket query
|
||||
Err(Error::Forbidden(
|
||||
"Cannot delete buckets using S3 api, please talk to Garage directly".into(),
|
||||
))
|
||||
}
|
||||
Method::GET => {
|
||||
if params.contains_key("location") {
|
||||
// GetBucketLocation call
|
||||
Ok(handle_get_bucket_location(garage)?)
|
||||
} else if params.contains_key("versioning") {
|
||||
// GetBucketVersioning
|
||||
Ok(handle_get_bucket_versioning()?)
|
||||
} else {
|
||||
// ListObjects or ListObjectsV2 query
|
||||
let q = parse_list_objects_query(bucket, ¶ms)?;
|
||||
Ok(handle_list(garage, &q).await?)
|
||||
}
|
||||
}
|
||||
Method::POST => {
|
||||
if params.contains_key(&"delete".to_string()) {
|
||||
// DeleteObjects
|
||||
Ok(handle_delete_objects(garage, bucket, req, content_sha256).await?)
|
||||
} else {
|
||||
debug!(
|
||||
"Body: {}",
|
||||
std::str::from_utf8(&hyper::body::to_bytes(req.into_body()).await?)
|
||||
.unwrap_or("<invalid utf8>")
|
||||
);
|
||||
Err(Error::BadRequest("Unsupported call".to_string()))
|
||||
}
|
||||
}
|
||||
_ => Err(Error::BadRequest("Invalid method".to_string())),
|
||||
Endpoint::DeleteObjects { bucket } => {
|
||||
handle_delete_objects(garage, &bucket, req, content_sha256).await
|
||||
}
|
||||
endpoint => Err(Error::NotImplemented(endpoint.name().to_owned())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the bucket name and the key name from an HTTP path
|
||||
/// Extract the bucket name and the key name from an HTTP path and possibly a bucket provided in
|
||||
/// the host header of the request
|
||||
///
|
||||
/// S3 internally manages only buckets and keys. This function splits
|
||||
/// an HTTP path to get the corresponding bucket name and key.
|
||||
fn parse_bucket_key(path: &str) -> Result<(&str, Option<&str>), Error> {
|
||||
fn parse_bucket_key<'a>(
|
||||
path: &'a str,
|
||||
host_bucket: Option<&'a str>,
|
||||
) -> Result<(&'a str, Option<&'a str>), Error> {
|
||||
let path = path.trim_start_matches('/');
|
||||
|
||||
if let Some(bucket) = host_bucket {
|
||||
if !path.is_empty() {
|
||||
return Ok((bucket, Some(path)));
|
||||
} else {
|
||||
return Ok((bucket, None));
|
||||
}
|
||||
}
|
||||
|
||||
let (bucket, key) = match path.find('/') {
|
||||
Some(i) => {
|
||||
let key = &path[i + 1..];
|
||||
@@ -275,7 +300,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parse_bucket_containing_a_key() -> Result<(), Error> {
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket/a/super/file.jpg")?;
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket/a/super/file.jpg", None)?;
|
||||
assert_eq!(bucket, "my_bucket");
|
||||
assert_eq!(key.expect("key must be set"), "a/super/file.jpg");
|
||||
Ok(())
|
||||
@@ -283,10 +308,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parse_bucket_containing_no_key() -> Result<(), Error> {
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket/")?;
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket/", None)?;
|
||||
assert_eq!(bucket, "my_bucket");
|
||||
assert!(key.is_none());
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket")?;
|
||||
let (bucket, key) = parse_bucket_key("/my_bucket", None)?;
|
||||
assert_eq!(bucket, "my_bucket");
|
||||
assert!(key.is_none());
|
||||
Ok(())
|
||||
@@ -294,11 +319,30 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parse_bucket_containing_no_bucket() {
|
||||
let parsed = parse_bucket_key("");
|
||||
let parsed = parse_bucket_key("", None);
|
||||
assert!(parsed.is_err());
|
||||
let parsed = parse_bucket_key("/");
|
||||
let parsed = parse_bucket_key("/", None);
|
||||
assert!(parsed.is_err());
|
||||
let parsed = parse_bucket_key("////");
|
||||
let parsed = parse_bucket_key("////", None);
|
||||
assert!(parsed.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_bucket_with_vhost_and_key() -> Result<(), Error> {
|
||||
let (bucket, key) = parse_bucket_key("/a/super/file.jpg", Some("my-bucket"))?;
|
||||
assert_eq!(bucket, "my-bucket");
|
||||
assert_eq!(key.expect("key must be set"), "a/super/file.jpg");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_bucket_with_vhost_no_key() -> Result<(), Error> {
|
||||
let (bucket, key) = parse_bucket_key("", Some("my-bucket"))?;
|
||||
assert_eq!(bucket, "my-bucket");
|
||||
assert!(key.is_none());
|
||||
let (bucket, key) = parse_bucket_key("/", Some("my-bucket"))?;
|
||||
assert_eq!(bucket, "my-bucket");
|
||||
assert!(key.is_none());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
+27
-2
@@ -1,5 +1,8 @@
|
||||
use std::convert::TryInto;
|
||||
|
||||
use err_derive::Error;
|
||||
use hyper::StatusCode;
|
||||
use hyper::header::HeaderValue;
|
||||
use hyper::{HeaderMap, StatusCode};
|
||||
|
||||
use garage_util::error::Error as GarageError;
|
||||
|
||||
@@ -57,11 +60,15 @@ pub enum Error {
|
||||
|
||||
/// The client sent a range header with invalid value
|
||||
#[error(display = "Invalid HTTP range: {:?}", _0)]
|
||||
InvalidRange(#[error(from)] http_range::HttpRangeParseError),
|
||||
InvalidRange(#[error(from)] (http_range::HttpRangeParseError, u64)),
|
||||
|
||||
/// The client sent an invalid request
|
||||
#[error(display = "Bad request: {}", _0)]
|
||||
BadRequest(String),
|
||||
|
||||
/// The client sent a request for an action not supported by garage
|
||||
#[error(display = "Unimplemented action: {}", _0)]
|
||||
NotImplemented(String),
|
||||
}
|
||||
|
||||
impl From<roxmltree::Error> for Error {
|
||||
@@ -90,6 +97,8 @@ impl Error {
|
||||
Error::InternalError(_) | Error::Hyper(_) | Error::Http(_) => {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
Error::InvalidRange(_) => StatusCode::RANGE_NOT_SATISFIABLE,
|
||||
Error::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED,
|
||||
_ => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
@@ -127,6 +136,22 @@ impl Error {
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_headers(&self, header_map: &mut HeaderMap<HeaderValue>) {
|
||||
use hyper::header;
|
||||
#[allow(clippy::single_match)]
|
||||
match self {
|
||||
Error::InvalidRange((_, len)) => {
|
||||
header_map.append(
|
||||
header::CONTENT_RANGE,
|
||||
format!("bytes */{}", len)
|
||||
.try_into()
|
||||
.expect("header value only contain ascii"),
|
||||
);
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait to map error to the Bad Request error code
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
use crate::Error;
|
||||
use idna::domain_to_unicode;
|
||||
|
||||
/// Host to bucket
|
||||
///
|
||||
/// Convert a host, like "bucket.garage-site.tld" to the corresponding bucket "bucket",
|
||||
/// considering that ".garage-site.tld" is the "root domain". For domains not matching
|
||||
/// the provided root domain, no bucket is returned
|
||||
/// This behavior has been chosen to follow AWS S3 semantic.
|
||||
pub fn host_to_bucket<'a>(host: &'a str, root: &str) -> Option<&'a str> {
|
||||
let root = root.trim_start_matches('.');
|
||||
let label_root = root.chars().filter(|c| c == &'.').count() + 1;
|
||||
let root = root.rsplit('.');
|
||||
let mut host = host.rsplitn(label_root + 1, '.');
|
||||
for root_part in root {
|
||||
let host_part = host.next()?;
|
||||
if root_part != host_part {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
host.next()
|
||||
}
|
||||
|
||||
/// Extract host from the authority section given by the HTTP host header
|
||||
///
|
||||
/// The HTTP host contains both a host and a port.
|
||||
/// Extracting the port is more complex than just finding the colon (:) symbol due to IPv6
|
||||
/// We do not use the collect pattern as there is no way in std rust to collect over a stack allocated value
|
||||
/// check here: <https://docs.rs/collect_slice/1.2.0/collect_slice/>
|
||||
pub fn authority_to_host(authority: &str) -> Result<String, Error> {
|
||||
let mut iter = authority.chars().enumerate();
|
||||
let (_, first_char) = iter
|
||||
.next()
|
||||
.ok_or_else(|| Error::BadRequest("Authority is empty".to_string()))?;
|
||||
|
||||
let split = match first_char {
|
||||
'[' => {
|
||||
let mut iter = iter.skip_while(|(_, c)| c != &']');
|
||||
match iter.next() {
|
||||
Some((_, ']')) => iter.next(),
|
||||
_ => {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Authority {} has an illegal format",
|
||||
authority
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => iter.find(|(_, c)| *c == ':'),
|
||||
};
|
||||
|
||||
let authority = match split {
|
||||
Some((i, ':')) => Ok(&authority[..i]),
|
||||
None => Ok(authority),
|
||||
Some((_, _)) => Err(Error::BadRequest(format!(
|
||||
"Authority {} has an illegal format",
|
||||
authority
|
||||
))),
|
||||
};
|
||||
authority.map(|h| domain_to_unicode(h).0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn authority_to_host_with_port() -> Result<(), Error> {
|
||||
let domain = authority_to_host("[::1]:3902")?;
|
||||
assert_eq!(domain, "[::1]");
|
||||
let domain2 = authority_to_host("garage.tld:65200")?;
|
||||
assert_eq!(domain2, "garage.tld");
|
||||
let domain3 = authority_to_host("127.0.0.1:80")?;
|
||||
assert_eq!(domain3, "127.0.0.1");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authority_to_host_without_port() -> Result<(), Error> {
|
||||
let domain = authority_to_host("[::1]")?;
|
||||
assert_eq!(domain, "[::1]");
|
||||
let domain2 = authority_to_host("garage.tld")?;
|
||||
assert_eq!(domain2, "garage.tld");
|
||||
let domain3 = authority_to_host("127.0.0.1")?;
|
||||
assert_eq!(domain3, "127.0.0.1");
|
||||
assert!(authority_to_host("[").is_err());
|
||||
assert!(authority_to_host("[hello").is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_to_bucket_test() {
|
||||
assert_eq!(
|
||||
host_to_bucket("john.doe.garage.tld", ".garage.tld").unwrap(),
|
||||
"john.doe"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
host_to_bucket("john.doe.garage.tld", "garage.tld").unwrap(),
|
||||
"john.doe"
|
||||
);
|
||||
|
||||
assert_eq!(host_to_bucket("john.doe.com", "garage.tld"), None);
|
||||
|
||||
assert_eq!(host_to_bucket("john.doe.com", ".garage.tld"), None);
|
||||
|
||||
assert_eq!(host_to_bucket("garage.tld", "garage.tld"), None);
|
||||
|
||||
assert_eq!(host_to_bucket("garage.tld", ".garage.tld"), None);
|
||||
|
||||
assert_eq!(host_to_bucket("not-garage.tld", "garage.tld"), None);
|
||||
assert_eq!(host_to_bucket("not-garage.tld", ".garage.tld"), None);
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,12 @@ pub use api_server::run_api_server;
|
||||
|
||||
mod signature;
|
||||
|
||||
pub mod helpers;
|
||||
mod s3_bucket;
|
||||
mod s3_copy;
|
||||
mod s3_delete;
|
||||
pub mod s3_get;
|
||||
mod s3_list;
|
||||
mod s3_put;
|
||||
mod s3_router;
|
||||
mod s3_xml;
|
||||
|
||||
@@ -45,6 +45,7 @@ pub fn handle_list_buckets(api_key: &Key) -> Result<Response<Body>, Error> {
|
||||
.authorized_buckets
|
||||
.items()
|
||||
.iter()
|
||||
.filter(|(_, _, perms)| perms.allow_read || perms.allow_write)
|
||||
.map(|(name, ts, _)| s3_xml::Bucket {
|
||||
creation_date: s3_xml::Value(msec_to_rfc3339(*ts)),
|
||||
name: s3_xml::Value(name.to_string()),
|
||||
|
||||
+5
-8
@@ -156,11 +156,12 @@ pub async fn handle_get(
|
||||
let range = match req.headers().get("range") {
|
||||
Some(range) => {
|
||||
let range_str = range.to_str()?;
|
||||
let mut ranges = http_range::HttpRange::parse(range_str, last_v_meta.size)?;
|
||||
let mut ranges = http_range::HttpRange::parse(range_str, last_v_meta.size)
|
||||
.map_err(|e| (e, last_v_meta.size))?;
|
||||
if ranges.len() > 1 {
|
||||
return Err(Error::BadRequest(
|
||||
"Multiple ranges not supported".to_string(),
|
||||
));
|
||||
// garage does not support multi-range requests yet, so we respond with the entire
|
||||
// object when multiple ranges are requested
|
||||
None
|
||||
} else {
|
||||
ranges.pop()
|
||||
}
|
||||
@@ -235,10 +236,6 @@ async fn handle_get_range(
|
||||
begin: u64,
|
||||
end: u64,
|
||||
) -> Result<Response<Body>, Error> {
|
||||
if end > version_meta.size {
|
||||
return Err(Error::BadRequest("Range not included in file".to_string()));
|
||||
}
|
||||
|
||||
let resp_builder = object_headers(version, version_meta)
|
||||
.header("Content-Length", format!("{}", end - begin))
|
||||
.header(
|
||||
|
||||
+1
-27
@@ -1,4 +1,4 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use hyper::{Body, Response};
|
||||
@@ -35,32 +35,6 @@ struct ListResultInfo {
|
||||
etag: String,
|
||||
}
|
||||
|
||||
pub fn parse_list_objects_query(
|
||||
bucket: &str,
|
||||
params: &HashMap<String, String>,
|
||||
) -> Result<ListObjectsQuery, Error> {
|
||||
Ok(ListObjectsQuery {
|
||||
is_v2: params.get("list-type").map(|x| x == "2").unwrap_or(false),
|
||||
bucket: bucket.to_string(),
|
||||
delimiter: params.get("delimiter").filter(|x| !x.is_empty()).cloned(),
|
||||
max_keys: params
|
||||
.get("max-keys")
|
||||
.map(|x| {
|
||||
x.parse::<usize>()
|
||||
.ok_or_bad_request("Invalid value for max-keys")
|
||||
})
|
||||
.unwrap_or(Ok(1000))?,
|
||||
prefix: params.get("prefix").cloned().unwrap_or_default(),
|
||||
marker: params.get("marker").cloned(),
|
||||
continuation_token: params.get("continuation-token").cloned(),
|
||||
start_after: params.get("start-after").cloned(),
|
||||
urlencode_resp: params
|
||||
.get("encoding-type")
|
||||
.map(|x| x == "url")
|
||||
.unwrap_or(false),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn handle_list(
|
||||
garage: Arc<Garage>,
|
||||
query: &ListObjectsQuery,
|
||||
|
||||
+1
-6
@@ -354,15 +354,10 @@ pub async fn handle_put_part(
|
||||
req: Request<Body>,
|
||||
bucket: &str,
|
||||
key: &str,
|
||||
part_number_str: &str,
|
||||
part_number: u64,
|
||||
upload_id: &str,
|
||||
content_sha256: Option<Hash>,
|
||||
) -> Result<Response<Body>, Error> {
|
||||
// Check parameters
|
||||
let part_number = part_number_str
|
||||
.parse::<u64>()
|
||||
.ok_or_bad_request("Invalid part number")?;
|
||||
|
||||
let version_uuid = decode_upload_id(upload_id)?;
|
||||
|
||||
let content_md5 = match req.headers().get("content-md5") {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "Garage, an S3-compatible distributed object store for self-hosted deployments"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[[bin]]
|
||||
name = "garage"
|
||||
@@ -14,12 +15,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.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" }
|
||||
garage_api = { version = "0.5.0", path = "../api" }
|
||||
garage_model = { version = "0.5.0", path = "../model" }
|
||||
garage_rpc = { version = "0.5.0", path = "../rpc" }
|
||||
garage_table = { version = "0.5.0", path = "../table" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
garage_web = { version = "0.5.0", path = "../web" }
|
||||
|
||||
bytes = "1.0"
|
||||
git-version = "0.3.4"
|
||||
|
||||
+3
-3
@@ -339,7 +339,7 @@ impl AdminRpcHandler {
|
||||
|
||||
let mut failures = vec![];
|
||||
let ring = self.garage.system.ring.borrow().clone();
|
||||
for node in ring.config.members.keys() {
|
||||
for node in ring.layout.node_ids().iter() {
|
||||
let node = (*node).into();
|
||||
let resp = self
|
||||
.endpoint
|
||||
@@ -383,7 +383,7 @@ impl AdminRpcHandler {
|
||||
let mut ret = String::new();
|
||||
let ring = self.garage.system.ring.borrow().clone();
|
||||
|
||||
for node in ring.config.members.keys() {
|
||||
for node in ring.layout.node_ids().iter() {
|
||||
let mut opt = opt.clone();
|
||||
opt.all_nodes = false;
|
||||
|
||||
@@ -446,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();
|
||||
|
||||
+56
-158
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
|
||||
use garage_util::error::*;
|
||||
|
||||
use garage_rpc::ring::*;
|
||||
use garage_rpc::layout::*;
|
||||
use garage_rpc::system::*;
|
||||
use garage_rpc::*;
|
||||
|
||||
@@ -20,11 +20,8 @@ pub async fn cli_command_dispatch(
|
||||
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::Layout(layout_opt) => {
|
||||
cli_layout_command_dispatch(layout_opt, system_rpc_endpoint, rpc_host).await
|
||||
}
|
||||
Command::Bucket(bo) => {
|
||||
cmd_admin(admin_rpc_endpoint, rpc_host, AdminRpc::BucketOperation(bo)).await
|
||||
@@ -48,56 +45,60 @@ pub async fn cmd_status(rpc_cli: &Endpoint<SystemRpc, ()>, rpc_host: NodeID) ->
|
||||
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))),
|
||||
};
|
||||
let layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
println!("==== HEALTHY NODES ====");
|
||||
let mut healthy_nodes = vec!["ID\tHostname\tAddress\tTag\tZone\tCapacity".to_string()];
|
||||
let mut healthy_nodes = vec!["ID\tHostname\tAddress\tTags\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,
|
||||
));
|
||||
match layout.roles.get(&adv.id) {
|
||||
Some(NodeRoleV(Some(cfg))) => {
|
||||
healthy_nodes.push(format!(
|
||||
"{id:?}\t{host}\t{addr}\t[{tags}]\t{zone}\t{capacity}",
|
||||
id = adv.id,
|
||||
host = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
tags = cfg.tags.join(","),
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
let new_role = match layout.staging.get(&adv.id) {
|
||||
Some(NodeRoleV(Some(_))) => "(pending)",
|
||||
_ => "NO ROLE ASSIGNED",
|
||||
};
|
||||
healthy_nodes.push(format!(
|
||||
"{id:?}\t{h}\t{addr}\t{new_role}",
|
||||
id = adv.id,
|
||||
h = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
new_role = new_role,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
let failure_case_2 = layout
|
||||
.roles
|
||||
.items()
|
||||
.iter()
|
||||
.any(|(id, _)| !status_keys.contains(id));
|
||||
.filter(|(_, _, v)| v.0.is_some())
|
||||
.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()];
|
||||
vec!["ID\tHostname\tAddress\tTags\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) {
|
||||
if let Some(NodeRoleV(Some(cfg))) = layout.roles.get(&adv.id) {
|
||||
failed_nodes.push(format!(
|
||||
"{id:?}\t{host}\t{addr}\t[{tag}]\t{zone}\t{capacity}\t{last_seen}",
|
||||
"{id:?}\t{host}\t{addr}\t[{tags}]\t{zone}\t{capacity}\t{last_seen}",
|
||||
id = adv.id,
|
||||
host = adv.status.hostname,
|
||||
addr = adv.addr,
|
||||
tag = cfg.tag,
|
||||
tags = cfg.tags.join(","),
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
last_seen = adv
|
||||
@@ -107,20 +108,28 @@ pub async fn cmd_status(rpc_cli: &Endpoint<SystemRpc, ()>, rpc_host: NodeID) ->
|
||||
));
|
||||
}
|
||||
}
|
||||
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(),
|
||||
));
|
||||
for (id, _, role_v) in layout.roles.items().iter() {
|
||||
if let NodeRoleV(Some(cfg)) = role_v {
|
||||
if !status_keys.contains(id) {
|
||||
failed_nodes.push(format!(
|
||||
"{id:?}\t??\t??\t[{tags}]\t{zone}\t{capacity}\tnever seen",
|
||||
id = id,
|
||||
tags = cfg.tags.join(","),
|
||||
zone = cfg.zone,
|
||||
capacity = cfg.capacity_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
format_table(failed_nodes);
|
||||
}
|
||||
|
||||
if print_staging_role_changes(&layout) {
|
||||
println!();
|
||||
println!("Please use `garage layout show` to check the proposed new layout and apply it.");
|
||||
println!();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -141,115 +150,6 @@ pub async fn cmd_connect(
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -283,5 +183,3 @@ pub async fn cmd_admin(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- Utility functions ----
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
use garage_util::crdt::Crdt;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::*;
|
||||
|
||||
use garage_rpc::layout::*;
|
||||
use garage_rpc::system::*;
|
||||
use garage_rpc::*;
|
||||
|
||||
use crate::cli::*;
|
||||
|
||||
pub async fn cli_layout_command_dispatch(
|
||||
cmd: LayoutOperation,
|
||||
system_rpc_endpoint: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
) -> Result<(), Error> {
|
||||
match cmd {
|
||||
LayoutOperation::Assign(configure_opt) => {
|
||||
cmd_assign_role(system_rpc_endpoint, rpc_host, configure_opt).await
|
||||
}
|
||||
LayoutOperation::Remove(remove_opt) => {
|
||||
cmd_remove_role(system_rpc_endpoint, rpc_host, remove_opt).await
|
||||
}
|
||||
LayoutOperation::Show => cmd_show_layout(system_rpc_endpoint, rpc_host).await,
|
||||
LayoutOperation::Apply(apply_opt) => {
|
||||
cmd_apply_layout(system_rpc_endpoint, rpc_host, apply_opt).await
|
||||
}
|
||||
LayoutOperation::Revert(revert_opt) => {
|
||||
cmd_revert_layout(system_rpc_endpoint, rpc_host, revert_opt).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn cmd_assign_role(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: AssignRoleOpt,
|
||||
) -> 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 layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
let mut roles = layout.roles.clone();
|
||||
roles.merge(&layout.staging);
|
||||
|
||||
for replaced in args.replace.iter() {
|
||||
let replaced_node = find_matching_node(layout.node_ids().iter().cloned(), replaced)?;
|
||||
match roles.get(&replaced_node) {
|
||||
Some(NodeRoleV(Some(_))) => {
|
||||
layout
|
||||
.staging
|
||||
.merge(&roles.update_mutator(replaced_node, NodeRoleV(None)));
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::Message(format!(
|
||||
"Cannot replace node {:?} as it is not currently in planned layout",
|
||||
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 roles.get(&added_node) {
|
||||
Some(NodeRoleV(Some(old))) => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
None => old.capacity,
|
||||
};
|
||||
let tags = if args.tags.is_empty() {
|
||||
old.tags.clone()
|
||||
} else {
|
||||
args.tags
|
||||
};
|
||||
NodeRole {
|
||||
zone: args.zone.unwrap_or_else(|| old.zone.to_string()),
|
||||
capacity,
|
||||
tags,
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let capacity = match args.capacity {
|
||||
Some(c) => Some(c),
|
||||
None if args.gateway => None,
|
||||
None => return Err(Error::Message(
|
||||
"Please specify a capacity with the -c flag, or set node explicitly as gateway with -g".into())),
|
||||
};
|
||||
NodeRole {
|
||||
zone: args.zone.ok_or("Please specifiy a zone with the -z flag")?,
|
||||
capacity,
|
||||
tags: args.tags,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
layout
|
||||
.staging
|
||||
.merge(&roles.update_mutator(added_node, NodeRoleV(Some(new_entry))));
|
||||
|
||||
send_layout(rpc_cli, rpc_host, layout).await?;
|
||||
|
||||
println!("Role change is staged but not yet commited.");
|
||||
println!("Use `garage layout show` to view staged role changes,");
|
||||
println!("and `garage layout apply` to enact staged changes.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_remove_role(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
args: RemoveRoleOpt,
|
||||
) -> Result<(), Error> {
|
||||
let mut layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
let mut roles = layout.roles.clone();
|
||||
roles.merge(&layout.staging);
|
||||
|
||||
let deleted_node =
|
||||
find_matching_node(roles.items().iter().map(|(id, _, _)| *id), &args.node_id)?;
|
||||
|
||||
layout
|
||||
.staging
|
||||
.merge(&roles.update_mutator(deleted_node, NodeRoleV(None)));
|
||||
|
||||
send_layout(rpc_cli, rpc_host, layout).await?;
|
||||
|
||||
println!("Role removal is staged but not yet commited.");
|
||||
println!("Use `garage layout show` to view staged role changes,");
|
||||
println!("and `garage layout apply` to enact staged changes.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_show_layout(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
) -> Result<(), Error> {
|
||||
let mut layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
println!("==== CURRENT CLUSTER LAYOUT ====");
|
||||
if !print_cluster_layout(&layout) {
|
||||
println!("No nodes currently have a role in the cluster.");
|
||||
println!("See `garage status` to view available nodes.");
|
||||
}
|
||||
println!();
|
||||
println!("Current cluster layout version: {}", layout.version);
|
||||
|
||||
if print_staging_role_changes(&layout) {
|
||||
layout.roles.merge(&layout.staging);
|
||||
|
||||
println!();
|
||||
println!("==== NEW CLUSTER LAYOUT AFTER APPLYING CHANGES ====");
|
||||
if !print_cluster_layout(&layout) {
|
||||
println!("No nodes have a role in the new layout.");
|
||||
}
|
||||
println!();
|
||||
|
||||
// this will print the stats of what partitions
|
||||
// will move around when we apply
|
||||
if layout.calculate_partition_assignation() {
|
||||
println!("To enact the staged role changes, type:");
|
||||
println!();
|
||||
println!(" garage layout apply --version {}", layout.version + 1);
|
||||
println!();
|
||||
println!(
|
||||
"You can also revert all proposed changes with: garage layout revert --version {}",
|
||||
layout.version + 1
|
||||
);
|
||||
} else {
|
||||
println!("Not enough nodes have an assigned role to maintain enough copies of data.");
|
||||
println!("This new layout cannot yet be applied.");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_apply_layout(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
apply_opt: ApplyLayoutOpt,
|
||||
) -> Result<(), Error> {
|
||||
let mut layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
match apply_opt.version {
|
||||
None => {
|
||||
println!("Please pass the --version flag to ensure that you are writing the correct version of the cluster layout.");
|
||||
println!("To know the correct value of the --version flag, invoke `garage layout show` and review the proposed changes.");
|
||||
return Err(Error::Message("--version flag is missing".into()));
|
||||
}
|
||||
Some(v) => {
|
||||
if v != layout.version + 1 {
|
||||
return Err(Error::Message("Invalid value of --version flag".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
layout.roles.merge(&layout.staging);
|
||||
|
||||
if !layout.calculate_partition_assignation() {
|
||||
return Err(Error::Message("Could not calculate new assignation of partitions to nodes. This can happen if there are less nodes than the desired number of copies of your data (see the replication_mode configuration parameter).".into()));
|
||||
}
|
||||
|
||||
layout.staging.clear();
|
||||
layout.staging_hash = blake2sum(&rmp_to_vec_all_named(&layout.staging).unwrap()[..]);
|
||||
|
||||
layout.version += 1;
|
||||
|
||||
send_layout(rpc_cli, rpc_host, layout).await?;
|
||||
|
||||
println!("New cluster layout with updated role assignation has been applied in cluster.");
|
||||
println!("Data will now be moved around between nodes accordingly.");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cmd_revert_layout(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
revert_opt: RevertLayoutOpt,
|
||||
) -> Result<(), Error> {
|
||||
let mut layout = fetch_layout(rpc_cli, rpc_host).await?;
|
||||
|
||||
match revert_opt.version {
|
||||
None => {
|
||||
println!("Please pass the --version flag to ensure that you are writing the correct version of the cluster layout.");
|
||||
println!("To know the correct value of the --version flag, invoke `garage layout show` and review the proposed changes.");
|
||||
return Err(Error::Message("--version flag is missing".into()));
|
||||
}
|
||||
Some(v) => {
|
||||
if v != layout.version + 1 {
|
||||
return Err(Error::Message("Invalid value of --version flag".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
layout.staging.clear();
|
||||
layout.staging_hash = blake2sum(&rmp_to_vec_all_named(&layout.staging).unwrap()[..]);
|
||||
|
||||
layout.version += 1;
|
||||
|
||||
send_layout(rpc_cli, rpc_host, layout).await?;
|
||||
|
||||
println!("All proposed role changes in cluster layout have been canceled.");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// --- utility ---
|
||||
|
||||
pub async fn fetch_layout(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
) -> Result<ClusterLayout, Error> {
|
||||
match rpc_cli
|
||||
.call(&rpc_host, &SystemRpc::PullClusterLayout, PRIO_NORMAL)
|
||||
.await??
|
||||
{
|
||||
SystemRpc::AdvertiseClusterLayout(t) => Ok(t),
|
||||
resp => Err(Error::Message(format!("Invalid RPC response: {:?}", resp))),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send_layout(
|
||||
rpc_cli: &Endpoint<SystemRpc, ()>,
|
||||
rpc_host: NodeID,
|
||||
layout: ClusterLayout,
|
||||
) -> Result<(), Error> {
|
||||
rpc_cli
|
||||
.call(
|
||||
&rpc_host,
|
||||
&SystemRpc::AdvertiseClusterLayout(layout),
|
||||
PRIO_NORMAL,
|
||||
)
|
||||
.await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn print_cluster_layout(layout: &ClusterLayout) -> bool {
|
||||
let mut table = vec!["ID\tTags\tZone\tCapacity".to_string()];
|
||||
for (id, _, role) in layout.roles.items().iter() {
|
||||
let role = match &role.0 {
|
||||
Some(r) => r,
|
||||
_ => continue,
|
||||
};
|
||||
let tags = role.tags.join(",");
|
||||
table.push(format!(
|
||||
"{:?}\t{}\t{}\t{}",
|
||||
id,
|
||||
tags,
|
||||
role.zone,
|
||||
role.capacity_string()
|
||||
));
|
||||
}
|
||||
if table.len() == 1 {
|
||||
false
|
||||
} else {
|
||||
format_table(table);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub fn print_staging_role_changes(layout: &ClusterLayout) -> bool {
|
||||
if !layout.staging.items().is_empty() {
|
||||
println!();
|
||||
println!("==== STAGED ROLE CHANGES ====");
|
||||
let mut table = vec!["ID\tTags\tZone\tCapacity".to_string()];
|
||||
for (id, _, role) in layout.staging.items().iter() {
|
||||
if let Some(role) = &role.0 {
|
||||
let tags = role.tags.join(",");
|
||||
table.push(format!(
|
||||
"{:?}\t{}\t{}\t{}",
|
||||
id,
|
||||
tags,
|
||||
role.zone,
|
||||
role.capacity_string()
|
||||
));
|
||||
} else {
|
||||
table.push(format!("{:?}\tREMOVED", id));
|
||||
}
|
||||
}
|
||||
format_table(table);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
pub(crate) mod cmd;
|
||||
pub(crate) mod init;
|
||||
pub(crate) mod layout;
|
||||
pub(crate) mod structs;
|
||||
pub(crate) mod util;
|
||||
|
||||
pub(crate) use cmd::*;
|
||||
pub(crate) use init::*;
|
||||
pub(crate) use layout::*;
|
||||
pub(crate) use structs::*;
|
||||
pub(crate) use util::*;
|
||||
|
||||
+54
-25
@@ -8,24 +8,23 @@ pub enum Command {
|
||||
#[structopt(name = "server")]
|
||||
Server,
|
||||
|
||||
/// Print identifier (public key) of this garage node.
|
||||
/// Generates a new keypair if necessary.
|
||||
#[structopt(name = "node-id")]
|
||||
NodeId(NodeIdOpt),
|
||||
|
||||
/// Get network status
|
||||
#[structopt(name = "status")]
|
||||
Status,
|
||||
|
||||
/// Garage node operations
|
||||
/// Operations on individual Garage nodes
|
||||
#[structopt(name = "node")]
|
||||
Node(NodeOperation),
|
||||
|
||||
/// Bucket operations
|
||||
/// Operations on the assignation of node roles in the cluster layout
|
||||
#[structopt(name = "layout")]
|
||||
Layout(LayoutOperation),
|
||||
|
||||
/// Operations on buckets
|
||||
#[structopt(name = "bucket")]
|
||||
Bucket(BucketOperation),
|
||||
|
||||
/// Key operations
|
||||
/// Operations on S3 access keys
|
||||
#[structopt(name = "key")]
|
||||
Key(KeyOperation),
|
||||
|
||||
@@ -40,17 +39,13 @@ pub enum Command {
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub enum NodeOperation {
|
||||
/// Print identifier (public key) of this Garage node
|
||||
#[structopt(name = "id")]
|
||||
NodeId(NodeIdOpt),
|
||||
|
||||
/// 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)]
|
||||
@@ -68,8 +63,31 @@ pub struct ConnectNodeOpt {
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct ConfigureNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
pub enum LayoutOperation {
|
||||
/// Assign role to Garage node
|
||||
#[structopt(name = "assign")]
|
||||
Assign(AssignRoleOpt),
|
||||
|
||||
/// Remove role from Garage cluster node
|
||||
#[structopt(name = "remove")]
|
||||
Remove(RemoveRoleOpt),
|
||||
|
||||
/// Show roles currently assigned to nodes and changes staged for commit
|
||||
#[structopt(name = "show")]
|
||||
Show,
|
||||
|
||||
/// Apply staged changes to cluster layout
|
||||
#[structopt(name = "apply")]
|
||||
Apply(ApplyLayoutOpt),
|
||||
|
||||
/// Revert staged changes to cluster layout
|
||||
#[structopt(name = "revert")]
|
||||
Revert(RevertLayoutOpt),
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct AssignRoleOpt {
|
||||
/// Node to which to assign role (prefix of hexadecimal node id)
|
||||
pub(crate) node_id: String,
|
||||
|
||||
/// Location (zone or datacenter) of the node
|
||||
@@ -84,9 +102,9 @@ pub struct ConfigureNodeOpt {
|
||||
#[structopt(short = "g", long = "gateway")]
|
||||
pub(crate) gateway: bool,
|
||||
|
||||
/// Optional node tag
|
||||
/// Optional tags to add to node
|
||||
#[structopt(short = "t", long = "tag")]
|
||||
pub(crate) tag: Option<String>,
|
||||
pub(crate) tags: Vec<String>,
|
||||
|
||||
/// Replaced node(s): list of node IDs that will be removed from the current cluster
|
||||
#[structopt(long = "replace")]
|
||||
@@ -94,13 +112,24 @@ pub struct ConfigureNodeOpt {
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct RemoveNodeOpt {
|
||||
/// Node to configure (prefix of hexadecimal node id)
|
||||
pub struct RemoveRoleOpt {
|
||||
/// Node whose role to remove (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(StructOpt, Debug)]
|
||||
pub struct ApplyLayoutOpt {
|
||||
/// Version number of new configuration: this command will fail if
|
||||
/// it is not exactly 1 + the previous configuration's version
|
||||
#[structopt(long = "version")]
|
||||
pub(crate) version: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(StructOpt, Debug)]
|
||||
pub struct RevertLayoutOpt {
|
||||
/// Version number of old configuration to which to revert
|
||||
#[structopt(long = "version")]
|
||||
pub(crate) version: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, StructOpt, Debug)]
|
||||
|
||||
+3
-1
@@ -70,7 +70,9 @@ async fn main() {
|
||||
|
||||
server::run_server(opt.config_file).await
|
||||
}
|
||||
Command::NodeId(node_id_opt) => node_id_command(opt.config_file, node_id_opt.quiet),
|
||||
Command::Node(NodeOperation::NodeId(node_id_opt)) => {
|
||||
node_id_command(opt.config_file, node_id_opt.quiet)
|
||||
}
|
||||
_ => cli_command(opt).await,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_model"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "Core data model for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
@@ -13,9 +14,9 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
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_rpc = { version = "0.5.0", path = "../rpc" }
|
||||
garage_table = { version = "0.5.0", path = "../table" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
|
||||
async-trait = "0.1.7"
|
||||
arc-swap = "1.0"
|
||||
|
||||
+180
-54
@@ -1,3 +1,4 @@
|
||||
use std::convert::TryInto;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -31,10 +32,20 @@ pub const INLINE_THRESHOLD: usize = 3072;
|
||||
pub const BACKGROUND_WORKERS: u64 = 1;
|
||||
pub const BACKGROUND_TRANQUILITY: u32 = 3;
|
||||
|
||||
const BLOCK_RW_TIMEOUT: Duration = Duration::from_secs(42);
|
||||
const BLOCK_GC_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
// Timeout for RPCs that read and write blocks to remote nodes
|
||||
const BLOCK_RW_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
// Timeout for RPCs that ask other nodes whether they need a copy
|
||||
// of a given block before we delete it locally
|
||||
const NEED_BLOCK_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const RESYNC_RETRY_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
// The delay between the time where a resync operation fails
|
||||
// and the time when it is retried.
|
||||
const RESYNC_RETRY_DELAY: Duration = Duration::from_secs(60);
|
||||
|
||||
// The delay between the moment when the reference counter
|
||||
// drops to zero, and the moment where we allow ourselves
|
||||
// to delete the block locally.
|
||||
const BLOCK_GC_DELAY: Duration = Duration::from_secs(600);
|
||||
|
||||
/// RPC messages used to share blocks of data between nodes
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -180,7 +191,7 @@ impl BlockManager {
|
||||
/// that are required because of refcount > 0, and will try
|
||||
/// to fix any mismatch between the two.
|
||||
pub async fn repair_data_store(&self, must_exit: &watch::Receiver<bool>) -> Result<(), Error> {
|
||||
// 1. Repair blocks from RC table
|
||||
// 1. Repair blocks from RC table.
|
||||
let garage = self.garage.load_full().unwrap();
|
||||
let mut last_hash = None;
|
||||
for (i, entry) in garage.block_ref_table.data.store.iter().enumerate() {
|
||||
@@ -245,40 +256,51 @@ impl BlockManager {
|
||||
/// Increment the number of time a block is used, putting it to resynchronization if it is
|
||||
/// required, but not known
|
||||
pub fn block_incref(&self, hash: &Hash) -> Result<(), Error> {
|
||||
let old_rc = self.rc.fetch_and_update(&hash, |old| {
|
||||
let old_v = old.map(u64_from_be_bytes).unwrap_or(0);
|
||||
Some(u64::to_be_bytes(old_v + 1).to_vec())
|
||||
})?;
|
||||
let old_rc = old_rc.map(u64_from_be_bytes).unwrap_or(0);
|
||||
if old_rc == 0 {
|
||||
self.put_to_resync(hash, BLOCK_RW_TIMEOUT)?;
|
||||
let old_rc = self
|
||||
.rc
|
||||
.fetch_and_update(&hash, |old| RcEntry::parse_opt(old).increment().serialize())?;
|
||||
let old_rc = RcEntry::parse_opt(old_rc);
|
||||
if old_rc.is_zero() {
|
||||
// When the reference counter is incremented, there is
|
||||
// normally a node that is responsible for sending us the
|
||||
// data of the block. However that operation may fail,
|
||||
// so in all cases we add the block here to the todo list
|
||||
// to check later that it arrived correctly, and if not
|
||||
// we will fecth it from someone.
|
||||
self.put_to_resync(hash, 2 * BLOCK_RW_TIMEOUT)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decrement the number of time a block is used
|
||||
pub fn block_decref(&self, hash: &Hash) -> Result<(), Error> {
|
||||
let new_rc = self.rc.update_and_fetch(&hash, |old| {
|
||||
let old_v = old.map(u64_from_be_bytes).unwrap_or(0);
|
||||
if old_v > 1 {
|
||||
Some(u64::to_be_bytes(old_v - 1).to_vec())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})?;
|
||||
if new_rc.is_none() {
|
||||
self.put_to_resync(hash, BLOCK_GC_TIMEOUT)?;
|
||||
let new_rc = self
|
||||
.rc
|
||||
.update_and_fetch(&hash, |old| RcEntry::parse_opt(old).decrement().serialize())?;
|
||||
let new_rc = RcEntry::parse_opt(new_rc);
|
||||
if let RcEntry::Deletable { .. } = new_rc {
|
||||
self.put_to_resync(hash, BLOCK_GC_DELAY + Duration::from_secs(10))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a block's reference count
|
||||
pub fn get_block_rc(&self, hash: &Hash) -> Result<u64, Error> {
|
||||
Ok(self
|
||||
.rc
|
||||
.get(hash.as_ref())?
|
||||
.map(u64_from_be_bytes)
|
||||
.unwrap_or(0))
|
||||
fn get_block_rc(&self, hash: &Hash) -> Result<RcEntry, Error> {
|
||||
Ok(RcEntry::parse_opt(self.rc.get(hash.as_ref())?))
|
||||
}
|
||||
|
||||
/// Delete an entry in the RC table if it is deletable and the
|
||||
/// deletion time has passed
|
||||
fn clear_deleted_block_rc(&self, hash: &Hash) -> Result<(), Error> {
|
||||
let now = now_msec();
|
||||
self.rc.update_and_fetch(&hash, |rcval| {
|
||||
let updated = match RcEntry::parse_opt(rcval) {
|
||||
RcEntry::Deletable { at_time } if now > at_time => RcEntry::Absent,
|
||||
v => v,
|
||||
};
|
||||
updated.serialize()
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Reading and writing blocks locally ----
|
||||
@@ -300,7 +322,7 @@ impl BlockManager {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
// Not found but maybe we should have had it ??
|
||||
self.put_to_resync(hash, Duration::from_millis(0))?;
|
||||
self.put_to_resync(hash, 2 * BLOCK_RW_TIMEOUT)?;
|
||||
return Err(Into::into(e));
|
||||
}
|
||||
};
|
||||
@@ -314,6 +336,7 @@ impl BlockManager {
|
||||
.await
|
||||
.move_block_to_corrupted(hash, self)
|
||||
.await?;
|
||||
self.put_to_resync(hash, Duration::from_millis(0))?;
|
||||
return Err(Error::CorruptData(*hash));
|
||||
}
|
||||
|
||||
@@ -328,7 +351,7 @@ impl BlockManager {
|
||||
.await
|
||||
.check_block_status(hash, self)
|
||||
.await?;
|
||||
Ok(needed && !exists)
|
||||
Ok(needed.is_nonzero() && !exists)
|
||||
}
|
||||
|
||||
/// Utility: gives the path of the directory in which a block should be found
|
||||
@@ -349,7 +372,7 @@ impl BlockManager {
|
||||
// ---- Resync loop ----
|
||||
|
||||
pub fn spawn_background_worker(self: Arc<Self>) {
|
||||
// Launch 2 simultaneous workers for background resync loop preprocessing
|
||||
// Launch n simultaneous workers for background resync loop preprocessing
|
||||
for i in 0..BACKGROUND_WORKERS {
|
||||
let bm2 = self.clone();
|
||||
let background = self.system.background.clone();
|
||||
@@ -400,14 +423,14 @@ impl BlockManager {
|
||||
|
||||
async fn resync_iter(&self, must_exit: &mut watch::Receiver<bool>) -> Result<bool, Error> {
|
||||
if let Some((time_bytes, hash_bytes)) = self.resync_queue.pop_min()? {
|
||||
let time_msec = u64_from_be_bytes(&time_bytes[0..8]);
|
||||
let time_msec = u64::from_be_bytes(time_bytes[0..8].try_into().unwrap());
|
||||
let now = now_msec();
|
||||
if now >= time_msec {
|
||||
let hash = Hash::try_from(&hash_bytes[..]).unwrap();
|
||||
let res = self.resync_block(&hash).await;
|
||||
if let Err(e) = &res {
|
||||
warn!("Error when resyncing {:?}: {}", hash, e);
|
||||
self.put_to_resync(&hash, RESYNC_RETRY_TIMEOUT)?;
|
||||
self.put_to_resync(&hash, RESYNC_RETRY_DELAY)?;
|
||||
}
|
||||
Ok(true)
|
||||
} else {
|
||||
@@ -437,15 +460,18 @@ impl BlockManager {
|
||||
.check_block_status(hash, self)
|
||||
.await?;
|
||||
|
||||
if exists != needed {
|
||||
info!(
|
||||
"Resync block {:?}: exists {}, needed {}",
|
||||
hash, exists, needed
|
||||
if exists != needed.is_needed() || exists != needed.is_nonzero() {
|
||||
debug!(
|
||||
"Resync block {:?}: exists {}, nonzero rc {}, deletable {}",
|
||||
hash,
|
||||
exists,
|
||||
needed.is_nonzero(),
|
||||
needed.is_deletable(),
|
||||
);
|
||||
}
|
||||
|
||||
if exists && !needed {
|
||||
trace!("Offloading block {:?}", hash);
|
||||
if exists && needed.is_deletable() {
|
||||
info!("Resync block {:?}: offloading and deleting", hash);
|
||||
|
||||
let mut who = self.replication.write_nodes(hash);
|
||||
if who.len() < self.replication.write_quorum() {
|
||||
@@ -488,7 +514,7 @@ impl BlockManager {
|
||||
need_nodes.len()
|
||||
);
|
||||
|
||||
let put_block_message = self.read_block(hash).await.err_context("PutBlock RPC")?;
|
||||
let put_block_message = self.read_block(hash).await?;
|
||||
self.system
|
||||
.rpc
|
||||
.try_call_many(
|
||||
@@ -499,10 +525,11 @@ impl BlockManager {
|
||||
.with_quorum(need_nodes.len())
|
||||
.with_timeout(BLOCK_RW_TIMEOUT),
|
||||
)
|
||||
.await?;
|
||||
.await
|
||||
.err_context("PutBlock RPC")?;
|
||||
}
|
||||
info!(
|
||||
"Deleting block {:?}, offload finished ({} / {})",
|
||||
"Deleting unneeded block {:?}, offload finished ({} / {})",
|
||||
hash,
|
||||
need_nodes.len(),
|
||||
who.len()
|
||||
@@ -513,12 +540,16 @@ impl BlockManager {
|
||||
.await
|
||||
.delete_if_unneeded(hash, self)
|
||||
.await?;
|
||||
|
||||
self.clear_deleted_block_rc(hash)?;
|
||||
}
|
||||
|
||||
if needed && !exists {
|
||||
// TODO find a way to not do this if they are sending it to us
|
||||
// Let's suppose this isn't an issue for now with the BLOCK_RW_TIMEOUT delay
|
||||
// between the RC being incremented and this part being called.
|
||||
if needed.is_nonzero() && !exists {
|
||||
info!(
|
||||
"Resync block {:?}: fetching absent but needed block (refcount > 0)",
|
||||
hash
|
||||
);
|
||||
|
||||
let block_data = self.rpc_get_block(hash).await?;
|
||||
self.write_block(hash, &block_data[..]).await?;
|
||||
}
|
||||
@@ -526,6 +557,8 @@ impl BlockManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Utility: iteration on files in the data directory ----
|
||||
|
||||
async fn for_each_file<F, Fut, State>(
|
||||
&self,
|
||||
state: State,
|
||||
@@ -608,7 +641,7 @@ impl EndpointHandler<BlockRpc> for BlockManager {
|
||||
|
||||
struct BlockStatus {
|
||||
exists: bool,
|
||||
needed: bool,
|
||||
needed: RcEntry,
|
||||
}
|
||||
|
||||
impl BlockManagerLocked {
|
||||
@@ -620,7 +653,7 @@ impl BlockManagerLocked {
|
||||
let path = mgr.block_path(hash);
|
||||
|
||||
let exists = fs::metadata(&path).await.is_ok();
|
||||
let needed = mgr.get_block_rc(hash)? > 0;
|
||||
let needed = mgr.get_block_rc(hash)?;
|
||||
|
||||
Ok(BlockStatus { exists, needed })
|
||||
}
|
||||
@@ -659,14 +692,13 @@ impl BlockManagerLocked {
|
||||
let mut path2 = path.clone();
|
||||
path2.set_extension("corrupted");
|
||||
fs::rename(path, path2).await?;
|
||||
mgr.put_to_resync(hash, Duration::from_millis(0))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn delete_if_unneeded(&self, hash: &Hash, mgr: &BlockManager) -> Result<(), Error> {
|
||||
let BlockStatus { exists, needed } = self.check_block_status(hash, mgr).await?;
|
||||
|
||||
if exists && !needed {
|
||||
if exists && needed.is_deletable() {
|
||||
let path = mgr.block_path(hash);
|
||||
fs::remove_file(path).await?;
|
||||
}
|
||||
@@ -674,9 +706,103 @@ impl BlockManagerLocked {
|
||||
}
|
||||
}
|
||||
|
||||
fn u64_from_be_bytes<T: AsRef<[u8]>>(bytes: T) -> u64 {
|
||||
assert!(bytes.as_ref().len() == 8);
|
||||
let mut x8 = [0u8; 8];
|
||||
x8.copy_from_slice(bytes.as_ref());
|
||||
u64::from_be_bytes(x8)
|
||||
/// Describes the state of the reference counter for a block
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum RcEntry {
|
||||
/// Present: the block has `count` references, with `count` > 0.
|
||||
///
|
||||
/// This is stored as u64::to_be_bytes(count)
|
||||
Present { count: u64 },
|
||||
|
||||
/// Deletable: the block has zero references, and can be deleted
|
||||
/// once time (returned by now_msec) is larger than at_time
|
||||
/// (in millis since Unix epoch)
|
||||
///
|
||||
/// This is stored as [0u8; 8] followed by u64::to_be_bytes(at_time),
|
||||
/// (this allows for the data format to be backwards compatible with
|
||||
/// previous Garage versions that didn't have this intermediate state)
|
||||
Deletable { at_time: u64 },
|
||||
|
||||
/// Absent: the block has zero references, and can be deleted
|
||||
/// immediately
|
||||
Absent,
|
||||
}
|
||||
|
||||
impl RcEntry {
|
||||
fn parse(bytes: &[u8]) -> Self {
|
||||
if bytes.len() == 8 {
|
||||
RcEntry::Present {
|
||||
count: u64::from_be_bytes(bytes.try_into().unwrap()),
|
||||
}
|
||||
} else if bytes.len() == 16 {
|
||||
RcEntry::Deletable {
|
||||
at_time: u64::from_be_bytes(bytes[8..16].try_into().unwrap()),
|
||||
}
|
||||
} else {
|
||||
panic!("Invalid RC entry: {:?}, database is corrupted. This is an error Garage is currently unable to recover from. Sorry, and also please report a bug.",
|
||||
bytes
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_opt<V: AsRef<[u8]>>(bytes: Option<V>) -> Self {
|
||||
bytes
|
||||
.map(|b| Self::parse(b.as_ref()))
|
||||
.unwrap_or(Self::Absent)
|
||||
}
|
||||
|
||||
fn serialize(self) -> Option<Vec<u8>> {
|
||||
match self {
|
||||
RcEntry::Present { count } => Some(u64::to_be_bytes(count).to_vec()),
|
||||
RcEntry::Deletable { at_time } => {
|
||||
Some([u64::to_be_bytes(0), u64::to_be_bytes(at_time)].concat())
|
||||
}
|
||||
RcEntry::Absent => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn increment(self) -> Self {
|
||||
let old_count = match self {
|
||||
RcEntry::Present { count } => count,
|
||||
_ => 0,
|
||||
};
|
||||
RcEntry::Present {
|
||||
count: old_count + 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn decrement(self) -> Self {
|
||||
match self {
|
||||
RcEntry::Present { count } => {
|
||||
if count > 1 {
|
||||
RcEntry::Present { count: count - 1 }
|
||||
} else {
|
||||
RcEntry::Deletable {
|
||||
at_time: now_msec() + BLOCK_GC_DELAY.as_millis() as u64,
|
||||
}
|
||||
}
|
||||
}
|
||||
del => del,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_zero(&self) -> bool {
|
||||
matches!(self, RcEntry::Deletable { .. } | RcEntry::Absent)
|
||||
}
|
||||
|
||||
fn is_nonzero(&self) -> bool {
|
||||
!self.is_zero()
|
||||
}
|
||||
|
||||
fn is_deletable(&self) -> bool {
|
||||
match self {
|
||||
RcEntry::Present { .. } => false,
|
||||
RcEntry::Deletable { at_time } => now_msec() > *at_time,
|
||||
RcEntry::Absent => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_needed(&self) -> bool {
|
||||
!self.is_deletable()
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_rpc"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "Cluster membership management and RPC protocol for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
@@ -13,7 +14,7 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
|
||||
arc-swap = "1.0"
|
||||
bytes = "1.0"
|
||||
@@ -26,6 +27,7 @@ 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_bytes = "0.11"
|
||||
serde_json = "1.0"
|
||||
|
||||
futures = "0.3"
|
||||
|
||||
@@ -0,0 +1,579 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use garage_util::crdt::{AutoCrdt, Crdt, LwwMap};
|
||||
use garage_util::data::*;
|
||||
|
||||
use crate::ring::*;
|
||||
|
||||
/// The layout of the cluster, i.e. the list of roles
|
||||
/// which are assigned to each cluster node
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ClusterLayout {
|
||||
pub version: u64,
|
||||
|
||||
pub replication_factor: usize,
|
||||
pub roles: LwwMap<Uuid, NodeRoleV>,
|
||||
|
||||
/// node_id_vec: a vector of node IDs with a role assigned
|
||||
/// in the system (this includes gateway nodes).
|
||||
/// The order here is different than the vec stored by `roles`, because:
|
||||
/// 1. non-gateway nodes are first so that they have lower numbers
|
||||
/// 2. nodes that don't have a role are excluded (but they need to
|
||||
/// stay in the CRDT as tombstones)
|
||||
pub node_id_vec: Vec<Uuid>,
|
||||
/// the assignation of data partitions to node, the values
|
||||
/// are indices in node_id_vec
|
||||
#[serde(with = "serde_bytes")]
|
||||
pub ring_assignation_data: Vec<CompactNodeType>,
|
||||
|
||||
/// Role changes which are staged for the next version of the layout
|
||||
pub staging: LwwMap<Uuid, NodeRoleV>,
|
||||
pub staging_hash: Hash,
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct NodeRoleV(pub Option<NodeRole>);
|
||||
|
||||
impl AutoCrdt for NodeRoleV {
|
||||
const WARN_IF_DIFFERENT: bool = true;
|
||||
}
|
||||
|
||||
/// The user-assigned roles of cluster nodes
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct NodeRole {
|
||||
/// Datacenter at which this entry belong. This information might be used to perform a better
|
||||
/// geodistribution
|
||||
pub zone: String,
|
||||
/// The (relative) capacity of the node
|
||||
/// If this is set to None, the node does not participate in storing data for the system
|
||||
/// and is only active as an API gateway to other nodes
|
||||
pub capacity: Option<u32>,
|
||||
/// A set of tags to recognize the node
|
||||
pub tags: Vec<String>,
|
||||
}
|
||||
|
||||
impl NodeRole {
|
||||
pub fn capacity_string(&self) -> String {
|
||||
match self.capacity {
|
||||
Some(c) => format!("{}", c),
|
||||
None => "gateway".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClusterLayout {
|
||||
pub fn new(replication_factor: usize) -> Self {
|
||||
let empty_lwwmap = LwwMap::new();
|
||||
let empty_lwwmap_hash = blake2sum(&rmp_to_vec_all_named(&empty_lwwmap).unwrap()[..]);
|
||||
|
||||
ClusterLayout {
|
||||
version: 0,
|
||||
replication_factor,
|
||||
roles: LwwMap::new(),
|
||||
node_id_vec: Vec::new(),
|
||||
ring_assignation_data: Vec::new(),
|
||||
staging: empty_lwwmap,
|
||||
staging_hash: empty_lwwmap_hash,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn merge(&mut self, other: &ClusterLayout) -> bool {
|
||||
match other.version.cmp(&self.version) {
|
||||
Ordering::Greater => {
|
||||
*self = other.clone();
|
||||
true
|
||||
}
|
||||
Ordering::Equal => {
|
||||
self.staging.merge(&other.staging);
|
||||
|
||||
let new_staging_hash = blake2sum(&rmp_to_vec_all_named(&self.staging).unwrap()[..]);
|
||||
let changed = new_staging_hash != self.staging_hash;
|
||||
|
||||
self.staging_hash = new_staging_hash;
|
||||
|
||||
changed
|
||||
}
|
||||
Ordering::Less => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a list of IDs of nodes that currently have
|
||||
/// a role in the cluster
|
||||
pub fn node_ids(&self) -> &[Uuid] {
|
||||
&self.node_id_vec[..]
|
||||
}
|
||||
|
||||
pub fn num_nodes(&self) -> usize {
|
||||
self.node_id_vec.len()
|
||||
}
|
||||
|
||||
/// Returns the role of a node in the layout
|
||||
pub fn node_role(&self, node: &Uuid) -> Option<&NodeRole> {
|
||||
match self.roles.get(node) {
|
||||
Some(NodeRoleV(Some(v))) => Some(v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a cluster layout for internal consistency
|
||||
/// returns true if consistent, false if error
|
||||
pub fn check(&self) -> bool {
|
||||
// Check that the hash of the staging data is correct
|
||||
let staging_hash = blake2sum(&rmp_to_vec_all_named(&self.staging).unwrap()[..]);
|
||||
if staging_hash != self.staging_hash {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that node_id_vec contains the correct list of nodes
|
||||
let mut expected_nodes = self
|
||||
.roles
|
||||
.items()
|
||||
.iter()
|
||||
.filter(|(_, _, v)| v.0.is_some())
|
||||
.map(|(id, _, _)| *id)
|
||||
.collect::<Vec<_>>();
|
||||
expected_nodes.sort();
|
||||
let mut node_id_vec = self.node_id_vec.clone();
|
||||
node_id_vec.sort();
|
||||
if expected_nodes != node_id_vec {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that the assignation data has the correct length
|
||||
if self.ring_assignation_data.len() != (1 << PARTITION_BITS) * self.replication_factor {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that the assigned nodes are correct identifiers
|
||||
// of nodes that are assigned a role
|
||||
// and that role is not the role of a gateway nodes
|
||||
for x in self.ring_assignation_data.iter() {
|
||||
if *x as usize >= self.node_id_vec.len() {
|
||||
return false;
|
||||
}
|
||||
let node = self.node_id_vec[*x as usize];
|
||||
match self.roles.get(&node) {
|
||||
Some(NodeRoleV(Some(x))) if x.capacity.is_some() => (),
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Calculate an assignation of partitions to nodes
|
||||
pub fn calculate_partition_assignation(&mut self) -> bool {
|
||||
let (configured_nodes, zones) = self.configured_nodes_and_zones();
|
||||
let n_zones = zones.len();
|
||||
|
||||
println!("Calculating updated partition assignation, this may take some time...");
|
||||
println!();
|
||||
|
||||
let old_partitions = self.parse_assignation_data();
|
||||
|
||||
let mut partitions = old_partitions.clone();
|
||||
for part in partitions.iter_mut() {
|
||||
part.nodes
|
||||
.retain(|(_, info)| info.map(|x| x.capacity.is_some()).unwrap_or(false));
|
||||
}
|
||||
|
||||
// When nodes are removed, or when bootstraping an assignation from
|
||||
// scratch for a new cluster, the old partitions will have holes (or be empty).
|
||||
// Here we add more nodes to make a complete (sub-optimal) assignation,
|
||||
// using an initial partition assignation that is calculated using the multi-dc maglev trick
|
||||
match self.initial_partition_assignation() {
|
||||
Some(initial_partitions) => {
|
||||
for (part, ipart) in partitions.iter_mut().zip(initial_partitions.iter()) {
|
||||
for (id, info) in ipart.nodes.iter() {
|
||||
if part.nodes.len() < self.replication_factor {
|
||||
part.add(part.nodes.len() + 1, n_zones, id, info.unwrap());
|
||||
}
|
||||
}
|
||||
assert!(part.nodes.len() == self.replication_factor);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate how many partitions each node should ideally store,
|
||||
// and how many partitions they are storing with the current assignation
|
||||
// This defines our target for which we will optimize in the following loop.
|
||||
let total_capacity = configured_nodes
|
||||
.iter()
|
||||
.map(|(_, info)| info.capacity.unwrap_or(0))
|
||||
.sum::<u32>() as usize;
|
||||
let total_partitions = self.replication_factor * (1 << PARTITION_BITS);
|
||||
let target_partitions_per_node = configured_nodes
|
||||
.iter()
|
||||
.map(|(id, info)| {
|
||||
(
|
||||
*id,
|
||||
info.capacity.unwrap_or(0) as usize * total_partitions / total_capacity,
|
||||
)
|
||||
})
|
||||
.collect::<HashMap<&Uuid, usize>>();
|
||||
|
||||
let mut partitions_per_node = self.partitions_per_node(&partitions[..]);
|
||||
|
||||
println!("Target number of partitions per node:");
|
||||
for (node, npart) in target_partitions_per_node.iter() {
|
||||
println!("{:?}\t{}", node, npart);
|
||||
}
|
||||
println!();
|
||||
|
||||
// Shuffle partitions between nodes so that nodes will reach (or better approach)
|
||||
// their target number of stored partitions
|
||||
loop {
|
||||
let mut option = None;
|
||||
for (i, part) in partitions.iter_mut().enumerate() {
|
||||
for (irm, (idrm, _)) in part.nodes.iter().enumerate() {
|
||||
let suprm = partitions_per_node.get(*idrm).cloned().unwrap_or(0) as i32
|
||||
- target_partitions_per_node.get(*idrm).cloned().unwrap_or(0) as i32;
|
||||
|
||||
for (idadd, infoadd) in configured_nodes.iter() {
|
||||
// skip replacing a node by itself
|
||||
// and skip replacing by gateway nodes
|
||||
if idadd == idrm || infoadd.capacity.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let supadd = partitions_per_node.get(*idadd).cloned().unwrap_or(0) as i32
|
||||
- target_partitions_per_node.get(*idadd).cloned().unwrap_or(0) as i32;
|
||||
|
||||
// We want to try replacing node idrm by node idadd
|
||||
// if that brings us close to our goal.
|
||||
let square = |i: i32| i * i;
|
||||
let oldcost = square(suprm) + square(supadd);
|
||||
let newcost = square(suprm - 1) + square(supadd + 1);
|
||||
if newcost >= oldcost {
|
||||
// not closer to our goal
|
||||
continue;
|
||||
}
|
||||
let gain = oldcost - newcost;
|
||||
|
||||
let mut newpart = part.clone();
|
||||
|
||||
newpart.nodes.remove(irm);
|
||||
if !newpart.add(newpart.nodes.len() + 1, n_zones, idadd, infoadd) {
|
||||
continue;
|
||||
}
|
||||
assert!(newpart.nodes.len() == self.replication_factor);
|
||||
|
||||
if !old_partitions[i]
|
||||
.is_valid_transition_to(&newpart, self.replication_factor)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if option
|
||||
.as_ref()
|
||||
.map(|(old_gain, _, _, _, _)| gain > *old_gain)
|
||||
.unwrap_or(true)
|
||||
{
|
||||
option = Some((gain, i, idadd, idrm, newpart));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((_gain, i, idadd, idrm, newpart)) = option {
|
||||
*partitions_per_node.entry(idadd).or_insert(0) += 1;
|
||||
*partitions_per_node.get_mut(idrm).unwrap() -= 1;
|
||||
partitions[i] = newpart;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check we completed the assignation correctly
|
||||
// (this is a set of checks for the algorithm's consistency)
|
||||
assert!(partitions.len() == (1 << PARTITION_BITS));
|
||||
assert!(partitions
|
||||
.iter()
|
||||
.all(|p| p.nodes.len() == self.replication_factor));
|
||||
|
||||
let new_partitions_per_node = self.partitions_per_node(&partitions[..]);
|
||||
assert!(new_partitions_per_node == partitions_per_node);
|
||||
|
||||
// Show statistics
|
||||
println!("New number of partitions per node:");
|
||||
for (node, npart) in partitions_per_node.iter() {
|
||||
println!("{:?}\t{}", node, npart);
|
||||
}
|
||||
println!();
|
||||
|
||||
let mut diffcount = HashMap::new();
|
||||
for (oldpart, newpart) in old_partitions.iter().zip(partitions.iter()) {
|
||||
let nminus = oldpart.txtplus(newpart);
|
||||
let nplus = newpart.txtplus(oldpart);
|
||||
if nminus != "[...]" || nplus != "[...]" {
|
||||
let tup = (nminus, nplus);
|
||||
*diffcount.entry(tup).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
if diffcount.is_empty() {
|
||||
println!("No data will be moved between nodes.");
|
||||
} else {
|
||||
let mut diffcount = diffcount.into_iter().collect::<Vec<_>>();
|
||||
diffcount.sort();
|
||||
println!("Number of partitions that move:");
|
||||
for ((nminus, nplus), npart) in diffcount {
|
||||
println!("\t{}\t{} -> {}", npart, nminus, nplus);
|
||||
}
|
||||
}
|
||||
println!();
|
||||
|
||||
// Calculate and save new assignation data
|
||||
let (nodes, assignation_data) =
|
||||
self.compute_assignation_data(&configured_nodes[..], &partitions[..]);
|
||||
|
||||
self.node_id_vec = nodes;
|
||||
self.ring_assignation_data = assignation_data;
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
fn initial_partition_assignation(&self) -> Option<Vec<PartitionAss<'_>>> {
|
||||
let (configured_nodes, zones) = self.configured_nodes_and_zones();
|
||||
let n_zones = zones.len();
|
||||
|
||||
// Create a vector of partition indices (0 to 2**PARTITION_BITS-1)
|
||||
let partitions_idx = (0usize..(1usize << PARTITION_BITS)).collect::<Vec<_>>();
|
||||
|
||||
// Prepare ring
|
||||
let mut partitions: Vec<PartitionAss> = partitions_idx
|
||||
.iter()
|
||||
.map(|_i| PartitionAss::new())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Create MagLev priority queues for each node
|
||||
let mut queues = configured_nodes
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(node_id, node_info)| {
|
||||
let mut parts = partitions_idx
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let part_data =
|
||||
[&u16::to_be_bytes(*i as u16)[..], node_id.as_slice()].concat();
|
||||
(*i, fasthash(&part_data[..]))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
parts.sort_by_key(|(_i, h)| *h);
|
||||
let parts_i = parts.iter().map(|(i, _h)| *i).collect::<Vec<_>>();
|
||||
(node_id, node_info, parts_i, 0)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let max_capacity = configured_nodes
|
||||
.iter()
|
||||
.filter_map(|(_, node_info)| node_info.capacity)
|
||||
.fold(0, std::cmp::max);
|
||||
|
||||
// Fill up ring
|
||||
for rep in 0..self.replication_factor {
|
||||
queues.sort_by_key(|(ni, _np, _q, _p)| {
|
||||
let queue_data = [&u16::to_be_bytes(rep as u16)[..], ni.as_slice()].concat();
|
||||
fasthash(&queue_data[..])
|
||||
});
|
||||
|
||||
for (_, _, _, pos) in queues.iter_mut() {
|
||||
*pos = 0;
|
||||
}
|
||||
|
||||
let mut remaining = partitions_idx.len();
|
||||
while remaining > 0 {
|
||||
let remaining0 = remaining;
|
||||
for i_round in 0..max_capacity {
|
||||
for (node_id, node_info, q, pos) in queues.iter_mut() {
|
||||
if i_round >= node_info.capacity.unwrap() {
|
||||
continue;
|
||||
}
|
||||
for (pos2, &qv) in q.iter().enumerate().skip(*pos) {
|
||||
if partitions[qv].add(rep + 1, n_zones, node_id, node_info) {
|
||||
remaining -= 1;
|
||||
*pos = pos2 + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if remaining == remaining0 {
|
||||
// No progress made, exit
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(partitions)
|
||||
}
|
||||
|
||||
fn configured_nodes_and_zones(&self) -> (Vec<(&Uuid, &NodeRole)>, HashSet<&str>) {
|
||||
let configured_nodes = self
|
||||
.roles
|
||||
.items()
|
||||
.iter()
|
||||
.filter(|(_id, _, info)| info.0.is_some())
|
||||
.map(|(id, _, info)| (id, info.0.as_ref().unwrap()))
|
||||
.collect::<Vec<(&Uuid, &NodeRole)>>();
|
||||
|
||||
let zones = configured_nodes
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(_id, info)| info.zone.as_str())
|
||||
.collect::<HashSet<&str>>();
|
||||
|
||||
(configured_nodes, zones)
|
||||
}
|
||||
|
||||
fn compute_assignation_data<'a>(
|
||||
&self,
|
||||
configured_nodes: &[(&'a Uuid, &'a NodeRole)],
|
||||
partitions: &[PartitionAss<'a>],
|
||||
) -> (Vec<Uuid>, Vec<CompactNodeType>) {
|
||||
assert!(partitions.len() == (1 << PARTITION_BITS));
|
||||
|
||||
// Make a canonical order for nodes
|
||||
let mut nodes = configured_nodes
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(id, _)| **id)
|
||||
.collect::<Vec<_>>();
|
||||
let nodes_rev = nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| (*id, i as CompactNodeType))
|
||||
.collect::<HashMap<Uuid, CompactNodeType>>();
|
||||
|
||||
let mut assignation_data = vec![];
|
||||
for partition in partitions.iter() {
|
||||
assert!(partition.nodes.len() == self.replication_factor);
|
||||
for (id, _) in partition.nodes.iter() {
|
||||
assignation_data.push(*nodes_rev.get(id).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
nodes.extend(
|
||||
configured_nodes
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_none())
|
||||
.map(|(id, _)| **id),
|
||||
);
|
||||
|
||||
(nodes, assignation_data)
|
||||
}
|
||||
|
||||
fn parse_assignation_data(&self) -> Vec<PartitionAss<'_>> {
|
||||
if self.ring_assignation_data.len() == self.replication_factor * (1 << PARTITION_BITS) {
|
||||
// If the previous assignation data is correct, use that
|
||||
let mut partitions = vec![];
|
||||
for i in 0..(1 << PARTITION_BITS) {
|
||||
let mut part = PartitionAss::new();
|
||||
for node_i in self.ring_assignation_data
|
||||
[i * self.replication_factor..(i + 1) * self.replication_factor]
|
||||
.iter()
|
||||
{
|
||||
let node_id = &self.node_id_vec[*node_i as usize];
|
||||
|
||||
if let Some(NodeRoleV(Some(info))) = self.roles.get(node_id) {
|
||||
part.nodes.push((node_id, Some(info)));
|
||||
} else {
|
||||
part.nodes.push((node_id, None));
|
||||
}
|
||||
}
|
||||
partitions.push(part);
|
||||
}
|
||||
partitions
|
||||
} else {
|
||||
// Otherwise start fresh
|
||||
(0..(1 << PARTITION_BITS))
|
||||
.map(|_| PartitionAss::new())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn partitions_per_node<'a>(&self, partitions: &[PartitionAss<'a>]) -> HashMap<&'a Uuid, usize> {
|
||||
let mut partitions_per_node = HashMap::<&Uuid, usize>::new();
|
||||
for p in partitions.iter() {
|
||||
for (id, _) in p.nodes.iter() {
|
||||
*partitions_per_node.entry(*id).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
partitions_per_node
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Internal structs for partition assignation in layout ----
|
||||
|
||||
#[derive(Clone)]
|
||||
struct PartitionAss<'a> {
|
||||
nodes: Vec<(&'a Uuid, Option<&'a NodeRole>)>,
|
||||
}
|
||||
|
||||
impl<'a> PartitionAss<'a> {
|
||||
fn new() -> Self {
|
||||
Self { nodes: Vec::new() }
|
||||
}
|
||||
|
||||
fn nplus(&self, other: &PartitionAss<'a>) -> usize {
|
||||
self.nodes
|
||||
.iter()
|
||||
.filter(|x| !other.nodes.contains(x))
|
||||
.count()
|
||||
}
|
||||
|
||||
fn txtplus(&self, other: &PartitionAss<'a>) -> String {
|
||||
let mut nodes = self
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|x| !other.nodes.contains(x))
|
||||
.map(|x| format!("{:?}", x.0))
|
||||
.collect::<Vec<_>>();
|
||||
nodes.sort();
|
||||
if self.nodes.iter().any(|x| other.nodes.contains(x)) {
|
||||
nodes.push("...".into());
|
||||
}
|
||||
format!("[{}]", nodes.join(" "))
|
||||
}
|
||||
|
||||
fn is_valid_transition_to(&self, other: &PartitionAss<'a>, replication_factor: usize) -> bool {
|
||||
let min_keep_nodes_per_part = (replication_factor + 1) / 2;
|
||||
let n_removed = self.nplus(other);
|
||||
|
||||
if self.nodes.len() <= min_keep_nodes_per_part {
|
||||
n_removed == 0
|
||||
} else {
|
||||
n_removed <= self.nodes.len() - min_keep_nodes_per_part
|
||||
}
|
||||
}
|
||||
|
||||
fn add(
|
||||
&mut self,
|
||||
target_len: usize,
|
||||
n_zones: usize,
|
||||
node: &'a Uuid,
|
||||
role: &'a NodeRole,
|
||||
) -> bool {
|
||||
if self.nodes.len() != target_len - 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let p_zns = self
|
||||
.nodes
|
||||
.iter()
|
||||
.map(|(_id, info)| info.unwrap().zone.as_str())
|
||||
.collect::<HashSet<&str>>();
|
||||
if (p_zns.len() < n_zones && !p_zns.contains(&role.zone.as_str()))
|
||||
|| (p_zns.len() == n_zones && !self.nodes.iter().any(|(id, _)| *id == node))
|
||||
{
|
||||
self.nodes.push((node, Some(role)));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ extern crate log;
|
||||
|
||||
mod consul;
|
||||
|
||||
pub mod layout;
|
||||
pub mod ring;
|
||||
pub mod system;
|
||||
|
||||
|
||||
+29
-168
@@ -1,12 +1,11 @@
|
||||
//! Module containing types related to computing nodes which should receive a copy of data blocks
|
||||
//! and metadata
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::convert::TryInto;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use garage_util::data::*;
|
||||
|
||||
use crate::layout::ClusterLayout;
|
||||
|
||||
/// A partition id, which is stored on 16 bits
|
||||
/// i.e. we have up to 2**16 partitions.
|
||||
/// (in practice we have exactly 2**PARTITION_BITS partitions)
|
||||
@@ -22,47 +21,6 @@ pub const PARTITION_BITS: usize = 8;
|
||||
|
||||
const PARTITION_MASK_U16: u16 = ((1 << PARTITION_BITS) - 1) << (16 - PARTITION_BITS);
|
||||
|
||||
/// The user-defined configuration of the cluster's nodes
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct NetworkConfig {
|
||||
/// Map of each node's id to it's configuration
|
||||
pub members: HashMap<Uuid, NetworkConfigEntry>,
|
||||
/// Version of this config
|
||||
pub version: u64,
|
||||
}
|
||||
|
||||
impl NetworkConfig {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
members: HashMap::new(),
|
||||
version: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The overall configuration of one (possibly remote) node
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct NetworkConfigEntry {
|
||||
/// Datacenter at which this entry belong. This infromation might be used to perform a better
|
||||
/// geodistribution
|
||||
pub zone: String,
|
||||
/// The (relative) capacity of the node
|
||||
/// If this is set to None, the node does not participate in storing data for the system
|
||||
/// and is only active as an API gateway to other nodes
|
||||
pub capacity: Option<u32>,
|
||||
/// A tag to recognize the entry, not used for other things than display
|
||||
pub tag: String,
|
||||
}
|
||||
|
||||
impl NetworkConfigEntry {
|
||||
pub fn capacity_string(&self) -> String {
|
||||
match self.capacity {
|
||||
Some(c) => format!("{}", c),
|
||||
None => "gateway".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A ring distributing fairly objects to nodes
|
||||
#[derive(Clone)]
|
||||
pub struct Ring {
|
||||
@@ -70,7 +28,7 @@ pub struct Ring {
|
||||
pub replication_factor: usize,
|
||||
|
||||
/// The network configuration used to generate this ring
|
||||
pub config: NetworkConfig,
|
||||
pub layout: ClusterLayout,
|
||||
|
||||
// Internal order of nodes used to make a more compact representation of the ring
|
||||
nodes: Vec<Uuid>,
|
||||
@@ -81,7 +39,7 @@ pub struct Ring {
|
||||
|
||||
// Type to store compactly the id of a node in the system
|
||||
// Change this to u16 the day we want to have more than 256 nodes in a cluster
|
||||
type CompactNodeType = u8;
|
||||
pub type CompactNodeType = u8;
|
||||
|
||||
// The maximum number of times an object might get replicated
|
||||
// This must be at least 3 because Garage supports 3-way replication
|
||||
@@ -102,132 +60,26 @@ struct RingEntry {
|
||||
}
|
||||
|
||||
impl Ring {
|
||||
// TODO this function MUST be refactored, it's 100 lines long, with a 50 lines loop, going up to 6
|
||||
// levels of imbrication. It is basically impossible to test, maintain, or understand for an
|
||||
// outsider.
|
||||
pub(crate) fn new(config: NetworkConfig, replication_factor: usize) -> Self {
|
||||
// Create a vector of partition indices (0 to 2**PARTITION_BITS-1)
|
||||
let partitions_idx = (0usize..(1usize << PARTITION_BITS)).collect::<Vec<_>>();
|
||||
|
||||
let zones = config
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(_id, info)| info.zone.as_str())
|
||||
.collect::<HashSet<&str>>();
|
||||
let n_zones = zones.len();
|
||||
|
||||
// Prepare ring
|
||||
let mut partitions: Vec<Vec<(&Uuid, &NetworkConfigEntry)>> = partitions_idx
|
||||
.iter()
|
||||
.map(|_i| Vec::new())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Create MagLev priority queues for each node
|
||||
let mut queues = config
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(node_id, node_info)| {
|
||||
let mut parts = partitions_idx
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let part_data =
|
||||
[&u16::to_be_bytes(*i as u16)[..], node_id.as_slice()].concat();
|
||||
(*i, fasthash(&part_data[..]))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
parts.sort_by_key(|(_i, h)| *h);
|
||||
let parts_i = parts.iter().map(|(i, _h)| *i).collect::<Vec<_>>();
|
||||
(node_id, node_info, parts_i, 0)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let max_capacity = config
|
||||
.members
|
||||
.iter()
|
||||
.filter_map(|(_, node_info)| node_info.capacity)
|
||||
.fold(0, std::cmp::max);
|
||||
|
||||
assert!(replication_factor <= MAX_REPLICATION);
|
||||
|
||||
// Fill up ring
|
||||
for rep in 0..replication_factor {
|
||||
queues.sort_by_key(|(ni, _np, _q, _p)| {
|
||||
let queue_data = [&u16::to_be_bytes(rep as u16)[..], ni.as_slice()].concat();
|
||||
fasthash(&queue_data[..])
|
||||
});
|
||||
|
||||
for (_, _, _, pos) in queues.iter_mut() {
|
||||
*pos = 0;
|
||||
}
|
||||
|
||||
let mut remaining = partitions_idx.len();
|
||||
while remaining > 0 {
|
||||
let remaining0 = remaining;
|
||||
for i_round in 0..max_capacity {
|
||||
for (node_id, node_info, q, pos) in queues.iter_mut() {
|
||||
if i_round >= node_info.capacity.unwrap() {
|
||||
continue;
|
||||
}
|
||||
for (pos2, &qv) in q.iter().enumerate().skip(*pos) {
|
||||
if partitions[qv].len() != rep {
|
||||
continue;
|
||||
}
|
||||
let p_zns = partitions[qv]
|
||||
.iter()
|
||||
.map(|(_id, info)| info.zone.as_str())
|
||||
.collect::<HashSet<&str>>();
|
||||
if (p_zns.len() < n_zones && !p_zns.contains(&node_info.zone.as_str()))
|
||||
|| (p_zns.len() == n_zones
|
||||
&& !partitions[qv].iter().any(|(id, _i)| id == node_id))
|
||||
{
|
||||
partitions[qv].push((node_id, node_info));
|
||||
remaining -= 1;
|
||||
*pos = pos2 + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if remaining == remaining0 {
|
||||
// No progress made, exit
|
||||
warn!("Could not build ring, not enough nodes configured.");
|
||||
return Self {
|
||||
replication_factor,
|
||||
config,
|
||||
nodes: vec![],
|
||||
ring: vec![],
|
||||
};
|
||||
}
|
||||
}
|
||||
pub(crate) fn new(layout: ClusterLayout, replication_factor: usize) -> Self {
|
||||
if replication_factor != layout.replication_factor {
|
||||
warn!("Could not build ring: replication factor does not match between local configuration and network role assignation.");
|
||||
return Self::empty(layout, replication_factor);
|
||||
}
|
||||
|
||||
// Make a canonical order for nodes
|
||||
let nodes = config
|
||||
.members
|
||||
.iter()
|
||||
.filter(|(_id, info)| info.capacity.is_some())
|
||||
.map(|(id, _)| *id)
|
||||
.collect::<Vec<_>>();
|
||||
let nodes_rev = nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, id)| (*id, i as CompactNodeType))
|
||||
.collect::<HashMap<Uuid, CompactNodeType>>();
|
||||
if layout.ring_assignation_data.len() != replication_factor * (1 << PARTITION_BITS) {
|
||||
warn!("Could not build ring: network role assignation data has invalid length");
|
||||
return Self::empty(layout, replication_factor);
|
||||
}
|
||||
|
||||
let ring = partitions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, nodes)| {
|
||||
let nodes = layout.node_id_vec.clone();
|
||||
let ring = (0..(1 << PARTITION_BITS))
|
||||
.map(|i| {
|
||||
let top = (i as u16) << (16 - PARTITION_BITS);
|
||||
let nodes = nodes
|
||||
.iter()
|
||||
.map(|(id, _info)| *nodes_rev.get(id).unwrap())
|
||||
.collect::<Vec<CompactNodeType>>();
|
||||
assert!(nodes.len() == replication_factor);
|
||||
let mut nodes_buf = [0u8; MAX_REPLICATION];
|
||||
nodes_buf[..replication_factor].copy_from_slice(&nodes[..]);
|
||||
nodes_buf[..replication_factor].copy_from_slice(
|
||||
&layout.ring_assignation_data
|
||||
[replication_factor * i..replication_factor * (i + 1)],
|
||||
);
|
||||
RingEntry {
|
||||
hash_prefix: top,
|
||||
nodes_buf,
|
||||
@@ -237,12 +89,21 @@ impl Ring {
|
||||
|
||||
Self {
|
||||
replication_factor,
|
||||
config,
|
||||
layout,
|
||||
nodes,
|
||||
ring,
|
||||
}
|
||||
}
|
||||
|
||||
fn empty(layout: ClusterLayout, replication_factor: usize) -> Self {
|
||||
Self {
|
||||
replication_factor,
|
||||
layout,
|
||||
nodes: vec![],
|
||||
ring: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the partition in which data would fall on
|
||||
pub fn partition_of(&self, position: &Hash) -> Partition {
|
||||
let top = u16::from_be_bytes(position.as_slice()[0..2].try_into().unwrap());
|
||||
|
||||
@@ -225,7 +225,7 @@ impl RpcHelper {
|
||||
// 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) {
|
||||
let our_zone = match ring.layout.node_role(&self.0.our_node_id) {
|
||||
Some(pc) => &pc.zone,
|
||||
None => "",
|
||||
};
|
||||
@@ -238,7 +238,7 @@ impl RpcHelper {
|
||||
// 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) {
|
||||
let peer_zone = match ring.layout.node_role(&to) {
|
||||
Some(pc) => &pc.zone,
|
||||
None => "",
|
||||
};
|
||||
|
||||
+59
-41
@@ -23,12 +23,13 @@ use netapp::{NetApp, NetworkKey, NodeID, NodeKey};
|
||||
|
||||
use garage_util::background::BackgroundRunner;
|
||||
use garage_util::config::Config;
|
||||
use garage_util::data::Uuid;
|
||||
use garage_util::data::*;
|
||||
use garage_util::error::*;
|
||||
use garage_util::persister::Persister;
|
||||
use garage_util::time::*;
|
||||
|
||||
use crate::consul::*;
|
||||
use crate::layout::*;
|
||||
use crate::ring::*;
|
||||
use crate::rpc_helper::*;
|
||||
|
||||
@@ -48,13 +49,13 @@ pub enum SystemRpc {
|
||||
Ok,
|
||||
/// Request to connect to a specific node (in <pubkey>@<host>:<port> format)
|
||||
Connect(String),
|
||||
/// Ask other node its config. Answered with AdvertiseConfig
|
||||
PullConfig,
|
||||
/// Ask other node its cluster layout. Answered with AdvertiseClusterLayout
|
||||
PullClusterLayout,
|
||||
/// 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),
|
||||
/// Advertisement of cluster layout. Sent spontanously or in response to PullClusterLayout
|
||||
AdvertiseClusterLayout(ClusterLayout),
|
||||
/// Get known nodes states
|
||||
GetKnownNodes,
|
||||
/// Return known nodes
|
||||
@@ -70,7 +71,7 @@ pub struct System {
|
||||
/// The id of this node
|
||||
pub id: Uuid,
|
||||
|
||||
persist_config: Persister<NetworkConfig>,
|
||||
persist_cluster_layout: Persister<ClusterLayout>,
|
||||
persist_peer_list: Persister<Vec<(Uuid, SocketAddr)>>,
|
||||
|
||||
local_status: ArcSwap<NodeStatus>,
|
||||
@@ -103,8 +104,10 @@ pub struct NodeStatus {
|
||||
pub hostname: String,
|
||||
/// Replication factor configured on the node
|
||||
pub replication_factor: usize,
|
||||
/// Configuration version
|
||||
pub config_version: u64,
|
||||
/// Cluster layout version
|
||||
pub cluster_layout_version: u64,
|
||||
/// Hash of cluster layout staging data
|
||||
pub cluster_layout_staging_hash: Hash,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -187,17 +190,17 @@ impl System {
|
||||
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_cluster_layout = Persister::new(&config.metadata_dir, "cluster_layout");
|
||||
let persist_peer_list = Persister::new(&config.metadata_dir, "peer_list");
|
||||
|
||||
let net_config = match persist_config.load() {
|
||||
let cluster_layout = match persist_cluster_layout.load() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
info!(
|
||||
"No valid previous network configuration stored ({}), starting fresh.",
|
||||
"No valid previous cluster layout stored ({}), starting fresh.",
|
||||
e
|
||||
);
|
||||
NetworkConfig::new()
|
||||
ClusterLayout::new(replication_factor)
|
||||
}
|
||||
};
|
||||
|
||||
@@ -206,10 +209,11 @@ impl System {
|
||||
.into_string()
|
||||
.unwrap_or_else(|_| "<invalid utf-8>".to_string()),
|
||||
replication_factor,
|
||||
config_version: net_config.version,
|
||||
cluster_layout_version: cluster_layout.version,
|
||||
cluster_layout_staging_hash: cluster_layout.staging_hash,
|
||||
};
|
||||
|
||||
let ring = Ring::new(net_config, replication_factor);
|
||||
let ring = Ring::new(cluster_layout, replication_factor);
|
||||
let (update_ring, ring) = watch::channel(Arc::new(ring));
|
||||
|
||||
if let Some(addr) = config.rpc_public_addr {
|
||||
@@ -229,7 +233,7 @@ impl System {
|
||||
|
||||
let sys = Arc::new(System {
|
||||
id: netapp.id.into(),
|
||||
persist_config,
|
||||
persist_cluster_layout,
|
||||
persist_peer_list,
|
||||
local_status: ArcSwap::new(Arc::new(local_status)),
|
||||
node_status: RwLock::new(HashMap::new()),
|
||||
@@ -292,12 +296,12 @@ impl System {
|
||||
}
|
||||
|
||||
/// Save network configuration to disc
|
||||
async fn save_network_config(self: Arc<Self>) -> Result<(), Error> {
|
||||
async fn save_cluster_layout(self: Arc<Self>) -> Result<(), Error> {
|
||||
let ring: Arc<Ring> = self.ring.borrow().clone();
|
||||
self.persist_config
|
||||
.save_async(&ring.config)
|
||||
self.persist_cluster_layout
|
||||
.save_async(&ring.layout)
|
||||
.await
|
||||
.expect("Cannot save current cluster configuration");
|
||||
.expect("Cannot save current cluster layout");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -305,7 +309,8 @@ impl System {
|
||||
let mut new_si: NodeStatus = self.local_status.load().as_ref().clone();
|
||||
|
||||
let ring = self.ring.borrow();
|
||||
new_si.config_version = ring.config.version;
|
||||
new_si.cluster_layout_version = ring.layout.version;
|
||||
new_si.cluster_layout_staging_hash = ring.layout.staging_hash;
|
||||
self.local_status.swap(Arc::new(new_si));
|
||||
}
|
||||
|
||||
@@ -337,9 +342,9 @@ impl System {
|
||||
)));
|
||||
}
|
||||
|
||||
fn handle_pull_config(&self) -> SystemRpc {
|
||||
fn handle_pull_cluster_layout(&self) -> SystemRpc {
|
||||
let ring = self.ring.borrow().clone();
|
||||
SystemRpc::AdvertiseConfig(ring.config.clone())
|
||||
SystemRpc::AdvertiseClusterLayout(ring.layout.clone())
|
||||
}
|
||||
|
||||
fn handle_get_known_nodes(&self) -> SystemRpc {
|
||||
@@ -360,7 +365,8 @@ impl System {
|
||||
.unwrap_or(NodeStatus {
|
||||
hostname: "?".to_string(),
|
||||
replication_factor: 0,
|
||||
config_version: 0,
|
||||
cluster_layout_version: 0,
|
||||
cluster_layout_staging_hash: Hash::from([0u8; 32]),
|
||||
}),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -381,10 +387,12 @@ impl System {
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
if info.config_version > local_info.config_version {
|
||||
if info.cluster_layout_version > local_info.cluster_layout_version
|
||||
|| info.cluster_layout_staging_hash != local_info.cluster_layout_staging_hash
|
||||
{
|
||||
let self2 = self.clone();
|
||||
self.background.spawn_cancellable(async move {
|
||||
self2.pull_config(from).await;
|
||||
self2.pull_cluster_layout(from).await;
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
@@ -397,32 +405,39 @@ impl System {
|
||||
Ok(SystemRpc::Ok)
|
||||
}
|
||||
|
||||
async fn handle_advertise_config(
|
||||
async fn handle_advertise_cluster_layout(
|
||||
self: Arc<Self>,
|
||||
adv: &NetworkConfig,
|
||||
adv: &ClusterLayout,
|
||||
) -> Result<SystemRpc, Error> {
|
||||
let update_ring = self.update_ring.lock().await;
|
||||
let ring: Arc<Ring> = self.ring.borrow().clone();
|
||||
let mut layout: ClusterLayout = self.ring.borrow().layout.clone();
|
||||
|
||||
if adv.version > ring.config.version {
|
||||
let ring = Ring::new(adv.clone(), self.replication_factor);
|
||||
let prev_layout_check = layout.check();
|
||||
if layout.merge(adv) {
|
||||
if prev_layout_check && !layout.check() {
|
||||
error!("New cluster layout is invalid, discarding.");
|
||||
return Err(Error::Message(
|
||||
"New cluster layout is invalid, discarding.".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let ring = Ring::new(layout.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),
|
||||
SystemRpc::AdvertiseClusterLayout(layout),
|
||||
RequestStrategy::with_priority(PRIO_HIGH),
|
||||
)
|
||||
.await;
|
||||
Ok(())
|
||||
});
|
||||
self.background.spawn(self.clone().save_network_config());
|
||||
self.background.spawn(self.clone().save_cluster_layout());
|
||||
}
|
||||
|
||||
Ok(SystemRpc::Ok)
|
||||
@@ -456,14 +471,15 @@ impl System {
|
||||
};
|
||||
|
||||
while !*stop_signal.borrow() {
|
||||
let not_configured = self.ring.borrow().config.members.is_empty();
|
||||
let not_configured = !self.ring.borrow().layout.check();
|
||||
let no_peers = self.fullmesh.get_peer_list().len() < self.replication_factor;
|
||||
let expected_n_nodes = self.ring.borrow().layout.num_nodes();
|
||||
let bad_peers = self
|
||||
.fullmesh
|
||||
.get_peer_list()
|
||||
.iter()
|
||||
.filter(|p| p.is_up())
|
||||
.count() != self.ring.borrow().config.members.len();
|
||||
.count() != expected_n_nodes;
|
||||
|
||||
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);
|
||||
@@ -533,18 +549,18 @@ impl System {
|
||||
self.persist_peer_list.save_async(&peer_list).await
|
||||
}
|
||||
|
||||
async fn pull_config(self: Arc<Self>, peer: Uuid) {
|
||||
async fn pull_cluster_layout(self: Arc<Self>, peer: Uuid) {
|
||||
let resp = self
|
||||
.rpc
|
||||
.call(
|
||||
&self.system_endpoint,
|
||||
peer,
|
||||
SystemRpc::PullConfig,
|
||||
SystemRpc::PullClusterLayout,
|
||||
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;
|
||||
if let Ok(SystemRpc::AdvertiseClusterLayout(layout)) = resp {
|
||||
let _: Result<_, _> = self.handle_advertise_cluster_layout(&layout).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -554,9 +570,11 @@ 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::PullClusterLayout => Ok(self.handle_pull_cluster_layout()),
|
||||
SystemRpc::AdvertiseStatus(adv) => self.handle_advertise_status(from.into(), adv).await,
|
||||
SystemRpc::AdvertiseConfig(adv) => self.clone().handle_advertise_config(adv).await,
|
||||
SystemRpc::AdvertiseClusterLayout(adv) => {
|
||||
self.clone().handle_advertise_cluster_layout(adv).await
|
||||
}
|
||||
SystemRpc::GetKnownNodes => Ok(self.handle_get_known_nodes()),
|
||||
_ => Err(Error::BadRpc("Unexpected RPC message".to_string())),
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_table"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "Table sharding and replication engine (DynamoDB-like) for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
@@ -13,8 +14,8 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_rpc = { version = "0.4.0", path = "../rpc" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
garage_rpc = { version = "0.5.0", path = "../rpc" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
|
||||
async-trait = "0.1.7"
|
||||
bytes = "1.0"
|
||||
|
||||
+3
-2
@@ -12,6 +12,7 @@ use garage_util::error::*;
|
||||
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)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+189
-45
@@ -1,4 +1,5 @@
|
||||
use std::collections::HashMap;
|
||||
use std::convert::TryInto;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -12,7 +13,8 @@ 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::system::System;
|
||||
use garage_rpc::*;
|
||||
@@ -24,7 +26,12 @@ 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 + 'static, R: TableReplication + 'static> {
|
||||
// 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>>,
|
||||
|
||||
@@ -72,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();
|
||||
@@ -136,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()
|
||||
@@ -146,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 {
|
||||
@@ -154,7 +203,7 @@ where
|
||||
}
|
||||
|
||||
if errs.is_empty() {
|
||||
Ok(true)
|
||||
Ok(None)
|
||||
} else {
|
||||
Err(Error::Message(
|
||||
errs.into_iter()
|
||||
@@ -162,23 +211,42 @@ 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));
|
||||
}
|
||||
|
||||
// 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(
|
||||
@@ -189,40 +257,43 @@ where
|
||||
.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
|
||||
);
|
||||
|
||||
// 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()),
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -240,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)
|
||||
}
|
||||
@@ -248,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
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -4,7 +4,6 @@
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
pub mod crdt;
|
||||
pub mod schema;
|
||||
pub mod util;
|
||||
|
||||
@@ -18,3 +17,7 @@ pub mod table;
|
||||
pub use schema::*;
|
||||
pub use table::*;
|
||||
pub use util::*;
|
||||
|
||||
pub mod crdt {
|
||||
pub use garage_util::crdt::*;
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ impl TableReplication for TableFullReplication {
|
||||
|
||||
fn write_nodes(&self, _hash: &Hash) -> Vec<Uuid> {
|
||||
let ring = self.system.ring.borrow();
|
||||
ring.config.members.keys().cloned().collect::<Vec<_>>()
|
||||
ring.layout.node_ids().to_vec()
|
||||
}
|
||||
fn write_quorum(&self) -> usize {
|
||||
let nmembers = self.system.ring.borrow().config.members.len();
|
||||
let nmembers = self.system.ring.borrow().layout.node_ids().len();
|
||||
if nmembers > self.max_faults {
|
||||
nmembers - self.max_faults
|
||||
} else {
|
||||
|
||||
+2
-1
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_util"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "Utility crate for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
|
||||
+4
-1
@@ -39,7 +39,7 @@ pub struct Config {
|
||||
pub rpc_public_addr: Option<SocketAddr>,
|
||||
|
||||
/// Bootstrap peers RPC address
|
||||
#[serde(deserialize_with = "deserialize_vec_addr")]
|
||||
#[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>,
|
||||
@@ -68,6 +68,9 @@ pub struct ApiConfig {
|
||||
pub api_bind_addr: SocketAddr,
|
||||
/// S3 region to use
|
||||
pub s3_region: String,
|
||||
/// Suffix to remove from domain name to find bucket. If None,
|
||||
/// vhost-style S3 request are disabled
|
||||
pub root_domain: Option<String>,
|
||||
}
|
||||
|
||||
/// Configuration for serving files as normal web server
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use garage_util::data::*;
|
||||
use crate::data::*;
|
||||
|
||||
/// Definition of a CRDT - all CRDT Rust types implement this.
|
||||
///
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use garage_util::time::now_msec;
|
||||
use crate::time::now_msec;
|
||||
|
||||
use crate::crdt::crdt::*;
|
||||
|
||||
@@ -104,11 +106,15 @@ where
|
||||
T: Clone + Crdt,
|
||||
{
|
||||
fn merge(&mut self, other: &Self) {
|
||||
if other.ts > self.ts {
|
||||
self.ts = other.ts;
|
||||
self.v = other.v.clone();
|
||||
} else if other.ts == self.ts {
|
||||
self.v.merge(&other.v);
|
||||
match other.ts.cmp(&self.ts) {
|
||||
Ordering::Greater => {
|
||||
self.ts = other.ts;
|
||||
self.v = other.v.clone();
|
||||
}
|
||||
Ordering::Equal => {
|
||||
self.v.merge(&other.v);
|
||||
}
|
||||
Ordering::Less => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use std::cmp::Ordering;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use garage_util::time::now_msec;
|
||||
use crate::time::now_msec;
|
||||
|
||||
use crate::crdt::crdt::*;
|
||||
|
||||
@@ -135,11 +137,15 @@ where
|
||||
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);
|
||||
match ts2.cmp(ts1) {
|
||||
Ordering::Greater => {
|
||||
self.vals[i].1 = *ts2;
|
||||
self.vals[i].2 = v2.clone();
|
||||
}
|
||||
Ordering::Equal => {
|
||||
self.vals[i].2.merge(v2);
|
||||
}
|
||||
Ordering::Less => (),
|
||||
}
|
||||
}
|
||||
Err(i) => {
|
||||
@@ -5,6 +5,7 @@ extern crate log;
|
||||
|
||||
pub mod background;
|
||||
pub mod config;
|
||||
pub mod crdt;
|
||||
pub mod data;
|
||||
pub mod error;
|
||||
pub mod persister;
|
||||
|
||||
+6
-6
@@ -1,11 +1,12 @@
|
||||
[package]
|
||||
name = "garage_web"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
authors = ["Alex Auvolat <alex@adnab.me>", "Quentin Dufour <quentin@dufour.io>"]
|
||||
edition = "2018"
|
||||
license = "AGPL-3.0"
|
||||
description = "S3-like website endpoint crate for the Garage object store"
|
||||
repository = "https://git.deuxfleurs.fr/Deuxfleurs/garage"
|
||||
readme = "../../README.md"
|
||||
|
||||
[lib]
|
||||
path = "lib.rs"
|
||||
@@ -13,13 +14,12 @@ path = "lib.rs"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
garage_api = { version = "0.4.0", path = "../api" }
|
||||
garage_model = { version = "0.4.0", path = "../model" }
|
||||
garage_util = { version = "0.4.0", path = "../util" }
|
||||
garage_table = { version = "0.4.0", path = "../table" }
|
||||
garage_api = { version = "0.5.0", path = "../api" }
|
||||
garage_model = { version = "0.5.0", path = "../model" }
|
||||
garage_util = { version = "0.5.0", path = "../util" }
|
||||
garage_table = { version = "0.5.0", path = "../table" }
|
||||
|
||||
err-derive = "0.3"
|
||||
idna = "0.2"
|
||||
log = "0.4"
|
||||
percent-encoding = "2.1.0"
|
||||
|
||||
|
||||
+10
-1
@@ -1,5 +1,6 @@
|
||||
use err_derive::Error;
|
||||
use hyper::StatusCode;
|
||||
use hyper::header::HeaderValue;
|
||||
use hyper::{HeaderMap, StatusCode};
|
||||
|
||||
use garage_util::error::Error as GarageError;
|
||||
|
||||
@@ -47,4 +48,12 @@ impl Error {
|
||||
_ => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_headers(&self, header_map: &mut HeaderMap<HeaderValue>) {
|
||||
#[allow(clippy::single_match)]
|
||||
match self {
|
||||
Error::ApiError(e) => e.add_headers(header_map),
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-111
@@ -9,9 +9,8 @@ use hyper::{
|
||||
Body, Method, Request, Response, Server,
|
||||
};
|
||||
|
||||
use idna::domain_to_unicode;
|
||||
|
||||
use crate::error::*;
|
||||
use garage_api::helpers::{authority_to_host, host_to_bucket};
|
||||
use garage_api::s3_get::{handle_get, handle_head};
|
||||
use garage_model::bucket_table::*;
|
||||
use garage_model::garage::Garage;
|
||||
@@ -63,6 +62,7 @@ fn error_to_res(e: Error) -> Response<Body> {
|
||||
let body: Body = Body::from(format!("{}\n", e));
|
||||
let mut http_error = Response::new(body);
|
||||
*http_error.status_mut() = e.http_status_code();
|
||||
e.add_headers(http_error.headers_mut());
|
||||
http_error
|
||||
}
|
||||
|
||||
@@ -75,9 +75,9 @@ async fn serve_file(garage: Arc<Garage>, req: Request<Body>) -> Result<Response<
|
||||
.to_str()?;
|
||||
|
||||
// Get bucket
|
||||
let (host, _) = domain_to_unicode(authority_to_host(authority)?);
|
||||
let host = authority_to_host(authority)?;
|
||||
let root = &garage.config.s3_web.root_domain;
|
||||
let bucket = host_to_bucket(&host, root);
|
||||
let bucket = host_to_bucket(&host, root).unwrap_or(&host);
|
||||
|
||||
// Check bucket is exposed as a website
|
||||
let bucket_desc = garage
|
||||
@@ -108,65 +108,6 @@ async fn serve_file(garage: Arc<Garage>, req: Request<Body>) -> Result<Response<
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Extract host from the authority section given by the HTTP host header
|
||||
///
|
||||
/// The HTTP host contains both a host and a port.
|
||||
/// Extracting the port is more complex than just finding the colon (:) symbol due to IPv6
|
||||
/// We do not use the collect pattern as there is no way in std rust to collect over a stack allocated value
|
||||
/// check here: https://docs.rs/collect_slice/1.2.0/collect_slice/
|
||||
fn authority_to_host(authority: &str) -> Result<&str, Error> {
|
||||
let mut iter = authority.chars().enumerate();
|
||||
let (_, first_char) = iter
|
||||
.next()
|
||||
.ok_or_else(|| Error::BadRequest("Authority is empty".to_string()))?;
|
||||
|
||||
let split = match first_char {
|
||||
'[' => {
|
||||
let mut iter = iter.skip_while(|(_, c)| c != &']');
|
||||
match iter.next() {
|
||||
Some((_, ']')) => iter.next(),
|
||||
_ => {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"Authority {} has an illegal format",
|
||||
authority
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => iter.find(|(_, c)| *c == ':'),
|
||||
};
|
||||
|
||||
match split {
|
||||
Some((i, ':')) => Ok(&authority[..i]),
|
||||
None => Ok(authority),
|
||||
Some((_, _)) => Err(Error::BadRequest(format!(
|
||||
"Authority {} has an illegal format",
|
||||
authority
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Host to bucket
|
||||
///
|
||||
/// Convert a host, like "bucket.garage-site.tld" or "john.doe.com"
|
||||
/// to the corresponding bucket, resp. "bucket" and "john.doe.com"
|
||||
/// considering that ".garage-site.tld" is the "root domain".
|
||||
/// This behavior has been chosen to follow AWS S3 semantic.
|
||||
fn host_to_bucket<'a>(host: &'a str, root: &str) -> &'a str {
|
||||
if root.len() >= host.len() || !host.ends_with(root) {
|
||||
return host;
|
||||
}
|
||||
|
||||
let len_diff = host.len() - root.len();
|
||||
let missing_starting_dot = !root.starts_with('.');
|
||||
let cursor = if missing_starting_dot {
|
||||
len_diff - 1
|
||||
} else {
|
||||
len_diff
|
||||
};
|
||||
&host[..cursor]
|
||||
}
|
||||
|
||||
/// Path to key
|
||||
///
|
||||
/// Convert the provided path to the internal key
|
||||
@@ -200,54 +141,6 @@ fn path_to_key<'a>(path: &'a str, index: &str) -> Result<Cow<'a, str>, Error> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn authority_to_host_with_port() -> Result<(), Error> {
|
||||
let domain = authority_to_host("[::1]:3902")?;
|
||||
assert_eq!(domain, "[::1]");
|
||||
let domain2 = authority_to_host("garage.tld:65200")?;
|
||||
assert_eq!(domain2, "garage.tld");
|
||||
let domain3 = authority_to_host("127.0.0.1:80")?;
|
||||
assert_eq!(domain3, "127.0.0.1");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authority_to_host_without_port() -> Result<(), Error> {
|
||||
let domain = authority_to_host("[::1]")?;
|
||||
assert_eq!(domain, "[::1]");
|
||||
let domain2 = authority_to_host("garage.tld")?;
|
||||
assert_eq!(domain2, "garage.tld");
|
||||
let domain3 = authority_to_host("127.0.0.1")?;
|
||||
assert_eq!(domain3, "127.0.0.1");
|
||||
assert!(authority_to_host("[").is_err());
|
||||
assert!(authority_to_host("[hello").is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_to_bucket_test() {
|
||||
assert_eq!(
|
||||
host_to_bucket("john.doe.garage.tld", ".garage.tld"),
|
||||
"john.doe"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
host_to_bucket("john.doe.garage.tld", "garage.tld"),
|
||||
"john.doe"
|
||||
);
|
||||
|
||||
assert_eq!(host_to_bucket("john.doe.com", "garage.tld"), "john.doe.com");
|
||||
|
||||
assert_eq!(
|
||||
host_to_bucket("john.doe.com", ".garage.tld"),
|
||||
"john.doe.com"
|
||||
);
|
||||
|
||||
assert_eq!(host_to_bucket("garage.tld", "garage.tld"), "garage.tld");
|
||||
|
||||
assert_eq!(host_to_bucket("garage.tld", ".garage.tld"), "garage.tld");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_to_key_test() -> Result<(), Error> {
|
||||
assert_eq!(path_to_key("/file%20.jpg", "index.html")?, "file .jpg");
|
||||
|
||||
Reference in New Issue
Block a user