Compare commits

..

6 Commits

Author SHA1 Message Date
trinity-1686a 45f44023a8 and again 2026-03-05 23:44:11 +01:00
trinity-1686a 173a54a83c identical but maybe valid 2026-03-05 23:41:20 +01:00
trinity-1686a 41c943a6b1 this schema is known-broken, but hey 2026-03-05 12:40:05 +01:00
trinity-1686a 84c1e189c4 this schema is known-broken, but hey 2026-03-05 11:20:42 +01:00
trinity-1686a dc8355d0f3 edit openapi by hand 😭 2026-03-05 11:03:58 +01:00
trinity-1686a 1c12ca4caf modify schema in a compatible way to maybe fix typescript sdk 2026-03-05 00:13:55 +01:00
154 changed files with 831 additions and 1003 deletions
-10
View File
@@ -16,16 +16,6 @@ steps:
commands: commands:
- nix-build -j4 --attr flakePackages.fmt - nix-build -j4 --attr flakePackages.fmt
- name: check typos
image: nixpkgs/nix:nixos-24.05
commands:
- nix-shell --attr ci --run typos
- name: check lints with clippy
image: nixpkgs/nix:nixos-24.05
commands:
- nix-build -j4 --attr flakePackages.clippy
- name: build - name: build
image: nixpkgs/nix:nixos-24.05 image: nixpkgs/nix:nixos-24.05
commands: commands:
+5 -5
View File
@@ -39,7 +39,7 @@ garage_web = { version = "2.2.0", path = "src/web" }
k2v-client = { version = "0.0.4", path = "src/k2v-client" } k2v-client = { version = "0.0.4", path = "src/k2v-client" }
# External crates from crates.io # External crates from crates.io
arc-swap = "1.1" arc-swap = "1.0"
argon2 = "0.5" argon2 = "0.5"
async-trait = "0.1.7" async-trait = "0.1.7"
backtrace = "0.3" backtrace = "0.3"
@@ -95,7 +95,7 @@ fjall = "2.4"
async-compression = { version = "0.4", features = ["tokio", "zstd"] } async-compression = { version = "0.4", features = ["tokio", "zstd"] }
zstd = { version = "0.13", default-features = false } zstd = { version = "0.13", default-features = false }
quick-xml = { version = "0.26", features = ["serialize"] } quick-xml = { version = "0.26", features = [ "serialize" ] }
rmp-serde = "1.1.2" rmp-serde = "1.1.2"
serde = { version = "1.0", default-features = false, features = ["derive", "rc"] } serde = { version = "1.0", default-features = false, features = ["derive", "rc"] }
serde_bytes = "0.11" serde_bytes = "0.11"
@@ -115,7 +115,7 @@ httpdate = "1.0"
http-range = "0.1" http-range = "0.1"
http-body-util = "0.1" http-body-util = "0.1"
hyper = { version = "1.0", default-features = false } hyper = { version = "1.0", default-features = false }
hyper-util = { version = "0.1", features = ["full"] } hyper-util = { version = "0.1", features = [ "full" ] }
multer = "3.0" multer = "3.0"
percent-encoding = "2.2" percent-encoding = "2.2"
roxmltree = "0.19" roxmltree = "0.19"
@@ -123,11 +123,11 @@ url = "2.3"
futures = "0.3" futures = "0.3"
futures-util = "0.3" futures-util = "0.3"
tokio = { version = "1.0", default-features = false, features = ["rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] } tokio = { version = "1.0", default-features = false, features = ["net", "rt", "rt-multi-thread", "io-util", "net", "time", "macros", "sync", "signal", "fs"] }
tokio-util = { version = "0.7", features = ["compat", "io"] } tokio-util = { version = "0.7", features = ["compat", "io"] }
tokio-stream = { version = "0.1", features = ["net"] } tokio-stream = { version = "0.1", features = ["net"] }
opentelemetry = { version = "0.17", features = ["rt-tokio", "metrics", "trace"] } opentelemetry = { version = "0.17", features = [ "rt-tokio", "metrics", "trace" ] }
opentelemetry-prometheus = "0.10" opentelemetry-prometheus = "0.10"
opentelemetry-otlp = "0.10" opentelemetry-otlp = "0.10"
opentelemetry-contrib = "0.9" opentelemetry-contrib = "0.9"
+4 -4
View File
@@ -3,10 +3,10 @@ info:
version: v0.8.0 version: v0.8.0
title: Garage Administration API v0+garage-v0.8.0 title: Garage Administration API v0+garage-v0.8.0
description: | description: |
Administrate your Garage cluster programmatically, including status, layout, keys, buckets, and maintenance tasks. Administrate your Garage cluster programatically, including status, layout, keys, buckets, and maintainance tasks.
*Disclaimer: The API is not stable yet, hence its v0 tag. The API can change at any time, and changes can include breaking backward compatibility. Read the changelog and upgrade your scripts before upgrading. Additionally, this specification is very early stage and can contain bugs, especially on error return codes/types that are not tested yet. Do not expect a well finished and polished product!* *Disclaimer: The API is not stable yet, hence its v0 tag. The API can change at any time, and changes can include breaking backward compatibility. Read the changelog and upgrade your scripts before upgrading. Additionnaly, this specification is very early stage and can contain bugs, especially on error return codes/types that are not tested yet. Do not expect a well finished and polished product!*
paths: paths:
/status: /status:
get: get:
tags: tags:
+5 -5
View File
@@ -3,10 +3,10 @@ info:
version: v0.9.0 version: v0.9.0
title: Garage Administration API v0+garage-v0.9.0 title: Garage Administration API v0+garage-v0.9.0
description: | description: |
Administrate your Garage cluster programmatically, including status, layout, keys, buckets, and maintenance tasks. Administrate your Garage cluster programatically, including status, layout, keys, buckets, and maintainance tasks.
*Disclaimer: The API is not stable yet, hence its v0 tag. The API can change at any time, and changes can include breaking backward compatibility. Read the changelog and upgrade your scripts before upgrading. Additionally, this specification is very early stage and can contain bugs, especially on error return codes/types that are not tested yet. Do not expect a well finished and polished product!* *Disclaimer: The API is not stable yet, hence its v0 tag. The API can change at any time, and changes can include breaking backward compatibility. Read the changelog and upgrade your scripts before upgrading. Additionnaly, this specification is very early stage and can contain bugs, especially on error return codes/types that are not tested yet. Do not expect a well finished and polished product!*
paths: paths:
/health: /health:
get: get:
tags: tags:
@@ -440,7 +440,7 @@ paths:
- "false" - "false"
example: "true" example: "true"
required: false required: false
description: "Whether or not the secret key should be returned in the response" description: "Wether or not the secret key should be returned in the response"
responses: responses:
'500': '500':
description: "The server can not handle your request. Check your connectivity with the rest of the cluster." description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+47 -48
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0", "openapi": "3.1.0",
"info": { "info": {
"title": "Garage administration API", "title": "Garage administration API",
"description": "Administrate your Garage cluster programmatically, including status, layout, keys, buckets, and maintenance tasks.\n\n*Disclaimer: This API may change in future Garage versions. Read the changelog and upgrade your scripts before upgrading. Additionally, this specification is early stage and can contain bugs, so be careful and please report any issues on our issue tracker.*", "description": "Administrate your Garage cluster programatically, including status, layout, keys, buckets, and maintainance tasks.\n\n*Disclaimer: This API may change in future Garage versions. Read the changelog and upgrade your scripts before upgrading. Additionnaly, this specification is early stage and can contain bugs, so be careful and please report any issues on our issue tracker.*",
"contact": { "contact": {
"name": "The Garage team", "name": "The Garage team",
"url": "https://garagehq.deuxfleurs.fr/", "url": "https://garagehq.deuxfleurs.fr/",
@@ -2394,7 +2394,7 @@
}, },
"websiteAccess": { "websiteAccess": {
"type": "boolean", "type": "boolean",
"description": "Whether website access is enabled for this bucket" "description": "Whether website acces is enabled for this bucket"
}, },
"websiteConfig": { "websiteConfig": {
"oneOf": [ "oneOf": [
@@ -2441,7 +2441,7 @@
"properties": { "properties": {
"connectedNodes": { "connectedNodes": {
"type": "integer", "type": "integer",
"description": "the number of nodes this Garage node currently has an open connection to", "description": "the nubmer of nodes this Garage node currently has an open connection to",
"minimum": 0 "minimum": 0
}, },
"knownNodes": { "knownNodes": {
@@ -3922,23 +3922,26 @@
} }
}, },
{ {
"allOf": [ "$ref": "#/components/schemas/NodeRoleUpdate"
{ }
"$ref": "#/components/schemas/NodeAssignedRole" ]
}, },
{ "NodeRoleUpdate": {
"type": "object", "allOf": [
"required": [ {
"id" "$ref": "#/components/schemas/NodeAssignedRole"
], },
"properties": { {
"id": { "type": "object",
"type": "string", "required": [
"description": "ID of the node for which this change applies" "id"
} ],
} "properties": {
"id": {
"type": "string",
"description": "ID of the node for which this change applies"
} }
] }
} }
] ]
}, },
@@ -4350,43 +4353,39 @@
"WorkerStateResp": { "WorkerStateResp": {
"oneOf": [ "oneOf": [
{ {
"type": "string", "$ref": "#/components/schemas/Yolo"
"enum": [ },
"busy"
]
},
{ {
"$ref": "#/components/schemas/WorkerStateRespStrs"
}
]
},
"Yolo": {
"type": "object",
"required": [
"throttled"
],
"properties": {
"throttled": {
"type": "object", "type": "object",
"required": [ "required": [
"throttled" "durationSecs"
], ],
"properties": { "properties": {
"throttled": { "durationSecs": {
"type": "object", "type": "number",
"required": [ "format": "float"
"durationSecs"
],
"properties": {
"durationSecs": {
"type": "number",
"format": "float"
}
}
} }
} }
},
{
"type": "string",
"enum": [
"idle"
]
},
{
"type": "string",
"enum": [
"done"
]
} }
}
},
"WorkerStateRespStrs": {
"type": "string",
"enum": [
"busy",
"idle",
"done"
] ]
}, },
"ZoneRedundancy": { "ZoneRedundancy": {
+1 -1
View File
@@ -51,4 +51,4 @@ We are currently building this SDK for [Python](@/documentation/build/python.md#
More information: More information:
- [In the reference manual](@/documentation/reference-manual/admin-api.md) - [In the reference manual](@/documentation/reference-manual/admin-api.md)
- [Full specification](https://garagehq.deuxfleurs.fr/api/garage-admin-v0.html) - [Full specifiction](https://garagehq.deuxfleurs.fr/api/garage-admin-v0.html)
+3 -3
View File
@@ -5,13 +5,13 @@ weight = 99
## S3 ## S3
If you are developing a new application, you may want to use Garage to store your user's media. 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, 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. 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.
Developing your own wrapper around the REST API is time consuming and complicated. Developping your own wrapper around the REST API is time consuming and complicated.
Instead, there are some libraries already available. Instead, there are some libraries already avalaible.
Some of them are maintained by Amazon, some by Minio, others by the community. Some of them are maintained by Amazon, some by Minio, others by the community.
+1 -1
View File
@@ -23,7 +23,7 @@ To configure S3-compatible software to interact with Garage,
you will need the following parameters: you will need the following parameters:
- An **API endpoint**: this corresponds to the HTTP or HTTPS address - An **API endpoint**: this corresponds to the HTTP or HTTPS address
used to contact the Garage server. When running Garage locally this will usually used to contact the Garage server. When runing Garage locally this will usually
be `http://127.0.0.1:3900`. In a real-world setting, you would usually have a reverse-proxy be `http://127.0.0.1:3900`. In a real-world setting, you would usually have a reverse-proxy
that adds TLS support and makes your Garage server available under a public hostname that adds TLS support and makes your Garage server available under a public hostname
such as `https://garage.example.com`. such as `https://garage.example.com`.
+5 -5
View File
@@ -54,7 +54,7 @@ garage bucket allow nextcloud --read --write --key nextcloud-key
Now edit your Nextcloud configuration file to enable object storage. Now edit your Nextcloud configuration file to enable object storage.
On my installation, the config. file is located at the following path: `/var/www/nextcloud/config/config.php`. On my installation, the config. file is located at the following path: `/var/www/nextcloud/config/config.php`.
We will add a new root key to the `$CONFIG` dictionary named `objectstore`: We will add a new root key to the `$CONFIG` dictionnary named `objectstore`:
```php ```php
<?php <?php
@@ -413,7 +413,7 @@ mc mirror --newer-than "3h" ./public/system/ garage/mastodon-data
## Matrix ## Matrix
Matrix is a chat communication protocol. Its main stable server implementation, [Synapse](https://matrix-org.github.io/synapse/latest/), provides a module to store media on a S3 backend. Additionally, a server independent media store supporting S3 has been developed 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. Matrix is a chat communication protocol. Its main stable server implementation, [Synapse](https://matrix-org.github.io/synapse/latest/), provides a module to store media on a S3 backend. Additionally, a server independent media store supporting S3 has been developped by the community, it has been made possible thanks to how the matrix API has been designed and will work with implementations like Conduit, Dendrite, etc.
### synapse-s3-storage-provider (synapse only) ### synapse-s3-storage-provider (synapse only)
@@ -450,7 +450,7 @@ media_storage_providers:
Note that uploaded media will also be stored locally and this behavior can not be deactivated, it is even required for 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. some operations like resizing images.
In fact, your local filesystem is considered as a cache but without any automated way to garbage collect it. 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. 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: If you installed the module with the command provided before, you should be able to bring it in your path:
@@ -646,7 +646,7 @@ s3:
b2-eu-cen: # Don't change this key, it is hardcoded b2-eu-cen: # Don't change this key, it is hardcoded
key: <keyID> key: <keyID>
secret: <keySecret> secret: <keySecret>
endpoint: garage:3900 # publicly accessible endpoint of your garage instance endpoint: garage:3900 # publically accessible endpoint of your garage instance
region: garage region: garage
bucket: <yourbucketName> bucket: <yourbucketName>
use_path_style: true use_path_style: true
@@ -730,7 +730,7 @@ Pleroma have an internal migration tool that can encounter some fatal error
So, use [your best tool](https://garagehq.deuxfleurs.fr/documentation/connect/cli/) to sync `/var/lib/pleroma/uploads/` in your S3. So, use [your best tool](https://garagehq.deuxfleurs.fr/documentation/connect/cli/) to sync `/var/lib/pleroma/uploads/` in your S3.
Then, to avoid some non existent problem (just in case of), run this command Then, to avoid some non existant problem (just in case of), run this command
```bash ```bash
while true while true
+2 -2
View File
@@ -41,7 +41,7 @@ Some commands:
# list buckets # list buckets
mc ls garage/ mc ls garage/
# list objects in a bucket # list objets in a bucket
mc ls garage/my_files mc ls garage/my_files
# copy from your filesystem to garage # copy from your filesystem to garage
@@ -218,7 +218,7 @@ Within Cyberduck, a
available within the `Preferences -> Profiles` section. This can enabled and available within the `Preferences -> Profiles` section. This can enabled and
then connections to Garage may be configured. then connections to Garage may be configured.
### Instructions for the CLI ### Instuctions for the CLI
To configure duck (Cyberduck's CLI tool), start by creating its folder hierarchy: To configure duck (Cyberduck's CLI tool), start by creating its folder hierarchy:
+3 -1
View File
@@ -201,9 +201,11 @@ on the binary cache, the client will download the result from the cache instead
### Channels ### Channels
Channels additionally serve Nix definitions, ie. a `.nix` file referencing Channels additionnaly serve Nix definitions, ie. a `.nix` file referencing
all the derivations you want to serve. all the derivations you want to serve.
## Gitlab ## Gitlab
*External link:* [Gitlab Documentation > Object storage](https://docs.gitlab.com/ee/administration/object_storage.html) *External link:* [Gitlab Documentation > Object storage](https://docs.gitlab.com/ee/administration/object_storage.html)
+1 -1
View File
@@ -13,7 +13,7 @@ have published Ansible roles. We list them and compare them below.
| **Runtime** | Systemd | Docker | Systemd | | **Runtime** | Systemd | Docker | Systemd |
| **Target OS** | Any Linux | Any Linux | Any Linux | | **Target OS** | Any Linux | Any Linux | Any Linux |
| **Architecture** | amd64, arm64, i686 | amd64, arm64 | arm64, arm, 386, amd64 | | **Architecture** | amd64, arm64, i686 | amd64, arm64 | arm64, arm, 386, amd64 |
| **Additional software** | None | Traefik | Nginx and Keepalived (optional) | | **Additional software** | None | Traefik | Ngnix and Keepalived (optional) |
| **Automatic node connection** | ❌ | ✅ | ✅ | | **Automatic node connection** | ❌ | ✅ | ✅ |
| **Layout management** | ❌ | ✅ | ✅ | | **Layout management** | ❌ | ✅ | ✅ |
| **Manage buckets & keys** | ❌ | ✅ (basic) | ✅ | | **Manage buckets & keys** | ❌ | ✅ (basic) | ✅ |
+4 -4
View File
@@ -33,7 +33,7 @@ by adding encryption at different levels.
We would be very curious to know your needs and thougs about ideas such as We would be very curious to know your needs and thougs about ideas such as
encryption practices and things like key management, as we want Garage to be a encryption practices and things like key management, as we want Garage to be a
serious base platform for the development of secure, encrypted applications. serious base platform for the developpment of secure, encrypted applications.
Do not hesitate to come talk to us if you have any thoughts or questions on the Do not hesitate to come talk to us if you have any thoughts or questions on the
subject. subject.
@@ -59,7 +59,7 @@ For standard S3 API requests, Garage does not encrypt data at rest by itself.
For the most generic at rest encryption of data, we recommend setting up your For the most generic at rest encryption of data, we recommend setting up your
storage partitions on encrypted LUKS devices. storage partitions on encrypted LUKS devices.
If you are developing your own client software that makes use of S3 storage, If you are developping your own client software that makes use of S3 storage,
we recommend implementing data encryption directly on the client side and never we recommend implementing data encryption directly on the client side and never
transmitting plaintext data to Garage. This makes it easy to use an external transmitting plaintext data to Garage. This makes it easy to use an external
untrusted storage provider if necessary. untrusted storage provider if necessary.
@@ -108,14 +108,14 @@ Protects against the following threats:
- Stolen HDD - Stolen HDD
Crucially, does not protect against malicious sysadmins or remote attackers that Crucially, does not protect againt malicious sysadmins or remote attackers that
might gain access to your servers. might gain access to your servers.
Methods include full-disk encryption with tools such as LUKS. Methods include full-disk encryption with tools such as LUKS.
## Encrypting data on the client side ## Encrypting data on the client side
Protects against the following threats: Protects againt the following threats:
- A honest-but-curious administrator - A honest-but-curious administrator
- A malicious administrator that tries to corrupt your data - A malicious administrator that tries to corrupt your data
+1 -1
View File
@@ -9,7 +9,7 @@ There are three methods to expose buckets as website:
1. using the PutBucketWebsite S3 API call, which is allowed for access keys that have the owner permission bit set 1. using the PutBucketWebsite S3 API call, which is allowed for access keys that have the owner permission bit set
2. from the Garage CLI, by an administrator of the cluster 2. from the Garage CLI, by an adminstrator of the cluster
3. using the Garage administration API 3. using the Garage administration API
+2 -2
View File
@@ -25,7 +25,7 @@ sudo apt-get install build-essential
The primary location for Garage's source code is the The primary location for Garage's source code is the
[Forgejo repository](https://git.deuxfleurs.fr/Deuxfleurs/garage), [Forgejo repository](https://git.deuxfleurs.fr/Deuxfleurs/garage),
which contains all of the released versions as well as the code which contains all of the released versions as well as the code
for the development of the next version. for the developpement of the next version.
Clone the repository and enter it as follows: Clone the repository and enter it as follows:
@@ -41,7 +41,7 @@ git tag # List available tags
git checkout v0.8.0 # Change v0.8.0 with the version you wish to build git checkout v0.8.0 # Change v0.8.0 with the version you wish to build
``` ```
Otherwise you will be building a development build from the `main` branch Otherwise you will be building a developpement build from the `main` branch
that includes all of the changes to be released in the next version. that includes all of the changes to be released in the next version.
Be careful that such a build might be unstable or contain bugs, Be careful that such a build might be unstable or contain bugs,
and could be incompatible with nodes that run stable versions of Garage. and could be incompatible with nodes that run stable versions of Garage.
+2 -2
View File
@@ -26,7 +26,7 @@ Or deploy with custom values:
helm install --create-namespace --namespace garage garage ./garage -f values.override.yaml helm install --create-namespace --namespace garage garage ./garage -f values.override.yaml
``` ```
If you want to manage the CustomResourceDefinition used by garage for its `kubernetes_discovery` outside of the helm chart, add `garage.kubernetesSkipCrd: true` to your custom values and use the kustomization before deploying the helm chart: If you want to manage the CustomRessourceDefinition used by garage for its `kubernetes_discovery` outside of the helm chart, add `garage.kubernetesSkipCrd: true` to your custom values and use the kustomization before deploying the helm chart:
```bash ```bash
kubectl apply -k ../k8s/crd kubectl apply -k ../k8s/crd
@@ -47,7 +47,7 @@ All possible configuration values can be found with:
helm show values ./garage helm show values ./garage
``` ```
This is an example `values.override.yaml` for deploying in a microk8s cluster with a https s3 api ingress route: This is an example `values.overrride.yaml` for deploying in a microk8s cluster with a https s3 api ingress route:
```yaml ```yaml
garage: garage:
+1 -1
View File
@@ -272,7 +272,7 @@ Add the following configuration section [to compress response](https://doc.traef
### Add caching response ### Add caching response
Traefik's caching middleware is only available on [enterprise version](https://doc.traefik.io/traefik-enterprise/middlewares/http-cache/), however the freely-available [Souin plugin](https://github.com/darkweak/souin#tr%C3%A6fik-container) can also do the job. (section to be completed) Traefik's caching middleware is only available on [entreprise version](https://doc.traefik.io/traefik-enterprise/middlewares/http-cache/), however the freely-available [Souin plugin](https://github.com/darkweak/souin#tr%C3%A6fik-container) can also do the job. (section to be completed)
### Complete example ### Complete example
+1 -1
View File
@@ -38,7 +38,7 @@ WantedBy=multi-user.target
id is dynamically allocated by systemd (set with `DynamicUser=true`). It cannot id is dynamically allocated by systemd (set with `DynamicUser=true`). It cannot
access (read or write) home folders (`/home`, `/root` and `/run/user`), the 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 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. Additionally, the process `/var/lib/garage` is writable as seen by the service. Additionnaly, the process
can not gain new privileges over time. can not gain new privileges over time.
For this to work correctly, your `garage.toml` must be set with For this to work correctly, your `garage.toml` must be set with
+3 -1
View File
@@ -10,7 +10,7 @@ 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 you, how to better use it, how to contribute to it, what can Garage could
and could not do, etc. and could not do, etc.
- **[Goals and use cases](@/documentation/design/goals.md):** This page explains why Garage was conceived and what practical use cases it targets. - **[Goals and use cases](@/documentation/design/goals.md):** This page explains why Garage was concieved and what practical use cases it targets.
- **[Related work](@/documentation/design/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. - **[Related work](@/documentation/design/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.
@@ -31,3 +31,5 @@ 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/src/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2021-04-28_spirals-team/talk.pdf) - [(en, 2021-04-28) Distributed object storage is centralised](https://git.deuxfleurs.fr/Deuxfleurs/garage/src/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/src/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2020-12-02_wide-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/src/commit/b1f60579a13d3c5eba7f74b1775c84639ea9b51a/doc/talks/2020-12-02_wide-team/talk.pdf)
+5 -5
View File
@@ -15,14 +15,14 @@ The more a user request will require intra-cluster requests to complete, the mor
This is especially true for sequential requests: requests that must wait the result of another request to be sent. This is especially true for sequential requests: requests that must wait the result of another request to be sent.
We designed Garage without consensus algorithms (eg. Paxos or Raft) to minimize the number of sequential and parallel requests. We designed Garage without consensus algorithms (eg. Paxos or Raft) to minimize the number of sequential and parallel requests.
This series of benchmarks quantifies the impact of this design choice. This serie of benchmarks quantifies the impact of this design choice.
### On a simple simulated network ### On a simple simulated network
We start with a controlled environment, all the instances are running on the same (powerful enough) machine. We start with a controlled environment, all the instances are running on the same (powerful enough) machine.
To control the network latency, we simulate the network with [mknet](https://git.deuxfleurs.fr/trinity-1686a/mknet) (a tool we developed, based on `tc` and the linux network stack). To control the network latency, we simulate the network with [mknet](https://git.deuxfleurs.fr/trinity-1686a/mknet) (a tool we developped, based on `tc` and the linux network stack).
To measure S3 endpoints latency, we use our own tool [s3lat](https://git.deuxfleurs.fr/quentin/s3lat/) to observe only the intra-cluster latency and not some contention on the nodes (CPU, RAM, disk I/O, network bandwidth, etc.). To mesure S3 endpoints latency, we use our own tool [s3lat](https://git.deuxfleurs.fr/quentin/s3lat/) to observe only the intra-cluster latency and not some contention on the nodes (CPU, RAM, disk I/O, network bandwidth, etc.).
Compared to other benchmark tools, S3Lat sends only one (small) request at the same time and measures its latency. Compared to other benchmark tools, S3Lat sends only one (small) request at the same time and measures its latency.
We selected 5 standard endpoints that are often in the critical path: ListBuckets, ListObjects, GetObject, PutObject and RemoveObject. We selected 5 standard endpoints that are often in the critical path: ListBuckets, ListObjects, GetObject, PutObject and RemoveObject.
@@ -32,7 +32,7 @@ In this first benchmark, we consider 5 instances that are located in a different
Compared to garage, minio latency drastically increases on 3 endpoints: GetObject, PutObject, RemoveObject. Compared to garage, minio latency drastically increases on 3 endpoints: GetObject, PutObject, RemoveObject.
We suppose that these requests on minio make transactions over Raft, involving 4 sequential requests: 1) sending the message to the leader, 2) having the leader dispatch it to the other nodes, 3) waiting for the confirmation of followers and finally 4) committing it. With our current configuration, one Raft transaction will take around 400 ms. GetObject seems to correlate to 1 transaction while PutObject and RemoveObject seems to correlate to 2 or 3. Reviewing minio code would be required to confirm this hypothesis. We suppose that these requests on minio make transactions over Raft, involving 4 sequential requests: 1) sending the message to the leader, 2) having the leader dispatch it to the other nodes, 3) waiting for the confirmation of followers and finally 4) commiting it. With our current configuration, one Raft transaction will take around 400 ms. GetObject seems to correlate to 1 transaction while PutObject and RemoveObject seems to correlate to 2 or 3. Reviewing minio code would be required to confirm this hypothesis.
Conversely, garage uses an architecture similar to DynamoDB and never require global cluster coordination to answer a request. Conversely, garage uses an architecture similar to DynamoDB and never require global cluster coordination to answer a request.
Instead, garage can always contact the right node in charge of the requested data, and can answer in as low as one request in the case of GetObject and PutObject. We also observed that Garage latency, while often lower to minio, is more dispersed: garage is still in beta and has not received any performance optimization yet. Instead, garage can always contact the right node in charge of the requested data, and can answer in as low as one request in the case of GetObject and PutObject. We also observed that Garage latency, while often lower to minio, is more dispersed: garage is still in beta and has not received any performance optimization yet.
@@ -50,7 +50,7 @@ We plot a similar graph as before:
This new graph is very similar to the one before, neither minio or garage seems to benefit from this new topology, but they also do not suffer from it. This new graph is very similar to the one before, neither minio or garage seems to benefit from this new topology, but they also do not suffer from it.
Considering garage, this is expected: nodes in the same DC are put in the same zone, and then data are spread on different zones for data resiliency and availability. Considering garage, this is expected: nodes in the same DC are put in the same zone, and then data are spread on different zones for data resiliency and availaibility.
Then, in the default mode, requesting data requires to query at least 2 zones to be sure that we have the most up to date information. Then, in the default mode, requesting data requires to query at least 2 zones to be sure that we have the most up to date information.
These requests will involve at least one inter-DC communication. These requests will involve at least one inter-DC communication.
In other words, we prioritize data availability and synchronization over raw performances. In other words, we prioritize data availability and synchronization over raw performances.
+2 -1
View File
@@ -94,7 +94,7 @@ delete a tombstone, the following condition has to be met:
- All nodes responsible for storing this entry are aware of the existence of - 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 the tombstone, i.e. they cannot hold another version of the entry that is
superseded by the tombstone. This ensures that deleting the tombstone is superseeded by the tombstone. This ensures that deleting the tombstone is
safe and that no deleted value will come back in the system. safe and that no deleted value will come back in the system.
Garage uses atomic database operations (such as compare-and-swap and Garage uses atomic database operations (such as compare-and-swap and
@@ -141,3 +141,4 @@ 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 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 delay is a compromise that gives good security while not having this problem of
disk space explosion on rebalance. disk space explosion on rebalance.
+2 -2
View File
@@ -37,7 +37,7 @@ However, Amazon S3 source code is not open but alternatives were proposed.
We identified Minio, Pithos, Swift and Ceph. We identified Minio, Pithos, Swift and Ceph.
Minio/Ceph enforces a total order, so properties similar to a (relaxed) filesystem. Minio/Ceph enforces a total order, so properties similar to a (relaxed) filesystem.
Swift and Pithos are probably the most similar to AWS S3 with their consistent hashing ring. Swift and Pithos are probably the most similar to AWS S3 with their consistent hashing ring.
However Pithos is not maintained anymore. More precisely the company that published Pithos version 1 has developed a second version 2 but has not open sourced it. However Pithos is not maintained anymore. More precisely the company that published Pithos version 1 has developped a second version 2 but has not open sourced it.
Some tests conducted by the [ACIDES project](https://acides.org/) have shown that Openstack Swift consumes way more resources (CPU+RAM) that we can afford. Furthermore, people developing Swift have not designed their software for geo-distribution. Some tests conducted by the [ACIDES project](https://acides.org/) have shown that Openstack Swift consumes way more resources (CPU+RAM) that we can afford. Furthermore, people developing Swift have not designed their software for geo-distribution.
There were many attempts in research too. I am only thinking to [LBFS](https://pdos.csail.mit.edu/papers/lbfs:sosp01/lbfs.pdf) that was used as a basis for Seafile. But none of them have been effectively implemented yet. There were many attempts in research too. I am only thinking to [LBFS](https://pdos.csail.mit.edu/papers/lbfs:sosp01/lbfs.pdf) that was used as a basis for Seafile. But none of them have been effectively implemented yet.
@@ -63,7 +63,7 @@ Due to its industry oriented design, Ceph is also far from being *Simple* to ope
In a certain way, Ceph and MinIO are closer together than they are from Garage or OpenStack Swift. 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](https://github.com/exoscale/pithos):**
Pithos has been abandoned and should probably not used yet, in the following we explain why we did not pick their design. 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). 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. 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. They built a closed-source version 2 that does not store blobs in the database (only metadata) but did not communicate further on it.
+5 -3
View File
@@ -23,7 +23,7 @@ This logic is defined in `nix/build_index.nix`.
For each commit, we first pass the code to a formatter (rustfmt) and a linter (clippy). For each commit, we first pass the code to a formatter (rustfmt) and a linter (clippy).
Then we try to build it in debug mode and run both unit tests and our integration tests. Then we try to build it in debug mode and run both unit tests and our integration tests.
Additionally, when releasing, our integration tests are run on the release build for amd64 and i686. Additionnaly, when releasing, our integration tests are run on the release build for amd64 and i686.
## Generated Artifacts ## Generated Artifacts
@@ -32,7 +32,7 @@ We generate the following binary artifacts for now:
- **os**: linux - **os**: linux
- **format**: static binary, docker container - **format**: static binary, docker container
Additionally we also build two web pages and one JSON document: Additionnaly we also build two web pages and one JSON document:
- the documentation (this website) - the documentation (this website)
- [the release page](https://garagehq.deuxfleurs.fr/_releases.html) - [the release page](https://garagehq.deuxfleurs.fr/_releases.html)
- [the release list in JSON format](https://garagehq.deuxfleurs.fr/_releases.json) - [the release list in JSON format](https://garagehq.deuxfleurs.fr/_releases.json)
@@ -67,7 +67,7 @@ nix copy --to 's3://nix?endpoint=garage.deuxfleurs.fr&region=garage&secret-key=/
The previous command will only send the built package and not its dependencies. The previous command will only send the built package and not its dependencies.
In the case of our CI pipeline, we want to cache all intermediate build steps In the case of our CI pipeline, we want to cache all intermediate build steps
as well. This can be done using this quite involved command (here as an example as well. This can be done using this quite involved command (here as an example
for the `pkgs.amd64.release` package): for the `pkgs.amd64.relase` package):
```bash ```bash
nix copy -j8 \ nix copy -j8 \
@@ -174,3 +174,5 @@ drone sign --save Deuxfleurs/garage
``` ```
Looking at the file, you will see that most of the commands are `nix-shell` and `nix-build` commands with various parameters. Looking at the file, you will see that most of the commands are `nix-shell` and `nix-build` commands with various parameters.
+2 -2
View File
@@ -242,7 +242,7 @@ dc3 Tags Partitions Capacity Usable capacity
TOTAL 256 (256 unique) 2.0 GB 1000.0 MB (50.0%) TOTAL 256 (256 unique) 2.0 GB 1000.0 MB (50.0%)
``` ```
As we can see, the node that was moved to `dc3` (node4) is only used at 25% (approximately), As we can see, the node that was moved to `dc3` (node4) is only used at 25% (approximatively),
whereas the node that was already in `dc3` (node3) is used at 75%. whereas the node that was already in `dc3` (node3) is used at 75%.
This can be explained by the following: This can be explained by the following:
@@ -260,7 +260,7 @@ This can be explained by the following:
data can be removed to be moved to node1. data can be removed to be moved to node1.
- Garage will move data in equal proportions from all possible sources, in this - Garage will move data in equal proportions from all possible sources, in this
case it means that it will transfer 25% of the entire data set from node3 to case it means that it will tranfer 25% of the entire data set from node3 to
node1 and another 25% from node4 to node1. node1 and another 25% from node4 to node1.
This explains why node3 ends with 75% utilization (100% from before minus 25% This explains why node3 ends with 75% utilization (100% from before minus 25%
+1 -1
View File
@@ -40,7 +40,7 @@ First of all, Garage divides the set of all possible block hashes
in a fixed number of slices (currently 1024), and assigns in a fixed number of slices (currently 1024), and assigns
to each slice a primary storage location among the specified data directories. to each slice a primary storage location among the specified data directories.
The number of slices having their primary location in each data directory The number of slices having their primary location in each data directory
is proportional to the capacity specified in the config file. is proportionnal to the capacity specified in the config file.
When Garage receives a block to write, it will always write it in the primary When Garage receives a block to write, it will always write it in the primary
directory of the slice that contains its hash. directory of the slice that contains its hash.
+1 -1
View File
@@ -56,7 +56,7 @@ From a high level perspective, a major upgrade looks like this:
10. Enable API access (reverse step 1) 10. Enable API access (reverse step 1)
11. Monitor your cluster while load comes back, check that all your applications are happy with this new version 11. Monitor your cluster while load comes back, check that all your applications are happy with this new version
### Major upgrades with minimal downtime ### Major upgarades with minimal downtime
There is only one operation that has to be coordinated cluster-wide: the switch of one version of the internal RPC protocol to the next. There is only one operation that has to be coordinated cluster-wide: the switch of one version of the internal RPC protocol to the next.
This means that an upgrade with very limited downtime can simply be performed from one major version to the next by restarting all nodes This means that an upgrade with very limited downtime can simply be performed from one major version to the next by restarting all nodes
+13 -13
View File
@@ -372,7 +372,7 @@ Performance characteristics of the different DB engines are as follows:
not recommended. not recommended.
- Keys in LMDB are limited to 511 bytes. This limit translates to limits on - Keys in LMDB are limited to 511 bytes. This limit translates to limits on
object keys in S3 and sort keys in K2V that are limited to 479 bytes. object keys in S3 and sort keys in K2V that are limted to 479 bytes.
- **Sqlite:** Garage supports Sqlite as an alternative storage backend for - **Sqlite:** Garage supports Sqlite as an alternative storage backend for
metadata, which does not have the issues listed above for LMDB. Sqlite is metadata, which does not have the issues listed above for LMDB. Sqlite is
@@ -396,7 +396,7 @@ garage convert-db -a <input db engine> -i <input db path> \
``` ```
Make sure to specify the full database path as presented in the table above Make sure to specify the full database path as presented in the table above
(third column), and not just the path to the metadata directory. (third colummn), and not just the path to the metadata directory.
#### `metadata_fsync` {#metadata_fsync} #### `metadata_fsync` {#metadata_fsync}
@@ -438,7 +438,7 @@ This might reduce the risk that a data block is lost in rare
situations such as simultaneous node losing power, situations such as simultaneous node losing power,
at the cost of a moderate drop in write performance. at the cost of a moderate drop in write performance.
Similarly to `metadata_fsync`, this is likely not necessary Similarly to `metatada_fsync`, this is likely not necessary
if geographical replication is used. if geographical replication is used.
#### `metadata_auto_snapshot_interval` (since `v0.9.4`) {#metadata_auto_snapshot_interval} #### `metadata_auto_snapshot_interval` (since `v0.9.4`) {#metadata_auto_snapshot_interval}
@@ -554,7 +554,7 @@ awaits for one of the `block_max_concurrent_reads` slots to be available
slot, it reads the entire block file to RAM and frees the slot as soon as the slot, it reads the entire block file to RAM and frees the slot as soon as the
block file is finished reading. Only after the slot is released will the block file is finished reading. Only after the slot is released will the
block's data start being transferred over the network. If the request fails to block's data start being transferred over the network. If the request fails to
acquire a reading slot within 15 seconds, it fails with a timeout error. acquire a reading slot wihtin 15 seconds, it fails with a timeout error.
Timeout events can be monitored through the `block_read_semaphore_timeouts` Timeout events can be monitored through the `block_read_semaphore_timeouts`
metric in Prometheus: a non-zero number of such events indicates an I/O metric in Prometheus: a non-zero number of such events indicates an I/O
bottleneck on HDD read speed. bottleneck on HDD read speed.
@@ -617,11 +617,11 @@ storing the secret as the `GARAGE_RPC_SECRET_FILE` environment variable.
#### `rpc_bind_addr` {#rpc_bind_addr} #### `rpc_bind_addr` {#rpc_bind_addr}
The address and port on which to bind for inter-cluster communications The address and port on which to bind for inter-cluster communcations
(referred to as RPC for remote procedure calls). (reffered to as RPC for remote procedure calls).
The port specified here should be the same one that other nodes will used to contact The port specified here should be the same one that other nodes will used to contact
the node, even in the case of a NAT: the NAT should be configured to forward the external the node, even in the case of a NAT: the NAT should be configured to forward the external
port number to the same internal port number. This means that if you have several nodes running port number to the same internal port nubmer. This means that if you have several nodes running
behind a NAT, they should each use a different RPC port number. behind a NAT, they should each use a different RPC port number.
#### `rpc_bind_outgoing` (since `v0.9.2`) {#rpc_bind_outgoing} #### `rpc_bind_outgoing` (since `v0.9.2`) {#rpc_bind_outgoing}
@@ -784,14 +784,14 @@ manually.
#### `api_bind_addr` {#s3_api_bind_addr} #### `api_bind_addr` {#s3_api_bind_addr}
The IP and port on which to bind for accepting S3 API calls. The IP and port on which to bind for accepting S3 API calls.
This endpoint does not support TLS: a reverse proxy should be used to provide it. This endpoint does not suport TLS: a reverse proxy should be used to provide it.
Alternatively, since `v0.8.5`, a path can be used to create a unix socket with 0222 mode. Alternatively, since `v0.8.5`, a path can be used to create a unix socket with 0222 mode.
#### `s3_region` {#s3_region} #### `s3_region` {#s3_region}
Garage will accept S3 API calls that are targeted to the S3 region defined here. Garage will accept S3 API calls that are targetted to the S3 region defined here.
API calls targeted to other regions will fail with a AuthorizationHeaderMalformed error API calls targetted to other regions will fail with a AuthorizationHeaderMalformed error
message that redirects the client to the correct region. message that redirects the client to the correct region.
#### `root_domain` {#s3_root_domain} #### `root_domain` {#s3_root_domain}
@@ -799,7 +799,7 @@ message that redirects the client to the correct region.
The optional suffix to access bucket using vhost-style in addition to path-style request. The optional 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. 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, Configuring vhost-style S3 required a wildcard DNS entry, and possibly a wildcard TLS certificate,
but might be required by software not supporting path-style requests. 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 If `root_domain` is `s3.garage.eu`, a bucket called `my-bucket` can be interacted with
using the hostname `my-bucket.s3.garage.eu`. using the hostname `my-bucket.s3.garage.eu`.
@@ -815,7 +815,7 @@ behaviour of this module.
The IP and port on which to bind for accepting HTTP requests to buckets configured The IP and port on which to bind for accepting HTTP requests to buckets configured
for website access. for website access.
This endpoint does not support TLS: a reverse proxy should be used to provide it. This endpoint does not suport TLS: a reverse proxy should be used to provide it.
Alternatively, since `v0.8.5`, a path can be used to create a unix socket with 0222 mode. Alternatively, since `v0.8.5`, a path can be used to create a unix socket with 0222 mode.
@@ -888,7 +888,7 @@ You can use any random string for this value. We recommend generating a random t
If this is set to `true`, accessing the metrics endpoint will always require If this is set to `true`, accessing the metrics endpoint will always require
an access token. Valid tokens include the `metrics_token` if it is set, an access token. Valid tokens include the `metrics_token` if it is set,
and admin API token defined dynamically in Garage which have and admin API token defined dynamicaly in Garage which have
the `Metrics` endpoint in their scope. the `Metrics` endpoint in their scope.
#### `trace_sink` {#admin_trace_sink} #### `trace_sink` {#admin_trace_sink}
+4 -4
View File
@@ -46,7 +46,7 @@ to select the replication mode best suited to your use case (hint: in most cases
### Compression and deduplication ### Compression and deduplication
All data stored in Garage is deduplicated, and optionally compressed using All data stored in Garage is deduplicated, and optionnally compressed using
Zstd. Objects uploaded to Garage are chunked in blocks of constant sizes (see Zstd. Objects uploaded to Garage are chunked in blocks of constant sizes (see
[`block_size`](@/documentation/reference-manual/configuration.md#block_size)), [`block_size`](@/documentation/reference-manual/configuration.md#block_size)),
and the hashes of individual blocks are used to dispatch them to storage nodes and the hashes of individual blocks are used to dispatch them to storage nodes
@@ -84,13 +84,13 @@ exposing the same content under different domain names.
Garage also supports bucket aliases which are local to a single user: Garage also supports bucket aliases which are local to a single user:
this allows different users to have different buckets with the same name, thus avoiding naming collisions. this allows different users to have different buckets with the same name, thus avoiding naming collisions.
This can be helpful for instance if you want to write an application that creates per-user buckets with always the same name. This can be helpfull for instance if you want to write an application that creates per-user buckets with always the same name.
This feature is totally invisible to S3 clients and does not break compatibility with AWS. This feature is totally invisible to S3 clients and does not break compatibility with AWS.
### Cluster administration API ### Cluster administration API
Garage provides a fully-fledged REST API to administer your cluster programmatically. Garage provides a fully-fledged REST API to administer your cluster programatically.
Functionality included in the admin API include: setting up and monitoring Functionality included in the admin API include: setting up and monitoring
cluster nodes, managing access credentials, and managing storage buckets and bucket aliases. cluster nodes, managing access credentials, and managing storage buckets and bucket aliases.
A full reference of the administration API is available [here](@/documentation/reference-manual/admin-api.md). A full reference of the administration API is available [here](@/documentation/reference-manual/admin-api.md).
@@ -100,7 +100,7 @@ A full reference of the administration API is available [here](@/documentation/r
Garage makes some internal metrics available in the Prometheus data format, Garage makes some internal metrics available in the Prometheus data format,
which allows you to build interactive dashboards to visualize the load and internal state of your storage cluster. which allows you to build interactive dashboards to visualize the load and internal state of your storage cluster.
For developers and performance-savvy administrators, For developpers and performance-savvy administrators,
Garage also supports exporting traces of what it does internally in OpenTelemetry format. Garage also supports exporting traces of what it does internally in OpenTelemetry format.
This allows to monitor the time spent at various steps of the processing of requests, This allows to monitor the time spent at various steps of the processing of requests,
in order to detect potential performance bottlenecks. in order to detect potential performance bottlenecks.
+2 -1
View File
@@ -19,7 +19,7 @@ The specification of the K2V API can be found
[here](https://git.deuxfleurs.fr/Deuxfleurs/garage/src/commit/f8be15c37db857e177d543de7be863692628d567/doc/drafts/k2v-spec.md). [here](https://git.deuxfleurs.fr/Deuxfleurs/garage/src/commit/f8be15c37db857e177d543de7be863692628d567/doc/drafts/k2v-spec.md).
This document also includes a high-level overview of K2V's design. This document also includes a high-level overview of K2V's design.
The K2V API uses AWSv4 signatures for authentication, same as the S3 API. The K2V API uses AWSv4 signatures for authentification, same as the S3 API.
The AWS region used for signature calculation is always the same as the one The AWS region used for signature calculation is always the same as the one
defined for the S3 API in the config file. defined for the S3 API in the config file.
@@ -55,3 +55,4 @@ cargo build --features cli --bin k2v-cli
The CLI utility is self-documented, run `k2v-cli --help` to learn how to use The CLI utility is self-documented, run `k2v-cli --help` to learn how to use
it. There is also a short README.md in the `src/k2v-client` folder with some it. There is also a short README.md in the `src/k2v-client` folder with some
instructions. instructions.
@@ -45,7 +45,7 @@ we suppose that OpenIO supports presigned URLs.
All endpoints that are missing on Garage will return a 501 Not Implemented. All endpoints that are missing on Garage will return a 501 Not Implemented.
Some `x-amz-` headers are not implemented. Some `x-amz-` headers are not implemented.
### Core endpoints ### Core endoints
| Endpoint | Garage | [Openstack Swift](https://docs.openstack.org/swift/latest/s3_compat.html) | [Ceph Object Gateway](https://docs.ceph.com/en/latest/radosgw/s3/) | [Riak CS](https://docs.riak.com/riak/cs/2.1.1/references/apis/storage/s3/index.html) | [OpenIO](https://docs.openio.io/latest/source/arch-design/s3_compliancy.html) | | Endpoint | Garage | [Openstack Swift](https://docs.openstack.org/swift/latest/s3_compat.html) | [Ceph Object Gateway](https://docs.ceph.com/en/latest/radosgw/s3/) | [Riak CS](https://docs.riak.com/riak/cs/2.1.1/references/apis/storage/s3/index.html) | [OpenIO](https://docs.openio.io/latest/source/arch-design/s3_compliancy.html) |
|------------------------------|----------------------------------|-----------------|---------------|---------|-----| |------------------------------|----------------------------------|-----------------|---------------|---------|-----|
@@ -135,12 +135,12 @@ If you need this feature, please [share your use case in our dedicated issue](ht
**PutBucketLifecycleConfiguration:** The only actions supported are **PutBucketLifecycleConfiguration:** The only actions supported are
`AbortIncompleteMultipartUpload` and `Expiration` (without the `AbortIncompleteMultipartUpload` and `Expiration` (without the
`ExpiredObjectDeleteMarker` field). All other operations are dependent on `ExpiredObjectDeleteMarker` field). All other operations are dependent on
either bucket versioning or storage classes which Garage currently does not either bucket versionning or storage classes which Garage currently does not
implement. The deprecated `Prefix` member directly in the the `Rule` implement. The deprecated `Prefix` member directly in the the `Rule`
structure/XML tag is not supported, specified prefixes must be inside the structure/XML tag is not supported, specified prefixes must be inside the
`Filter` structure/XML tag. `Filter` structure/XML tag.
**GetBucketVersioning:** Stub implementation which always returns "versioning not enabled", since Garage does not yet support bucket versioning. **GetBucketVersioning:** Stub implementation which always returns "versionning not enabled", since Garage does not yet support bucket versionning.
### Replication endpoints ### Replication endpoints
@@ -155,7 +155,7 @@ Please open an issue if you have a use case for replication.
*Note: Ceph documentation briefly says that Ceph supports *Note: Ceph documentation briefly says that Ceph supports
[replication through the S3 API](https://docs.ceph.com/en/latest/radosgw/multisite-sync-policy/#s3-replication-api) [replication through the S3 API](https://docs.ceph.com/en/latest/radosgw/multisite-sync-policy/#s3-replication-api)
but with some limitations. but with some limitations.
Additionally, replication endpoints are not documented in the S3 compatibility page so I don't know what kind of support we can expect.* Additionaly, replication endpoints are not documented in the S3 compatibility page so I don't know what kind of support we can expect.*
### Locking objects ### Locking objects
@@ -197,7 +197,7 @@ Please open an issue if you have a use case.
### Vendor specific endpoints ### Vendor specific endpoints
<details><summary>Display Amazon specific endpoints</summary> <details><summary>Display Amazon specifc endpoints</summary>
| Endpoint | Garage | [Openstack Swift](https://docs.openstack.org/swift/latest/s3_compat.html) | [Ceph Object Gateway](https://docs.ceph.com/en/latest/radosgw/s3/) | [Riak CS](https://docs.riak.com/riak/cs/2.1.1/references/apis/storage/s3/index.html) | [OpenIO](https://docs.openio.io/latest/source/arch-design/s3_compliancy.html) | | Endpoint | Garage | [Openstack Swift](https://docs.openstack.org/swift/latest/s3_compat.html) | [Ceph Object Gateway](https://docs.ceph.com/en/latest/radosgw/s3/) | [Riak CS](https://docs.riak.com/riak/cs/2.1.1/references/apis/storage/s3/index.html) | [OpenIO](https://docs.openio.io/latest/source/arch-design/s3_compliancy.html) |
@@ -234,3 +234,4 @@ Please open an issue if you have a use case.
| [SelectObjectContent](https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html) | ❌ Missing | ❌| ❌| ❌| ❌| | [SelectObjectContent](https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html) | ❌ Missing | ❌| ❌| ❌| ❌|
</details> </details>
@@ -3,7 +3,7 @@ title = "S3 compatibility target"
weight = 5 weight = 5
+++ +++
If there is a specific S3 functionality you have a need for, feel free to open 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 a PR to put the corresponding endpoints higher in the list. Please explain
your motivations for doing so in the PR message. your motivations for doing so in the PR message.
+2 -2
View File
@@ -68,7 +68,7 @@ Workflow for DELETE:
1. Check write permission (LDAP) 1. Check write permission (LDAP)
2. Get current version (or versions) in object table 2. Get current version (or versions) in object table
3. Do the deletion of those versions NOT IN A BACKGROUND JOB THIS TIME 3. Do the deletion of those versions NOT IN A BACKGROUND JOB THIS TIME
4. Return success to the user if we were able to delete blocks from the blocks table and entries from the object table 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: To delete a version:
@@ -92,7 +92,7 @@ Known issue: if someone is reading from a version that we want to delete and the
- file path = /meta/(first 3 hex digits of hash)/(rest of hash) - file path = /meta/(first 3 hex digits of hash)/(rest of hash)
- map block hash -> set of version UUIDs where it is referenced - map block hash -> set of version UUIDs where it is referenced
Useful metadata: 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 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, useful in the rebalancing algorithm - list of other nodes that we know have acknowledged a write of this block, useful in the rebalancing algorithm
+3 -3
View File
@@ -49,12 +49,12 @@ The ring construction that selects `n_token` random positions for each nodes giv
is not well-balanced: the space between the tokens varies a lot, and some partitions are thus bigger than others. is not well-balanced: the space between the tokens varies a lot, and some partitions are thus bigger than others.
This problem was demonstrated in the original Dynamo DB paper. This problem was demonstrated in the original Dynamo DB paper.
To solve this, we want to apply a better second method for partitioning our dataset: To solve this, we want to apply a better second method for partitionning our dataset:
1. fix an initially large number of partitions (say 1024) with evenly-spaced delimiters, 1. fix an initially large number of partitions (say 1024) with evenly-spaced delimiters,
2. attribute each partition randomly to a node, with a probability 2. attribute each partition randomly to a node, with a probability
proportional to its capacity (which `n_tokens` represented in the first proportionnal to its capacity (which `n_tokens` represented in the first
method) method)
For now we continue using the multi-DC ring walking described above. For now we continue using the multi-DC ring walking described above.
@@ -66,7 +66,7 @@ I have studied two ways to do the attribution of partitions to nodes, in a way t
MagLev provided significantly better balancing, as it guarantees that the exact MagLev provided significantly better balancing, as it guarantees that the exact
same number of partitions is attributed to all nodes that have the same same number of partitions is attributed to all nodes that have the same
capacity (and that this number is proportional to the node's capacity, except capacity (and that this number is proportionnal to the node's capacity, except
for large values), however in both cases: for large values), however in both cases:
- the distribution is still bad, because we use the naive multi-DC ring walking - the distribution is still bad, because we use the naive multi-DC ring walking
+1 -1
View File
@@ -19,7 +19,7 @@ The migration steps are as follows:
2. Disable API and web access. Garage does not support disabling 2. Disable API and web access. Garage does not support disabling
these endpoints but you can change the port number or stop your reverse these endpoints but you can change the port number or stop your reverse
proxy for instance. proxy for instance.
3. Check once again that your cluster is healthy. Run again `garage repair --all-nodes --yes tables` which is quick. 3. Check once again that your cluster is healty. Run again `garage repair --all-nodes --yes tables` which is quick.
Also check your queues are empty, run `garage stats` to query them. Also check your queues are empty, run `garage stats` to query them.
4. Turn off Garage v0.6 4. Turn off Garage v0.6
5. Backup the metadata folder of all your nodes: `cd /var/lib/garage ; tar -acf meta-v0.6.tar.zst meta/` 5. Backup the metadata folder of all your nodes: `cd /var/lib/garage ; tar -acf meta-v0.6.tar.zst meta/`
@@ -28,11 +28,11 @@ We should try to test in least invasive ways, i.e. minimize the impact of the te
- Not making `garage` a shared library (launch using `execve`, it's perfectly fine) - Not making `garage` a shared library (launch using `execve`, it's perfectly fine)
Instead, we should focus on building a clean outer interface for the `garage` binary, Instead, we should focus on building a clean outer interface for the `garage` binary,
for example loading configuration using environment variables instead of the configuration file if that's helpful for writing the tests. for example loading configuration using environnement variables instead of the configuration file if that's helpfull for writing the tests.
There are two reasons for this: There are two reasons for this:
- Keep the source code clean and focused - Keep the soure code clean and focused
- Test something that is as close as possible as the true garage that will actually be running - Test something that is as close as possible as the true garage that will actually be running
Reminder: rules of simplicity, concerning changes to Garage's source code. Reminder: rules of simplicity, concerning changes to Garage's source code.
@@ -71,3 +71,5 @@ Interesting blog posts on the blog of the Sled database:
Misc: Misc:
- [mutagen](https://github.com/llogiq/mutagen) - mutation testing is a way to assert our test quality by mutating the code and see if the mutation makes the tests fail - [mutagen](https://github.com/llogiq/mutagen) - mutation testing is a way to assert our test quality by mutating the code and see if the mutation makes the tests fail
- [fuzzing](https://rust-fuzz.github.io/book/) - cargo supports fuzzing, it could be a way to test our software reliability in presence of garbage data. - [fuzzing](https://rust-fuzz.github.io/book/) - cargo supports fuzzing, it could be a way to test our software reliability in presence of garbage data.
+5 -5
View File
@@ -176,7 +176,7 @@ Returns the cluster's current health in JSON format, with the following variable
- degraded: Garage node is not connected to all storage nodes, but a quorum of write nodes is available for all partitions - degraded: Garage node is not connected to all storage nodes, but a quorum of write nodes is available for all partitions
- unavailable: a quorum of write nodes is not available for some partitions - unavailable: a quorum of write nodes is not available for some partitions
- `knownNodes`: the number of nodes this Garage node has had a TCP connection to since the daemon started - `knownNodes`: the number of nodes this Garage node has had a TCP connection to since the daemon started
- `connectedNodes`: the number of nodes this Garage node currently has an open connection to - `connectedNodes`: the nubmer of nodes this Garage node currently has an open connection to
- `storageNodes`: the number of storage nodes currently registered in the cluster layout - `storageNodes`: the number of storage nodes currently registered in the cluster layout
- `storageNodesOk`: the number of storage nodes to which a connection is currently open - `storageNodesOk`: the number of storage nodes to which a connection is currently open
- `partitions`: the total number of partitions of the data (currently always 256) - `partitions`: the total number of partitions of the data (currently always 256)
@@ -379,7 +379,7 @@ Example response:
] ]
``` ```
#### GetKeyInfo `GET /v2/GetKeyInfo?id=<access key id>` #### GetKeyInfo `GET /v2/GetKeyInfo?id=<acces key id>`
#### GetKeyInfo `GET /v2/GetKeyInfo?search=<pattern>` #### GetKeyInfo `GET /v2/GetKeyInfo?search=<pattern>`
Returns information about the requested API access key. Returns information about the requested API access key.
@@ -388,7 +388,7 @@ If `id` is set, the key is looked up using its exact identifier (faster).
If `search` is set, the key is looked up using its name or prefix If `search` is set, the key is looked up using its name or prefix
of identifier (slower, all keys are enumerated to do this). of identifier (slower, all keys are enumerated to do this).
Optionally, the query parameter `showSecretKey=true` can be set to reveal the Optionnally, the query parameter `showSecretKey=true` can be set to reveal the
associated secret access key. associated secret access key.
Example response: Example response:
@@ -487,7 +487,7 @@ Request body format:
This returns the key info in the same format as the result of GetKeyInfo. This returns the key info in the same format as the result of GetKeyInfo.
#### UpdateKey `POST /v2/UpdateKey?id=<access key id>` #### UpdateKey `POST /v2/UpdateKey?id=<acces key id>`
Updates information about the specified API access key. Updates information about the specified API access key.
@@ -509,7 +509,7 @@ The possible flags in `allow` and `deny` are: `createBucket`.
This returns the key info in the same format as the result of GetKeyInfo. This returns the key info in the same format as the result of GetKeyInfo.
#### DeleteKey `POST /v2/DeleteKey?id=<access key id>` #### DeleteKey `POST /v2/DeleteKey?id=<acces key id>`
Deletes an API access key. Deletes an API access key.
+6 -6
View File
@@ -35,7 +35,7 @@ Triples in K2V are constituted of three fields:
partition key in which the client wants to read/delete lists of items partition key in which the client wants to read/delete lists of items
- a sort key (`sk`), an utf8 string that defines the index of the triplet inside its - a sort key (`sk`), an utf8 string that defines the index of the triplet inside its
partition; triplets are uniquely identified by their partition key + sort key partition; triplets are uniquely idendified by their partition key + sort key
- a value (`v`), an opaque binary blob associated to the partition key + sort key; - a value (`v`), an opaque binary blob associated to the partition key + sort key;
they are transmitted as binary when possible but in most case in the JSON API they are transmitted as binary when possible but in most case in the JSON API
@@ -74,7 +74,7 @@ are obsoleted by the new write.
**Basic insertion.** To insert a new value `v4` with context `[(node1, t2), (node2, t3)]`, in a **Basic insertion.** To insert a new value `v4` with context `[(node1, t2), (node2, t3)]`, in a
simple case where there was no insertion in-between reading the value simple case where there was no insertion in-between reading the value
mentioned above and writing `v4`, and supposing that node2 receives the mentionned above and writing `v4`, and supposing that node2 receives the
InsertItem query: InsertItem query:
- `node2` generates a timestamp `t4` such that `t4 > t3`. - `node2` generates a timestamp `t4` such that `t4 > t3`.
@@ -332,7 +332,7 @@ Inserts a single item. This request does not use JSON, the body is sent directly
To supersede previous values, the HTTP header `X-Garage-Causality-Token` should To supersede previous values, the HTTP header `X-Garage-Causality-Token` should
be set to the causality token returned by a previous read on this key. This be set to the causality token returned by a previous read on this key. This
header can be omitted for the first writes to the key. header can be ommitted for the first writes to the key.
Example query: Example query:
@@ -397,7 +397,7 @@ smallest partition key that exists. It returns partition keys in increasing
order, or decreasing order if `reverse` is set to `true`, order, or decreasing order if `reverse` is set to `true`,
and stops when either of the following conditions is met: and stops when either of the following conditions is met:
1. if `end` is specified, the partition key `end` is reached or surpassed (if it 1. if `end` is specfied, the partition key `end` is reached or surpassed (if it
is reached exactly, it is not included in the result) is reached exactly, it is not included in the result)
2. if `limit` is specified, `limit` partition keys have been listed 2. if `limit` is specified, `limit` partition keys have been listed
@@ -491,7 +491,7 @@ the triplet is inserted for the first time, the causality token should be set to
The value is expected to be a base64-encoded binary blob. The value `null` can The value is expected to be a base64-encoded binary blob. The value `null` can
also be used to delete the triplet while preserving causality information: this also be used to delete the triplet while preserving causality information: this
allows to know if a delete has happened concurrently with an insert, in which allows to know if a delete has happenned concurrently with an insert, in which
case both are preserved and returned on reads (see below). case both are preserved and returned on reads (see below).
Partition keys and sort keys are utf8 strings which are stored sorted by Partition keys and sort keys are utf8 strings which are stored sorted by
@@ -540,7 +540,7 @@ JSON struct with the following fields:
For each of the searches, triplets are listed and returned separately. The For each of the searches, triplets are listed and returned separately. The
semantics of `prefix`, `start`, `end`, `limit` and `reverse` are the same as for ReadIndex. The semantics of `prefix`, `start`, `end`, `limit` and `reverse` are the same as for ReadIndex. The
additional parameter `singleItem` allows to get a single item, whose sort key additionnal parameter `singleItem` allows to get a single item, whose sort key
is the one given in `start`. Parameters `conflictsOnly` and `tombstones` is the one given in `start`. Parameters `conflictsOnly` and `tombstones`
control additional filters on the items that are returned. control additional filters on the items that are returned.
+1 -1
View File
@@ -59,7 +59,7 @@ To link the effective storage capacity of the cluster to partition assignment, w
\end{equation} \end{equation}
This assumption is justified by the dispersion of the hashing function, when the number of partitions is small relative to the number of stored blocks. This assumption is justified by the dispersion of the hashing function, when the number of partitions is small relative to the number of stored blocks.
Every node $n$ will store some number $p_n$ of partitions (it is the number of partitions $p$ such that $n$ appears in the $\alpha_p$). Hence the partitions stored by $n$ (and hence all partitions by our assumption) have there size bounded by $c_n/p_n$. This remark leads us to define the optimal size that we will want to maximize: Every node $n$ wille store some number $p_n$ of partitions (it is the number of partitions $p$ such that $n$ appears in the $\alpha_p$). Hence the partitions stored by $n$ (and hence all partitions by our assumption) have there size bounded by $c_n/p_n$. This remark leads us to define the optimal size that we will want to maximize:
\begin{equation} \begin{equation}
\label{eq:optimal} \label{eq:optimal}
+10 -10
View File
@@ -38,7 +38,7 @@ We would like to compute an assignment of nodes to partitions. We will impose so
\end{equation} \end{equation}
This assumption is justified by the dispersion of the hashing function, when the number of partitions is small relative to the number of stored large objects. This assumption is justified by the dispersion of the hashing function, when the number of partitions is small relative to the number of stored large objects.
Every node $n$ will store some number $k_n$ of partitions. Hence the partitions stored by $n$ (and hence all partitions by our assumption) have there size bounded by $c_n/k_n$. This remark leads us to define the optimal size that we will want to maximize: Every node $n$ wille store some number $k_n$ of partitions. Hence the partitions stored by $n$ (and hence all partitions by our assumption) have there size bounded by $c_n/k_n$. This remark leads us to define the optimal size that we will want to maximize:
\begin{equation} \begin{equation}
\label{eq:optimal} \label{eq:optimal}
@@ -62,7 +62,7 @@ For now, in the following, we ask the following redundancy constraint:
\textbf{Mode 3:} every partition needs to be assignated to three nodes. We try to spread the three nodes over different zones as much as possible. \textbf{Mode 3:} every partition needs to be assignated to three nodes. We try to spread the three nodes over different zones as much as possible.
\textbf{Warning:} This is a working document written incrementally. The last version of the algorithm is the \textbf{parametric assignment} described in the next section. \textbf{Warning:} This is a working document written incrementaly. The last version of the algorithm is the \textbf{parametric assignment} described in the next section.
\section{Computation of a parametric assignment} \section{Computation of a parametric assignment}
@@ -318,7 +318,7 @@ $$
$$ $$
which is the universal upper bound on $s^*$. Hence any optimal utilization $(n_v)$ can be modified to another optimal utilization such that $n_v\ge \hat{n}_v$ which is the universal upper bound on $s^*$. Hence any optimal utilization $(n_v)$ can be modified to another optimal utilization such that $n_v\ge \hat{n}_v$
Because $z_0$ cannot store more than $N$ partition occurrences, in any assignment, at least $2N$ partitions must be assignated to the zones $Z\setminus\{z_0\}$. Let $C_0 = C-c_{z_0}$. Suppose that there exists a zone $z_1\neq z_0$ such that $c_{z_1}/C_0 \ge 1/2$. Then, with the same argument as for $z_0$, we can define Because $z_0$ cannot store more than $N$ partition occurences, in any assignment, at least $2N$ partitions must be assignated to the zones $Z\setminus\{z_0\}$. Let $C_0 = C-c_{z_0}$. Suppose that there exists a zone $z_1\neq z_0$ such that $c_{z_1}/C_0 \ge 1/2$. Then, with the same argument as for $z_0$, we can define
$$\hat{n}_v = \left\lfloor\frac{c_v}{c_{z_1}}N\right\rfloor$$ $$\hat{n}_v = \left\lfloor\frac{c_v}{c_{z_1}}N\right\rfloor$$
for every $v\in z_1$. for every $v\in z_1$.
@@ -351,7 +351,7 @@ Define $3N$ tokens $t_1,\ldots, t_{3N}\in V$ as follows:
Then for $1\le i \le N$, define the triplet $T_i$ to be Then for $1\le i \le N$, define the triplet $T_i$ to be
$(t_i, t_{i+N}, t_{i+2N})$. Since the same nodes of a zone appear contiguously, the three nodes of a triplet must belong to three distinct zones. $(t_i, t_{i+N}, t_{i+2N})$. Since the same nodes of a zone appear contiguously, the three nodes of a triplet must belong to three distinct zones.
However simple, this solution to go from an utilization to an assignment has the drawback of not spreading the triplets: a node will tend to be associated to the same two other nodes for many partitions. Hence, during data transfer, it will tend to use only two link, instead of spreading the bandwidth use over many other links to other nodes. To achieve this goal, we will reframe the search of an assignment as a flow problem. and in the flow algorithm, we will introduce randomness in the order of exploration. This will be sufficient to obtain a good dispersion of the triplets. However simple, this solution to go from an utilization to an assignment has the drawback of not spreading the triplets: a node will tend to be associated to the same two other nodes for many partitions. Hence, during data transfer, it will tend to use only two link, instead of spreading the bandwith use over many other links to other nodes. To achieve this goal, we will reframe the search of an assignment as a flow problem. and in the flow algorithm, we will introduce randomness in the order of exploration. This will be sufficient to obtain a good dispersion of the triplets.
\begin{figure} \begin{figure}
\centering \centering
@@ -436,7 +436,7 @@ T_3=(b,c,d').
$$ $$
One can check that in this case, it is impossible to minimize both the number of zone and node changes. One can check that in this case, it is impossible to minimize both the number of zone and node changes.
Because of the redundancy constraint, we cannot use a greedy algorithm to just replace nodes in the triplets to try to get the new utilization rate: this could lead to blocking situation where there is still a hole to fill in a triplet but no available node satisfies the zone separation constraint. To circumvent this issue, we propose an algorithm based on finding cycles in a graph encoding of the assignment. As in section \ref{sec:opt_assign}, we can explore the neighbours in a random order in the graph algorithms, to spread the triplets distribution. Because of the redundancy constraint, we cannot use a greedy algorithm to just replace nodes in the triplets to try to get the new utilization rate: this could lead to blocking situation where there is still a hole to fill in a triplet but no available node satisfies the zone separation constraint. To circumvent this issue, we propose an algorithm based on finding cycles in a graph encoding of the assignment. As in section \ref{sec:opt_assign}, we can explore the neigbours in a random order in the graph algorithms, to spread the triplets distribution.
\subsubsection{Minimizing the zone discrepancy} \subsubsection{Minimizing the zone discrepancy}
@@ -550,8 +550,8 @@ We give some considerations of worst case complexity for these algorithms. In th
Algorithm \ref{alg:util} can be implemented with complexity $O(\#V^2)$. The complexity of the function call at line \ref{lin:subutil} is $O(\#V)$. The difference between the sum of the subutilizations and $3N$ is at most the sum of the rounding errors when computing the $\hat{n}_v$. Hence it is bounded by $\#V$ and the loop at line \ref{lin:loopsub} is iterated at most $\#V$ times. Finding the minimizing $v$ at line \ref{lin:findmin} takes $O(\#V)$ operations (naively, we could also use a heap). Algorithm \ref{alg:util} can be implemented with complexity $O(\#V^2)$. The complexity of the function call at line \ref{lin:subutil} is $O(\#V)$. The difference between the sum of the subutilizations and $3N$ is at most the sum of the rounding errors when computing the $\hat{n}_v$. Hence it is bounded by $\#V$ and the loop at line \ref{lin:loopsub} is iterated at most $\#V$ times. Finding the minimizing $v$ at line \ref{lin:findmin} takes $O(\#V)$ operations (naively, we could also use a heap).
Algorithm \ref{alg:opt} can be implemented with complexity $O(N^3\times \#Z)$. The flow graph has $O(N+\#Z)$ vertices and $O(N\times \#Z)$ edges. Dinic's algorithm has complexity $O(\#\mathrm{Vertices}^2\#\mathrm{Edges})$ hence in our case it is $O(N^3\times \#Z)$. Algorithm \ref{alg:opt} can be implemented with complexity $O(N^3\times \#Z)$. The flow graph has $O(N+\#Z)$ vertices and $O(N\times \#Z)$ edges. Dinic's algorithm has complexity $O(\#\mathrm{Vertices}^2\#\mathrm{Edges})$ hence in our case it is $O(N^3\times \#Z)$.
Algorithm \ref{alg:mini} can be implemented with complexity $O(N^3\# Z)$ under \eqref{hyp:A} and $O(N^3 \#Z \#V)$ under \eqref{hyp:B}. Algorithm \ref{alg:mini} can be implented with complexity $O(N^3\# Z)$ under \eqref{hyp:A} and $O(N^3 \#Z \#V)$ under \eqref{hyp:B}.
The graph $G_T$ has $O(N)$ vertices and $O(N\times \#Z)$ edges under assumption \eqref{hyp:A} and respectively $O(N\times \#Z)$ vertices and $O(N\times \#V)$ edges under assumption \eqref{hyp:B}. The loop at line \ref{lin:repeat} is iterated at most $N$ times since the distance between $T$ and $T'$ decreases at every iteration. Bellman-Ford algorithm has complexity $O(\#\mathrm{Vertices}\#\mathrm{Edges})$, which in our case amounts to $O(N^2\# Z)$ under \eqref{hyp:A} and $O(N^2 \#Z \#V)$ under \eqref{hyp:B}. The graph $G_T$ has $O(N)$ vertices and $O(N\times \#Z)$ edges under assumption \eqref{hyp:A} and respectively $O(N\times \#Z)$ vertices and $O(N\times \#V)$ edges under assumption \eqref{hyp:B}. The loop at line \ref{lin:repeat} is iterated at most $N$ times since the distance between $T$ and $T'$ decreases at every iteration. Bellman-Ford algorithm has complexity $O(\#\mathrm{Vertices}\#\mathrm{Edges})$, which in our case amounts to $O(N^2\# Z)$ under \eqref{hyp:A} and $O(N^2 \#Z \#V)$ under \eqref{hyp:B}.
\begin{algorithm} \begin{algorithm}
@@ -637,7 +637,7 @@ We try to maximize $s^*$ defined in \eqref{eq:optimal}. So we can compute the op
\subsection{Computation of a candidate assignment} \subsection{Computation of a candidate assignment}
To compute a candidate assignment (that does not optimize zone spreading nor distance to a previous assignment yet), we can use the following flow problem. To compute a candidate assignment (that does not optimize zone spreading nor distance to a previous assignment yet), we can use the folowing flow problem.
Define the oriented weighted graph $(X,E)$. The set of vertices $X$ contains the source $\mathbf{s}$, the sink $\mathbf{t}$, vertices Define the oriented weighted graph $(X,E)$. The set of vertices $X$ contains the source $\mathbf{s}$, the sink $\mathbf{t}$, vertices
$\mathbf{x}_p, \mathbf{u}^+_p, \mathbf{u}^-_p$ for every partition $p$, vertices $\mathbf{y}_{p,z}$ for every partition $p$ and zone $z$, and vertices $\mathbf{z}_v$ for every node $v$. $\mathbf{x}_p, \mathbf{u}^+_p, \mathbf{u}^-_p$ for every partition $p$, vertices $\mathbf{y}_{p,z}$ for every partition $p$ and zone $z$, and vertices $\mathbf{z}_v$ for every node $v$.
@@ -680,14 +680,14 @@ Given the flow $f$, let $G_f=(X',E_f)$ be the multi-graph where $X' = X\setminus
\end{itemize} \end{itemize}
To summarize, arcs are oriented left to right if they correspond to a presence of flow in $f$, and right to left if they correspond to an absence of flow. They are positively weighted if we want them to stay at their current state, and negatively if we want them to switch. Let us compute the weight of such graph. To summarize, arcs are oriented left to right if they correspond to a presence of flow in $f$, and right to left if they correspond to an absence of flow. They are positively weighted if we want them to stay at their current state, and negatively if we want them to switch. Let us compute the weight of such graph.
\begin{multiline*} \begin{multline*}
w(G_f) = \sum_{e\in E_f} w(e_f) \\ w(G_f) = \sum_{e\in E_f} w(e_f) \\
= =
(\alpha - \beta -\gamma) N_1 + (\alpha +\beta - \gamma) N_2 + (\alpha+\beta+\gamma) N_3 (\alpha - \beta -\gamma) N_1 + (\alpha +\beta - \gamma) N_2 + (\alpha+\beta+\gamma) N_3
\\ + \\ +
\#V\times N - 4 \sum_p 3-\#(T_p\cap T'_p) \\ \#V\times N - 4 \sum_p 3-\#(T_p\cap T'_p) \\
=(\#V-12+\alpha-\beta-\gamma)\times N + 4Q_V + 2\beta N_2 + 2(\beta+\gamma) N_3 \\ =(\#V-12+\alpha-\beta-\gamma)\times N + 4Q_V + 2\beta N_2 + 2(\beta+\gamma) N_3 \\
\end{multiline*} \end{multline*}
As for the mode 3-strict, one can check that the difference of two such graphs corresponding to the same $(n_v)$ is always eulerian. Hence we can navigate in this class with the same greedy algorithm that discovers positive cycles and flips them. As for the mode 3-strict, one can check that the difference of two such graphs corresponding to the same $(n_v)$ is always eulerian. Hence we can navigate in this class with the same greedy algorithm that discovers positive cycles and flips them.
+1 -1
View File
@@ -67,7 +67,7 @@
clippy = lints.garage-cargo-clippy; clippy = lints.garage-cargo-clippy;
}; };
# ---- development shell, for making native builds only ---- # ---- developpment shell, for making native builds only ----
devShells = devShells =
let let
targets = compile { targets = compile {
+2 -2
View File
@@ -29,7 +29,7 @@ S3-compatible object store for small self-hosted geo-distributed deployments
| garage.dbEngine | string | `"lmdb"` | Can be changed for better performance on certain systems https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#db_engine | | garage.dbEngine | string | `"lmdb"` | Can be changed for better performance on certain systems https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#db_engine |
| garage.existingConfigMap | string | `""` | if not empty string, allow using an existing ConfigMap for the garage.toml, if set, ignores garage.toml | | garage.existingConfigMap | string | `""` | if not empty string, allow using an existing ConfigMap for the garage.toml, if set, ignores garage.toml |
| garage.garageTomlString | string | `""` | String Template for the garage configuration if set, ignores above values. Values can be templated, see https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/ | | garage.garageTomlString | string | `""` | String Template for the garage configuration if set, ignores above values. Values can be templated, see https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/ |
| garage.kubernetesSkipCrd | bool | `false` | Set to true if you want to use k8s discovery but install the CRDs manually outside of the helm chart, for example if you operate at namespace level without cluster resources | | garage.kubernetesSkipCrd | bool | `false` | Set to true if you want to use k8s discovery but install the CRDs manually outside of the helm chart, for example if you operate at namespace level without cluster ressources |
| garage.replicationFactor | string | `"3"` | Default to 3 replicas, see the replication_factor section at https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#replication_factor | | garage.replicationFactor | string | `"3"` | Default to 3 replicas, see the replication_factor section at https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#replication_factor |
| garage.consistencyMode | string | `"consistent"` | Default to read-after-write consistency, see the consistency_mode section at https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#consistency_mode | | garage.consistencyMode | string | `"consistent"` | Default to read-after-write consistency, see the consistency_mode section at https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#consistency_mode |
| garage.metadataAutoSnapshotInterval | string | `""` | If this value is set, Garage will automatically take a snapshot of the metadata DB file at a regular interval and save it in the metadata directory. https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#metadata_auto_snapshot_interval | | garage.metadataAutoSnapshotInterval | string | `""` | If this value is set, Garage will automatically take a snapshot of the metadata DB file at a regular interval and save it in the metadata directory. https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#metadata_auto_snapshot_interval |
@@ -76,7 +76,7 @@ S3-compatible object store for small self-hosted geo-distributed deployments
| persistence.enabled | bool | `true` | | | persistence.enabled | bool | `true` | |
| persistence.meta.hostPath | string | `"/var/lib/garage/meta"` | | | persistence.meta.hostPath | string | `"/var/lib/garage/meta"` | |
| persistence.meta.size | string | `"100Mi"` | | | persistence.meta.size | string | `"100Mi"` | |
| podAnnotations | object | `{}` | additional pod annotations | | podAnnotations | object | `{}` | additonal pod annotations |
| podSecurityContext.fsGroup | int | `1000` | | | podSecurityContext.fsGroup | int | `1000` | |
| podSecurityContext.runAsGroup | int | `1000` | | | podSecurityContext.runAsGroup | int | `1000` | |
| podSecurityContext.runAsNonRoot | bool | `true` | | | podSecurityContext.runAsNonRoot | bool | `true` | |
+1 -1
View File
@@ -13,7 +13,7 @@ data:
db_engine = "{{ .Values.garage.dbEngine }}" db_engine = "{{ .Values.garage.dbEngine }}"
block_size = "{{ .Values.garage.blockSize }}" block_size = {{ .Values.garage.blockSize }}
replication_factor = {{ .Values.garage.replicationFactor }} replication_factor = {{ .Values.garage.replicationFactor }}
consistency_mode = "{{ .Values.garage.consistencyMode }}" consistency_mode = "{{ .Values.garage.consistencyMode }}"
+3 -3
View File
@@ -44,7 +44,7 @@ garage:
# -- This is not required if you use the integrated kubernetes discovery # -- This is not required if you use the integrated kubernetes discovery
bootstrapPeers: [] bootstrapPeers: []
# -- Set to true if you want to use k8s discovery but install the CRDs manually outside # -- Set to true if you want to use k8s discovery but install the CRDs manually outside
# of the helm chart, for example if you operate at namespace level without cluster resources # of the helm chart, for example if you operate at namespace level without cluster ressources
kubernetesSkipCrd: false kubernetesSkipCrd: false
s3: s3:
api: api:
@@ -120,7 +120,7 @@ serviceAccount:
# If not set and create is true, a name is generated using the fullname template # If not set and create is true, a name is generated using the fullname template
name: "" name: ""
# -- additional pod annotations # -- additonal pod annotations
podAnnotations: {} podAnnotations: {}
podSecurityContext: podSecurityContext:
@@ -209,7 +209,7 @@ ingress:
# - kubernetes.docker.internal # - kubernetes.docker.internal
resources: {} resources: {}
# The following are indicative for a small-size deployment, for anything serious double them. # The following are indicative for a small-size deployement, for anything serious double them.
# limits: # limits:
# cpu: 100m # cpu: 100m
# memory: 1024Mi # memory: 1024Mi
+3 -3
View File
@@ -127,7 +127,7 @@ They are due to the download being interrupted in the middle (^C during first la
Add `:force?` to the `cached-wget!` call in `daemon.clj` to re-download the binary, Add `:force?` to the `cached-wget!` call in `daemon.clj` to re-download the binary,
or restar the VMs to clear temporary files. or restar the VMs to clear temporary files.
### In `jepsen.garage`: prefix weirdness ### In `jepsen.garage`: prefix wierdness
In `store/garage set1/20231019T163358.615+0200`: In `store/garage set1/20231019T163358.615+0200`:
@@ -146,12 +146,12 @@ and passing all values that were previously in the context (creds and prefix) as
The reg2 test is our custom checker for CRDT read-after-write on individual object keys, acting as registers which can be updated. The reg2 test is our custom checker for CRDT read-after-write on individual object keys, acting as registers which can be updated.
The test fails without the timestamp fix, which is expected as the clock scrambler will prevent nodes from having a correct ordering of objects. The test fails without the timestamp fix, which is expected as the clock scrambler will prevent nodes from having a correct ordering of objects.
With the timestamp fix (`--patch tsfix1`), the happened-before relationship should at least be respected, meaning that when a PutObject call starts With the timestamp fix (`--patch tsfix1`), the happenned-before relationship should at least be respected, meaning that when a PutObject call starts
after another PutObject call has ended, the second call should overwrite the value of the first call, and that value should not be after another PutObject call has ended, the second call should overwrite the value of the first call, and that value should not be
readable by future GetObject calls. readable by future GetObject calls.
However, we observed inconsistencies even with the timestamp fix. However, we observed inconsistencies even with the timestamp fix.
The inconsistencies seemed to always happened after writing a nil value, which translates to a DeleteObject call The inconsistencies seemed to always happenned after writing a nil value, which translates to a DeleteObject call
instead of a PutObject. By removing the possibility of writing nil values, therefore only doing instead of a PutObject. By removing the possibility of writing nil values, therefore only doing
PutObject calls, the issue disappears. There is therefore an issue to fix in DeleteObject. PutObject calls, the issue disappears. There is therefore an issue to fix in DeleteObject.
+2 -2
View File
@@ -2,7 +2,7 @@
: ' : '
This script tests whether uploaded parts can be skipped in a This script tests whether uploaded parts can be skipped in a
CompleteMultipartUpload CompleteMultipartUpoad
On Minio: yes, parts can be skipped On Minio: yes, parts can be skipped
@@ -52,7 +52,7 @@
Conclusions: Conclusions:
- Skipping a part in a CompleteMultipartUpload call is OK - Skipping a part in a CompleteMultipartUpoad call is OK
- The part is simply not included in the stored object - The part is simply not included in the stored object
- Sequential part renumbering counts only non-skipped parts - Sequential part renumbering counts only non-skipped parts
' '
+1 -2
View File
@@ -34,7 +34,6 @@ in
openssl openssl
curl curl
jq jq
typos
]; ];
shellHook = '' shellHook = ''
export AWS_REQUEST_CHECKSUM_CALCULATION='when_required' export AWS_REQUEST_CHECKSUM_CALCULATION='when_required'
@@ -52,7 +51,7 @@ in
function to_docker { function to_docker {
executor \ executor \
--force \ --force \
--custom-platform="$(echo "''${DOCKER_PLATFORM}" | sed 's/i386/386/')" \ --customPlatform="$(echo "''${DOCKER_PLATFORM}" | sed 's/i386/386/')" \
--destination "$(echo "''${CONTAINER_NAME}" | sed 's/i386/386/'):''${CONTAINER_TAG}" \ --destination "$(echo "''${CONTAINER_NAME}" | sed 's/i386/386/'):''${CONTAINER_TAG}" \
--context dir://`pwd` \ --context dir://`pwd` \
--verbosity=debug --verbosity=debug
+2 -2
View File
@@ -46,5 +46,5 @@ opentelemetry-prometheus = { workspace = true, optional = true }
prometheus = { workspace = true, optional = true } prometheus = { workspace = true, optional = true }
[features] [features]
metrics = ["opentelemetry-prometheus", "prometheus"] metrics = [ "opentelemetry-prometheus", "prometheus" ]
k2v = ["garage_model/k2v"] k2v = [ "garage_model/k2v" ]
+3 -3
View File
@@ -143,7 +143,7 @@ impl RequestHandler for UpdateAdminTokenRequest {
garage: &Arc<Garage>, garage: &Arc<Garage>,
_admin: &Admin, _admin: &Admin,
) -> Result<UpdateAdminTokenResponse, Error> { ) -> Result<UpdateAdminTokenResponse, Error> {
let mut token = get_existing_admin_token(garage, &self.id).await?; let mut token = get_existing_admin_token(&garage, &self.id).await?;
apply_token_updates(&mut token, self.body)?; apply_token_updates(&mut token, self.body)?;
@@ -164,7 +164,7 @@ impl RequestHandler for DeleteAdminTokenRequest {
garage: &Arc<Garage>, garage: &Arc<Garage>,
_admin: &Admin, _admin: &Admin,
) -> Result<DeleteAdminTokenResponse, Error> { ) -> Result<DeleteAdminTokenResponse, Error> {
let token = get_existing_admin_token(garage, &self.id).await?; let token = get_existing_admin_token(&garage, &self.id).await?;
garage garage
.admin_token_table .admin_token_table
@@ -224,7 +224,7 @@ impl RequestHandler for GetCurrentAdminTokenInfoRequest {
} }
let (prefix, _) = self.admin_token.split_once('.').unwrap(); let (prefix, _) = self.admin_token.split_once('.').unwrap();
let token = get_existing_admin_token(garage, &prefix.to_string()).await?; let token = get_existing_admin_token(&garage, &prefix.to_string()).await?;
Ok(GetCurrentAdminTokenInfoResponse(admin_token_info_results( Ok(GetCurrentAdminTokenInfoResponse(admin_token_info_results(
&token, now, &token, now,
+3 -3
View File
@@ -262,7 +262,7 @@ pub struct GetClusterHealthResponse {
pub status: String, pub status: String,
/// the number of nodes this Garage node has had a TCP connection to since the daemon started /// the number of nodes this Garage node has had a TCP connection to since the daemon started
pub known_nodes: usize, pub known_nodes: usize,
/// the number of nodes this Garage node currently has an open connection to /// the nubmer of nodes this Garage node currently has an open connection to
pub connected_nodes: usize, pub connected_nodes: usize,
/// the number of storage nodes currently registered in the cluster layout /// the number of storage nodes currently registered in the cluster layout
pub storage_nodes: usize, pub storage_nodes: usize,
@@ -387,7 +387,7 @@ pub struct UpdateAdminTokenRequestBody {
/// `GetClusterStatus`, etc), or the special value `*` to allow all /// `GetClusterStatus`, etc), or the special value `*` to allow all
/// admin endpoints. **WARNING:** Granting a scope of `CreateAdminToken` or /// admin endpoints. **WARNING:** Granting a scope of `CreateAdminToken` or
/// `UpdateAdminToken` trivially allows for privilege escalation, and is thus /// `UpdateAdminToken` trivially allows for privilege escalation, and is thus
/// functionally equivalent to granting a scope of `*`. /// functionnally equivalent to granting a scope of `*`.
pub scope: Option<Vec<String>>, pub scope: Option<Vec<String>>,
} }
@@ -841,7 +841,7 @@ pub struct GetBucketInfoResponse {
pub created: DateTime<Utc>, pub created: DateTime<Utc>,
/// List of global aliases for this bucket /// List of global aliases for this bucket
pub global_aliases: Vec<String>, pub global_aliases: Vec<String>,
/// Whether website access is enabled for this bucket /// Whether website acces is enabled for this bucket
pub website_access: bool, pub website_access: bool,
#[serde(default)] #[serde(default)]
/// Website configuration for this bucket /// Website configuration for this bucket
+7 -7
View File
@@ -64,7 +64,7 @@ impl EndpointHandler<AdminRpc> for AdminApiServer {
match message { match message {
AdminRpc::Proxy(req) => { AdminRpc::Proxy(req) => {
info!("Proxied admin API request: {}", req.name()); info!("Proxied admin API request: {}", req.name());
let res = req.clone().handle(&self.garage, self).await; let res = req.clone().handle(&self.garage, &self).await;
match res { match res {
Ok(res) => Ok(AdminRpcResponse::ProxyApiOkResponse(res.tagged())), Ok(res) => Ok(AdminRpcResponse::ProxyApiOkResponse(res.tagged())),
Err(e) => Ok(AdminRpcResponse::ApiErrorResponse { Err(e) => Ok(AdminRpcResponse::ApiErrorResponse {
@@ -76,7 +76,7 @@ impl EndpointHandler<AdminRpc> for AdminApiServer {
} }
AdminRpc::Internal(req) => { AdminRpc::Internal(req) => {
info!("Internal admin API request: {}", req.name()); info!("Internal admin API request: {}", req.name());
let res = req.clone().handle(&self.garage, self).await; let res = req.clone().handle(&self.garage, &self).await;
match res { match res {
Ok(res) => Ok(AdminRpcResponse::InternalApiOkResponse(res)), Ok(res) => Ok(AdminRpcResponse::InternalApiOkResponse(res)),
Err(e) => Ok(AdminRpcResponse::ApiErrorResponse { Err(e) => Ok(AdminRpcResponse::ApiErrorResponse {
@@ -173,12 +173,12 @@ impl AdminApiServer {
} }
match request { match request {
AdminApiRequest::Options(req) => req.handle(&self.garage, self).await, AdminApiRequest::Options(req) => req.handle(&self.garage, &self).await,
AdminApiRequest::CheckDomain(req) => req.handle(&self.garage, self).await, AdminApiRequest::CheckDomain(req) => req.handle(&self.garage, &self).await,
AdminApiRequest::Health(req) => req.handle(&self.garage, self).await, AdminApiRequest::Health(req) => req.handle(&self.garage, &self).await,
AdminApiRequest::Metrics(req) => req.handle(&self.garage, self).await, AdminApiRequest::Metrics(req) => req.handle(&self.garage, &self).await,
req => { req => {
let res = req.handle(&self.garage, self).await?; let res = req.handle(&self.garage, &self).await?;
let mut res = json_ok_response(&res)?; let mut res = json_ok_response(&res)?;
res.headers_mut() res.headers_mut()
.insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*")); .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
+9 -9
View File
@@ -29,7 +29,7 @@ impl RequestHandler for LocalListBlockErrorsRequest {
let errors = errors let errors = errors
.into_iter() .into_iter()
.map(|e| BlockError { .map(|e| BlockError {
block_hash: hex::encode(e.hash), block_hash: hex::encode(&e.hash),
refcount: e.refcount, refcount: e.refcount,
error_count: e.error_count, error_count: e.error_count,
last_try_secs_ago: now.saturating_sub(e.last_try) / 1000, last_try_secs_ago: now.saturating_sub(e.last_try) / 1000,
@@ -61,15 +61,15 @@ impl RequestHandler for LocalGetBlockInfoRequest {
VersionBacklink::MultipartUpload { upload_id } => { VersionBacklink::MultipartUpload { upload_id } => {
if let Some(u) = garage.mpu_table.get(upload_id, &EmptyKey).await? { if let Some(u) = garage.mpu_table.get(upload_id, &EmptyKey).await? {
BlockVersionBacklink::Upload { BlockVersionBacklink::Upload {
upload_id: hex::encode(upload_id), upload_id: hex::encode(&upload_id),
upload_deleted: u.deleted.get(), upload_deleted: u.deleted.get(),
upload_garbage_collected: false, upload_garbage_collected: false,
bucket_id: Some(hex::encode(u.bucket_id)), bucket_id: Some(hex::encode(&u.bucket_id)),
key: Some(u.key.to_string()), key: Some(u.key.to_string()),
} }
} else { } else {
BlockVersionBacklink::Upload { BlockVersionBacklink::Upload {
upload_id: hex::encode(upload_id), upload_id: hex::encode(&upload_id),
upload_deleted: true, upload_deleted: true,
upload_garbage_collected: true, upload_garbage_collected: true,
bucket_id: None, bucket_id: None,
@@ -78,12 +78,12 @@ impl RequestHandler for LocalGetBlockInfoRequest {
} }
} }
VersionBacklink::Object { bucket_id, key } => BlockVersionBacklink::Object { VersionBacklink::Object { bucket_id, key } => BlockVersionBacklink::Object {
bucket_id: hex::encode(bucket_id), bucket_id: hex::encode(&bucket_id),
key: key.to_string(), key: key.to_string(),
}, },
}; };
versions.push(BlockVersion { versions.push(BlockVersion {
version_id: hex::encode(br.version), version_id: hex::encode(&br.version),
ref_deleted: br.deleted.get(), ref_deleted: br.deleted.get(),
version_deleted: v.deleted.get(), version_deleted: v.deleted.get(),
garbage_collected: false, garbage_collected: false,
@@ -91,7 +91,7 @@ impl RequestHandler for LocalGetBlockInfoRequest {
}); });
} else { } else {
versions.push(BlockVersion { versions.push(BlockVersion {
version_id: hex::encode(br.version), version_id: hex::encode(&br.version),
ref_deleted: br.deleted.get(), ref_deleted: br.deleted.get(),
version_deleted: true, version_deleted: true,
garbage_collected: true, garbage_collected: true,
@@ -100,7 +100,7 @@ impl RequestHandler for LocalGetBlockInfoRequest {
} }
} }
Ok(LocalGetBlockInfoResponse { Ok(LocalGetBlockInfoResponse {
block_hash: hex::encode(hash), block_hash: hex::encode(&hash),
refcount, refcount,
versions, versions,
}) })
@@ -215,7 +215,7 @@ fn find_block_hash_by_prefix(garage: &Arc<Garage>, prefix: &str) -> Result<Hash,
for item in iter { for item in iter {
let (k, _v) = item.map_err(GarageError::from)?; let (k, _v) = item.map_err(GarageError::from)?;
let hash = Hash::try_from(&k[..32]).unwrap(); let hash = Hash::try_from(&k[..32]).unwrap();
if hash.as_slice()[..prefix_bin.len()] != prefix_bin { if &hash.as_slice()[..prefix_bin.len()] != prefix_bin {
break; break;
} }
if hex::encode(hash.as_slice()).starts_with(prefix) { if hex::encode(hash.as_slice()).starts_with(prefix) {
+4 -4
View File
@@ -183,7 +183,7 @@ impl RequestHandler for CreateBucketRequest {
let key = helper.key().get_existing_key(&la.access_key_id).await?; let key = helper.key().get_existing_key(&la.access_key_id).await?;
let state = key.state.as_option().unwrap(); let state = key.state.as_option().unwrap();
if state.local_aliases.get(&la.alias).is_some() { if matches!(state.local_aliases.get(&la.alias), Some(_)) {
return Err(Error::bad_request("Local alias already exists")); return Err(Error::bad_request("Local alias already exists"));
} }
} }
@@ -380,13 +380,13 @@ impl RequestHandler for InspectObjectRequest {
.map(|(vk, vb)| InspectObjectBlock { .map(|(vk, vb)| InspectObjectBlock {
part_number: vk.part_number, part_number: vk.part_number,
offset: vk.offset, offset: vk.offset,
hash: hex::encode(vb.hash), hash: hex::encode(&vb.hash),
size: vb.size, size: vb.size,
}) })
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.unwrap_or_default(); .unwrap_or_default();
let uuid = hex::encode(obj_ver.uuid); let uuid = hex::encode(&obj_ver.uuid);
let timestamp = DateTime::from_timestamp_millis(obj_ver.timestamp as i64) let timestamp = DateTime::from_timestamp_millis(obj_ver.timestamp as i64)
.expect("invalid timestamp in db"); .expect("invalid timestamp in db");
match &obj_ver.state { match &obj_ver.state {
@@ -467,7 +467,7 @@ impl RequestHandler for InspectObjectRequest {
} }
Ok(InspectObjectResponse { Ok(InspectObjectResponse {
bucket_id: hex::encode(object.bucket_id), bucket_id: hex::encode(&object.bucket_id),
key: object.key, key: object.key,
versions, versions,
}) })
+1 -1
View File
@@ -91,7 +91,7 @@ impl RequestHandler for GetKeyInfoRequest {
} }
}; };
key_info_results(garage, key, self.show_secret_key).await Ok(key_info_results(garage, key, self.show_secret_key).await?)
} }
} }
+9 -11
View File
@@ -143,7 +143,7 @@ impl RequestHandler for GetClusterLayoutHistoryRequest {
.iter() .iter()
.map(|node| { .map(|node| {
( (
hex::encode(node), hex::encode(&node),
NodeUpdateTrackers { NodeUpdateTrackers {
ack: layout.update_trackers.ack_map.get(node, min_stored), ack: layout.update_trackers.ack_map.get(node, min_stored),
sync: layout.update_trackers.sync_map.get(node, min_stored), sync: layout.update_trackers.sync_map.get(node, min_stored),
@@ -343,16 +343,14 @@ impl RequestHandler for ClusterLayoutSkipDeadNodesRequest {
for node in all_nodes.iter() { for node in all_nodes.iter() {
// Update ACK tracker for dead nodes or for all nodes if --allow-missing-data // Update ACK tracker for dead nodes or for all nodes if --allow-missing-data
if self.allow_missing_data || !status.iter().any(|x| x.id == *node && x.is_up) { if self.allow_missing_data || !status.iter().any(|x| x.id == *node && x.is_up) {
let ack_changed = layout.update_trackers.ack_map.set_max(*node, self.version); if layout.update_trackers.ack_map.set_max(*node, self.version) {
if ack_changed {
ack_updated.push(hex::encode(node)); ack_updated.push(hex::encode(node));
} }
} }
// If --allow-missing-data, update SYNC tracker for all nodes. // If --allow-missing-data, update SYNC tracker for all nodes.
if self.allow_missing_data { if self.allow_missing_data {
let sync_changed = layout.update_trackers.sync_map.set_max(*node, self.version); if layout.update_trackers.sync_map.set_max(*node, self.version) {
if sync_changed {
sync_updated.push(hex::encode(node)); sync_updated.push(hex::encode(node));
} }
} }
@@ -382,9 +380,9 @@ impl From<layout::ZoneRedundancy> for ZoneRedundancy {
} }
} }
impl From<ZoneRedundancy> for layout::ZoneRedundancy { impl Into<layout::ZoneRedundancy> for ZoneRedundancy {
fn from(val: ZoneRedundancy) -> Self { fn into(self) -> layout::ZoneRedundancy {
match val { match self {
ZoneRedundancy::Maximum => layout::ZoneRedundancy::Maximum, ZoneRedundancy::Maximum => layout::ZoneRedundancy::Maximum,
ZoneRedundancy::AtLeast(x) => layout::ZoneRedundancy::AtLeast(x), ZoneRedundancy::AtLeast(x) => layout::ZoneRedundancy::AtLeast(x),
} }
@@ -399,10 +397,10 @@ impl From<layout::LayoutParameters> for LayoutParameters {
} }
} }
impl From<LayoutParameters> for layout::LayoutParameters { impl Into<layout::LayoutParameters> for LayoutParameters {
fn from(val: LayoutParameters) -> Self { fn into(self) -> layout::LayoutParameters {
layout::LayoutParameters { layout::LayoutParameters {
zone_redundancy: val.zone_redundancy.into(), zone_redundancy: self.zone_redundancy.into(),
} }
} }
} }
+61 -58
View File
@@ -19,7 +19,7 @@ use crate::api::*;
(status = 200, description = "Garage daemon metrics exported in Prometheus format"), (status = 200, description = "Garage daemon metrics exported in Prometheus format"),
), ),
)] )]
fn Metrics() {} fn Metrics() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/health", path = "/health",
@@ -36,7 +36,7 @@ as long as it is able to have a quorum of nodes for read and write operations.
(status = 503, description = "This Garage daemon is not able to handle requests") (status = 503, description = "This Garage daemon is not able to handle requests")
), ),
)] )]
fn Health() {} fn Health() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/check", path = "/check",
@@ -54,7 +54,7 @@ do not correspond to an actual website.
(status = 400, description = "No static website bucket exists for this domain") (status = 400, description = "No static website bucket exists for this domain")
), ),
)] )]
fn CheckDomain() {} fn CheckDomain() -> () {}
// ********************************************** // **********************************************
// Cluster operations // Cluster operations
@@ -78,7 +78,7 @@ Returns the cluster's current status, including:
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetClusterStatus() {} fn GetClusterStatus() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetClusterHealth", path = "/v2/GetClusterHealth",
@@ -88,7 +88,7 @@ fn GetClusterStatus() {}
(status = 200, description = "Cluster health report", body = GetClusterHealthResponse), (status = 200, description = "Cluster health report", body = GetClusterHealthResponse),
), ),
)] )]
fn GetClusterHealth() {} fn GetClusterHealth() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetClusterStatistics", path = "/v2/GetClusterStatistics",
@@ -103,7 +103,7 @@ Fetch global cluster statistics.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetClusterStatistics() {} fn GetClusterStatistics() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/ConnectClusterNodes", path = "/v2/ConnectClusterNodes",
@@ -115,7 +115,7 @@ fn GetClusterStatistics() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ConnectClusterNodes() {} fn ConnectClusterNodes() -> () {}
// ********************************************** // **********************************************
// Admin API token operations // Admin API token operations
@@ -130,7 +130,7 @@ fn ConnectClusterNodes() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ListAdminTokens() {} fn ListAdminTokens() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetAdminTokenInfo", path = "/v2/GetAdminTokenInfo",
@@ -145,7 +145,7 @@ You can search by specifying the exact token identifier (`id`) or by specifying
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetAdminTokenInfo() {} fn GetAdminTokenInfo() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/CreateAdminToken", path = "/v2/CreateAdminToken",
@@ -157,7 +157,7 @@ fn GetAdminTokenInfo() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn CreateAdminToken() {} fn CreateAdminToken() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/UpdateAdminToken", path = "/v2/UpdateAdminToken",
@@ -172,7 +172,7 @@ Updates information about the specified admin API token.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn UpdateAdminToken() {} fn UpdateAdminToken() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/DeleteAdminToken", path = "/v2/DeleteAdminToken",
@@ -184,7 +184,7 @@ fn UpdateAdminToken() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn DeleteAdminToken() {} fn DeleteAdminToken() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetCurrentAdminTokenInfo", path = "/v2/GetCurrentAdminTokenInfo",
@@ -197,7 +197,7 @@ Return information about the calling admin API token.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetCurrentAdminTokenInfo() {} fn GetCurrentAdminTokenInfo() -> () {}
// ********************************************** // **********************************************
// Layout operations // Layout operations
@@ -219,7 +219,7 @@ Returns the cluster's current layout, including:
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetClusterLayout() {} fn GetClusterLayout() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetClusterLayoutHistory", path = "/v2/GetClusterLayoutHistory",
@@ -232,7 +232,7 @@ Returns the history of layouts in the cluster
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetClusterLayoutHistory() {} fn GetClusterLayoutHistory() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/UpdateClusterLayout", path = "/v2/UpdateClusterLayout",
@@ -261,7 +261,7 @@ Contrary to the CLI that may update only a subset of the fields capacity, zone a
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn UpdateClusterLayout() {} fn UpdateClusterLayout() -> () {}
// Hack: we cannot use the UpdateClusterLayoutRequest from api.rs, // Hack: we cannot use the UpdateClusterLayoutRequest from api.rs,
// as it contains (via NodeRoleChange) an untagged enum flattenned into // as it contains (via NodeRoleChange) an untagged enum flattenned into
@@ -293,13 +293,16 @@ pub enum NodeRoleChangeOpenapi {
/// Set `remove` to `true` to remove the node from the layout /// Set `remove` to `true` to remove the node from the layout
remove: bool, remove: bool,
}, },
#[serde(rename_all = "camelCase")] Update(NodeRoleUpdate),
Update { }
/// ID of the node for which this change applies
id: String, #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(flatten)] #[serde(rename_all = "camelCase")]
role: NodeAssignedRole, pub struct NodeRoleUpdate {
}, /// ID of the node for which this change applies
id: String,
#[serde(flatten)]
role: NodeAssignedRole,
} }
#[utoipa::path(post, #[utoipa::path(post,
@@ -315,7 +318,7 @@ Computes a new layout taking into account the staged parameters, and returns it
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn PreviewClusterLayoutChanges() {} fn PreviewClusterLayoutChanges() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/ApplyClusterLayout", path = "/v2/ApplyClusterLayout",
@@ -331,7 +334,7 @@ Applies to the cluster the layout changes currently registered as staged layout
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ApplyClusterLayout() {} fn ApplyClusterLayout() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/RevertClusterLayout", path = "/v2/RevertClusterLayout",
@@ -342,7 +345,7 @@ fn ApplyClusterLayout() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn RevertClusterLayout() {} fn RevertClusterLayout() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/ClusterLayoutSkipDeadNodes", path = "/v2/ClusterLayoutSkipDeadNodes",
@@ -354,7 +357,7 @@ fn RevertClusterLayout() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ClusterLayoutSkipDeadNodes() {} fn ClusterLayoutSkipDeadNodes() -> () {}
// ********************************************** // **********************************************
// Access key operations // Access key operations
@@ -369,7 +372,7 @@ fn ClusterLayoutSkipDeadNodes() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ListKeys() {} fn ListKeys() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetKeyInfo", path = "/v2/GetKeyInfo",
@@ -386,7 +389,7 @@ For confidentiality reasons, the secret key is not returned by default: you must
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetKeyInfo() {} fn GetKeyInfo() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/CreateKey", path = "/v2/CreateKey",
@@ -398,7 +401,7 @@ fn GetKeyInfo() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn CreateKey() {} fn CreateKey() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/ImportKey", path = "/v2/ImportKey",
@@ -414,7 +417,7 @@ Imports an existing API key. This feature must only be used for migrations and b
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ImportKey() {} fn ImportKey() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/UpdateKey", path = "/v2/UpdateKey",
@@ -431,7 +434,7 @@ Updates information about the specified API access key.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn UpdateKey() {} fn UpdateKey() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/DeleteKey", path = "/v2/DeleteKey",
@@ -443,7 +446,7 @@ fn UpdateKey() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn DeleteKey() {} fn DeleteKey() -> () {}
// ********************************************** // **********************************************
// Bucket operations // Bucket operations
@@ -458,7 +461,7 @@ fn DeleteKey() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ListBuckets() {} fn ListBuckets() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetBucketInfo", path = "/v2/GetBucketInfo",
@@ -475,7 +478,7 @@ and its quotas (if any).
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetBucketInfo() {} fn GetBucketInfo() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/CreateBucket", path = "/v2/CreateBucket",
@@ -490,7 +493,7 @@ Technically, you can also specify both `globalAlias` and `localAlias` and that w
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn CreateBucket() {} fn CreateBucket() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/UpdateBucket", path = "/v2/UpdateBucket",
@@ -516,7 +519,7 @@ to change only one of the two quotas.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn UpdateBucket() {} fn UpdateBucket() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/DeleteBucket", path = "/v2/DeleteBucket",
@@ -534,7 +537,7 @@ Deletes a storage bucket. A bucket cannot be deleted if it is not empty.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn DeleteBucket() {} fn DeleteBucket() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/CleanupIncompleteUploads", path = "/v2/CleanupIncompleteUploads",
@@ -546,7 +549,7 @@ fn DeleteBucket() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn CleanupIncompleteUploads() {} fn CleanupIncompleteUploads() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/InspectObject", path = "/v2/InspectObject",
@@ -568,7 +571,7 @@ upload is in progress and not yet finished.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn InspectObject() {} fn InspectObject() -> () {}
// ********************************************** // **********************************************
// Operations on permissions for keys on buckets // Operations on permissions for keys on buckets
@@ -594,7 +597,7 @@ If you want to disallow read for the key, check the DenyBucketKey operation.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn AllowBucketKey() {} fn AllowBucketKey() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/DenyBucketKey", path = "/v2/DenyBucketKey",
@@ -616,7 +619,7 @@ If you want the key to have the reading permission, check the AllowBucketKey ope
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn DenyBucketKey() {} fn DenyBucketKey() -> () {}
// ********************************************** // **********************************************
// Operations on bucket aliases // Operations on bucket aliases
@@ -632,7 +635,7 @@ fn DenyBucketKey() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn AddBucketAlias() {} fn AddBucketAlias() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/RemoveBucketAlias", path = "/v2/RemoveBucketAlias",
@@ -644,7 +647,7 @@ fn AddBucketAlias() {}
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn RemoveBucketAlias() {} fn RemoveBucketAlias() -> () {}
// Hack for issue #1249 (see UpdateClusterLayout) // Hack for issue #1249 (see UpdateClusterLayout)
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
@@ -680,7 +683,7 @@ Return information about the Garage daemon running on one or several nodes.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetNodeInfo() {} fn GetNodeInfo() -> () {}
#[utoipa::path(get, #[utoipa::path(get,
path = "/v2/GetNodeStatistics", path = "/v2/GetNodeStatistics",
@@ -696,7 +699,7 @@ Fetch statistics for one or several Garage nodes.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetNodeStatistics() {} fn GetNodeStatistics() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/CreateMetadataSnapshot", path = "/v2/CreateMetadataSnapshot",
@@ -710,7 +713,7 @@ Instruct one or several nodes to take a snapshot of their metadata databases.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn CreateMetadataSnapshot() {} fn CreateMetadataSnapshot() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/LaunchRepairOperation", path = "/v2/LaunchRepairOperation",
@@ -725,7 +728,7 @@ Launch a repair operation on one or several cluster nodes.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn LaunchRepairOperation() {} fn LaunchRepairOperation() -> () {}
// ********************************************** // **********************************************
// Worker operations // Worker operations
@@ -744,7 +747,7 @@ List background workers currently running on one or several cluster nodes.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ListWorkers() {} fn ListWorkers() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/GetWorkerInfo", path = "/v2/GetWorkerInfo",
@@ -759,7 +762,7 @@ Get information about the specified background worker on one or several cluster
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetWorkerInfo() {} fn GetWorkerInfo() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/GetWorkerVariable", path = "/v2/GetWorkerVariable",
@@ -774,7 +777,7 @@ Fetch values of one or several worker variables, from one or several cluster nod
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetWorkerVariable() {} fn GetWorkerVariable() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/SetWorkerVariable", path = "/v2/SetWorkerVariable",
@@ -789,7 +792,7 @@ Set the value for a worker variable, on one or several cluster nodes.
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn SetWorkerVariable() {} fn SetWorkerVariable() -> () {}
// ********************************************** // **********************************************
// Block operations // Block operations
@@ -807,7 +810,7 @@ List data blocks that are currently in an errored state on one or several Garage
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn ListBlockErrors() {} fn ListBlockErrors() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/GetBlockInfo", path = "/v2/GetBlockInfo",
@@ -822,7 +825,7 @@ Get detailed information about a data block stored on a Garage node, including a
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn GetBlockInfo() {} fn GetBlockInfo() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/RetryBlockResync", path = "/v2/RetryBlockResync",
@@ -837,7 +840,7 @@ Instruct Garage node(s) to retry the resynchronization of one or several missing
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn RetryBlockResync() {} fn RetryBlockResync() -> () {}
#[utoipa::path(post, #[utoipa::path(post,
path = "/v2/PurgeBlocks", path = "/v2/PurgeBlocks",
@@ -854,7 +857,7 @@ This will remove all objects and in-progress multipart uploads that contain the
(status = 500, description = "Internal server error") (status = 500, description = "Internal server error")
), ),
)] )]
fn PurgeBlocks() {} fn PurgeBlocks() -> () {}
// ********************************************** // **********************************************
// ********************************************** // **********************************************
@@ -878,9 +881,9 @@ impl Modify for SecurityAddon {
info( info(
version = "v2.2.0", version = "v2.2.0",
title = "Garage administration API", title = "Garage administration API",
description = "Administrate your Garage cluster programmatically, including status, layout, keys, buckets, and maintenance tasks. description = "Administrate your Garage cluster programatically, including status, layout, keys, buckets, and maintainance tasks.
*Disclaimer: This API may change in future Garage versions. Read the changelog and upgrade your scripts before upgrading. Additionally, this specification is early stage and can contain bugs, so be careful and please report any issues on our issue tracker.*", *Disclaimer: This API may change in future Garage versions. Read the changelog and upgrade your scripts before upgrading. Additionnaly, this specification is early stage and can contain bugs, so be careful and please report any issues on our issue tracker.*",
contact( contact(
name = "The Garage team", name = "The Garage team",
email = "garagehq@deuxfleurs.fr", email = "garagehq@deuxfleurs.fr",
+1 -1
View File
@@ -345,7 +345,7 @@ impl BlockRcRepair {
#[async_trait] #[async_trait]
impl Worker for BlockRcRepair { impl Worker for BlockRcRepair {
fn name(&self) -> String { fn name(&self) -> String {
"Block refcount repair worker".into() format!("Block refcount repair worker")
} }
fn status(&self) -> WorkerStatus { fn status(&self) -> WorkerStatus {
+1 -1
View File
@@ -150,7 +150,7 @@ impl TryFrom<HelperError> for CommonError {
pub fn pass_helper_error(err: HelperError) -> CommonError { pub fn pass_helper_error(err: HelperError) -> CommonError {
match CommonError::try_from(err) { match CommonError::try_from(err) {
Ok(e) => e, Ok(e) => e,
Err(e) => panic!("Helper error `{}` should hot have happened here", e), Err(e) => panic!("Helper error `{}` should hot have happenned here", e),
} }
} }
+1 -1
View File
@@ -88,7 +88,7 @@ pub fn handle_options_api(
// the same name, its CORS rules won't be applied // the same name, its CORS rules won't be applied
// and will be shadowed by the rules of the globally // and will be shadowed by the rules of the globally
// existing bucket (but this is inevitable because // existing bucket (but this is inevitable because
// OPTIONS calls are not authenticated). // OPTIONS calls are not auhtenticated).
if let Some(bn) = bucket_name { if let Some(bn) = bucket_name {
let helper = garage.bucket_helper(); let helper = garage.bucket_helper();
let bucket_opt = helper.resolve_global_bucket_fast(&bn)?; let bucket_opt = helper.resolve_global_bucket_fast(&bn)?;
+1 -1
View File
@@ -154,7 +154,7 @@ impl<A: ApiHandler> ApiServer<A> {
{ {
format!("{forwarded_for_ip_addr} (via {addr})") format!("{forwarded_for_ip_addr} (via {addr})")
} else { } else {
addr format!("{addr}")
}; };
// we only do this to log the access key, so we can discard any error // we only do this to log the access key, so we can discard any error
let key = self let key = self
+1 -1
View File
@@ -191,7 +191,7 @@ macro_rules! router_match {
}}; }};
(@@parse_param $query:expr, parse_default($default:expr), $param:ident) => {{ (@@parse_param $query:expr, parse_default($default:expr), $param:ident) => {{
// extract and parse optional query parameter // extract and parse optional query parameter
// using provided value as default if parameter is missing // using provided value as default if paramter is missing
$query.$param.take().map(|x| x $query.$param.take().map(|x| x
.parse() .parse()
.map_err(|_| Error::bad_request("Failed to parse query parameter"))) .map_err(|_| Error::bad_request("Failed to parse query parameter")))
+20 -14
View File
@@ -63,7 +63,6 @@ pub struct ExpectedChecksums {
pub extra: Option<ChecksumValue>, pub extra: Option<ChecksumValue>,
} }
#[derive(Default)]
pub struct Checksummer { pub struct Checksummer {
pub crc32: Option<CrcDigest>, pub crc32: Option<CrcDigest>,
pub crc32c: Option<CrcDigest>, pub crc32c: Option<CrcDigest>,
@@ -85,7 +84,14 @@ pub struct Checksums {
impl Checksummer { impl Checksummer {
pub fn new() -> Self { pub fn new() -> Self {
Default::default() Self {
crc32: None,
crc32c: None,
crc64nvme: None,
md5: None,
sha1: None,
sha256: None,
}
} }
pub fn init(expected: &ExpectedChecksums, add_md5: bool) -> Self { pub fn init(expected: &ExpectedChecksums, add_md5: bool) -> Self {
@@ -122,7 +128,7 @@ impl Checksummer {
} }
} }
pub fn add_algorithm(mut self, algo: Option<ChecksumAlgorithm>) -> Self { pub fn add(mut self, algo: Option<ChecksumAlgorithm>) -> Self {
match algo { match algo {
Some(ChecksumAlgorithm::Crc32) => { Some(ChecksumAlgorithm::Crc32) => {
self.crc32 = Some(new_crc32()); self.crc32 = Some(new_crc32());
@@ -181,7 +187,7 @@ impl Checksums {
pub fn verify(&self, expected: &ExpectedChecksums) -> Result<(), Error> { pub fn verify(&self, expected: &ExpectedChecksums) -> Result<(), Error> {
if let Some(expected_md5) = &expected.md5 { if let Some(expected_md5) = &expected.md5 {
match self.md5 { match self.md5 {
Some(md5) if BASE64_STANDARD.encode(md5) == expected_md5.trim_matches('"') => (), Some(md5) if BASE64_STANDARD.encode(&md5) == expected_md5.trim_matches('"') => (),
_ => { _ => {
return Err(Error::InvalidDigest( return Err(Error::InvalidDigest(
"MD5 checksum verification failed (from content-md5)".into(), "MD5 checksum verification failed (from content-md5)".into(),
@@ -306,7 +312,7 @@ pub fn extract_checksum_value(
ChecksumAlgorithm::Crc32 => { ChecksumAlgorithm::Crc32 => {
let crc32 = headers let crc32 = headers
.get(X_AMZ_CHECKSUM_CRC32) .get(X_AMZ_CHECKSUM_CRC32)
.and_then(|x| BASE64_STANDARD.decode(x).ok()) .and_then(|x| BASE64_STANDARD.decode(&x).ok())
.and_then(|x| x.try_into().ok()) .and_then(|x| x.try_into().ok())
.ok_or_bad_request("invalid x-amz-checksum-crc32 header")?; .ok_or_bad_request("invalid x-amz-checksum-crc32 header")?;
Ok(ChecksumValue::Crc32(crc32)) Ok(ChecksumValue::Crc32(crc32))
@@ -314,7 +320,7 @@ pub fn extract_checksum_value(
ChecksumAlgorithm::Crc32c => { ChecksumAlgorithm::Crc32c => {
let crc32c = headers let crc32c = headers
.get(X_AMZ_CHECKSUM_CRC32C) .get(X_AMZ_CHECKSUM_CRC32C)
.and_then(|x| BASE64_STANDARD.decode(x).ok()) .and_then(|x| BASE64_STANDARD.decode(&x).ok())
.and_then(|x| x.try_into().ok()) .and_then(|x| x.try_into().ok())
.ok_or_bad_request("invalid x-amz-checksum-crc32c header")?; .ok_or_bad_request("invalid x-amz-checksum-crc32c header")?;
Ok(ChecksumValue::Crc32c(crc32c)) Ok(ChecksumValue::Crc32c(crc32c))
@@ -322,7 +328,7 @@ pub fn extract_checksum_value(
ChecksumAlgorithm::Crc64Nvme => { ChecksumAlgorithm::Crc64Nvme => {
let crc64nvme = headers let crc64nvme = headers
.get(X_AMZ_CHECKSUM_CRC64NVME) .get(X_AMZ_CHECKSUM_CRC64NVME)
.and_then(|x| BASE64_STANDARD.decode(x).ok()) .and_then(|x| BASE64_STANDARD.decode(&x).ok())
.and_then(|x| x.try_into().ok()) .and_then(|x| x.try_into().ok())
.ok_or_bad_request("invalid x-amz-checksum-crc64nvme header")?; .ok_or_bad_request("invalid x-amz-checksum-crc64nvme header")?;
Ok(ChecksumValue::Crc64Nvme(crc64nvme)) Ok(ChecksumValue::Crc64Nvme(crc64nvme))
@@ -330,7 +336,7 @@ pub fn extract_checksum_value(
ChecksumAlgorithm::Sha1 => { ChecksumAlgorithm::Sha1 => {
let sha1 = headers let sha1 = headers
.get(X_AMZ_CHECKSUM_SHA1) .get(X_AMZ_CHECKSUM_SHA1)
.and_then(|x| BASE64_STANDARD.decode(x).ok()) .and_then(|x| BASE64_STANDARD.decode(&x).ok())
.and_then(|x| x.try_into().ok()) .and_then(|x| x.try_into().ok())
.ok_or_bad_request("invalid x-amz-checksum-sha1 header")?; .ok_or_bad_request("invalid x-amz-checksum-sha1 header")?;
Ok(ChecksumValue::Sha1(sha1)) Ok(ChecksumValue::Sha1(sha1))
@@ -338,7 +344,7 @@ pub fn extract_checksum_value(
ChecksumAlgorithm::Sha256 => { ChecksumAlgorithm::Sha256 => {
let sha256 = headers let sha256 = headers
.get(X_AMZ_CHECKSUM_SHA256) .get(X_AMZ_CHECKSUM_SHA256)
.and_then(|x| BASE64_STANDARD.decode(x).ok()) .and_then(|x| BASE64_STANDARD.decode(&x).ok())
.and_then(|x| x.try_into().ok()) .and_then(|x| x.try_into().ok())
.ok_or_bad_request("invalid x-amz-checksum-sha256 header")?; .ok_or_bad_request("invalid x-amz-checksum-sha256 header")?;
Ok(ChecksumValue::Sha256(sha256)) Ok(ChecksumValue::Sha256(sha256))
@@ -352,19 +358,19 @@ pub fn add_checksum_response_headers(
) -> http::response::Builder { ) -> http::response::Builder {
match checksum { match checksum {
Some(ChecksumValue::Crc32(crc32)) => { Some(ChecksumValue::Crc32(crc32)) => {
resp = resp.header(X_AMZ_CHECKSUM_CRC32, BASE64_STANDARD.encode(crc32)); resp = resp.header(X_AMZ_CHECKSUM_CRC32, BASE64_STANDARD.encode(&crc32));
} }
Some(ChecksumValue::Crc32c(crc32c)) => { Some(ChecksumValue::Crc32c(crc32c)) => {
resp = resp.header(X_AMZ_CHECKSUM_CRC32C, BASE64_STANDARD.encode(crc32c)); resp = resp.header(X_AMZ_CHECKSUM_CRC32C, BASE64_STANDARD.encode(&crc32c));
} }
Some(ChecksumValue::Crc64Nvme(crc64nvme)) => { Some(ChecksumValue::Crc64Nvme(crc64nvme)) => {
resp = resp.header(X_AMZ_CHECKSUM_CRC64NVME, BASE64_STANDARD.encode(crc64nvme)); resp = resp.header(X_AMZ_CHECKSUM_CRC64NVME, BASE64_STANDARD.encode(&crc64nvme));
} }
Some(ChecksumValue::Sha1(sha1)) => { Some(ChecksumValue::Sha1(sha1)) => {
resp = resp.header(X_AMZ_CHECKSUM_SHA1, BASE64_STANDARD.encode(sha1)); resp = resp.header(X_AMZ_CHECKSUM_SHA1, BASE64_STANDARD.encode(&sha1));
} }
Some(ChecksumValue::Sha256(sha256)) => { Some(ChecksumValue::Sha256(sha256)) => {
resp = resp.header(X_AMZ_CHECKSUM_SHA256, BASE64_STANDARD.encode(sha256)); resp = resp.header(X_AMZ_CHECKSUM_SHA256, BASE64_STANDARD.encode(&sha256));
} }
None => (), None => (),
} }
+1 -1
View File
@@ -69,7 +69,7 @@ pub fn verify_request(
mut req: Request<IncomingBody>, mut req: Request<IncomingBody>,
service: &'static str, service: &'static str,
) -> Result<VerifiedRequest, Error> { ) -> Result<VerifiedRequest, Error> {
let checked_signature = payload::check_payload_signature(garage, &mut req, service)?; let checked_signature = payload::check_payload_signature(&garage, &mut req, service)?;
let request = streaming::parse_streaming_body( let request = streaming::parse_streaming_body(
req, req,
+11 -15
View File
@@ -187,7 +187,7 @@ fn check_presigned_signature(
let headers_mut = request.headers_mut(); let headers_mut = request.headers_mut();
for (name, value) in query.iter() { for (name, value) in query.iter() {
if let Some(existing) = headers_mut.get(name) { if let Some(existing) = headers_mut.get(name) {
if signed_headers.contains(name) && existing.as_bytes() != value.value.as_bytes() { if signed_headers.contains(&name) && existing.as_bytes() != value.value.as_bytes() {
return Err(Error::bad_request(format!( return Err(Error::bad_request(format!(
"Conflicting values for `{}` in query parameters and request headers", "Conflicting values for `{}` in query parameters and request headers",
name name
@@ -269,24 +269,20 @@ fn verify_signed_headers(headers: &HeaderMap, signed_headers: &[HeaderName]) ->
return Err(Error::bad_request("Header `Host` should be signed")); return Err(Error::bad_request("Header `Host` should be signed"));
} }
for (name, _) in headers.iter() { for (name, _) in headers.iter() {
// Enforce signature of some headers // Enforce signature of all x-amz-* headers, except x-amz-content-sh256
if header_should_be_signed(name) && !signed_headers.contains(name) { // because it is included in the canonical request in all cases
return Err(Error::bad_request(format!( if name.as_str().starts_with("x-amz-") && name != X_AMZ_CONTENT_SHA256 {
"Header `{}` should be signed", if !signed_headers.contains(name) {
name return Err(Error::bad_request(format!(
))); "Header `{}` should be signed",
name
)));
}
} }
} }
Ok(()) Ok(())
} }
// Indicates whether a header is required to be signed
fn header_should_be_signed(name: &HeaderName) -> bool {
// Enforce signature of all x-amz-* headers, except x-amz-content-sh256
// because it is included in the canonical request in all cases
name.as_str().starts_with("x-amz-") && name != X_AMZ_CONTENT_SHA256
}
pub fn string_to_sign(datetime: &DateTime<Utc>, scope_string: &str, canonical_req: &str) -> String { pub fn string_to_sign(datetime: &DateTime<Utc>, scope_string: &str, canonical_req: &str) -> String {
let mut hasher = Sha256::default(); let mut hasher = Sha256::default();
hasher.update(canonical_req.as_bytes()); hasher.update(canonical_req.as_bytes());
@@ -347,7 +343,7 @@ pub fn canonical_request(
let canonical_query_string = { let canonical_query_string = {
let mut items = Vec::with_capacity(query.len()); let mut items = Vec::with_capacity(query.len());
for (_, QueryValue { key, value }) in query.iter() { for (_, QueryValue { key, value }) in query.iter() {
items.push(uri_encode(key, true) + "=" + &uri_encode(value, true)); items.push(uri_encode(&key, true) + "=" + &uri_encode(&value, true));
} }
items.sort(); items.sort();
items.join("&") items.join("&")
+1 -1
View File
@@ -60,7 +60,7 @@ pub fn parse_streaming_body(
request_trailer_checksum_algorithm(req.headers())? request_trailer_checksum_algorithm(req.headers())?
.ok_or_bad_request("Missing x-amz-trailer header")?, .ok_or_bad_request("Missing x-amz-trailer header")?,
); );
checksummer = checksummer.add_algorithm(algo); checksummer = checksummer.add(algo);
algo algo
} else { } else {
None None
+2 -2
View File
@@ -14,9 +14,9 @@ path = "lib.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
garage_model = { workspace = true, features = ["k2v"] } garage_model = { workspace = true, features = [ "k2v" ] }
garage_table.workspace = true garage_table.workspace = true
garage_util = { workspace = true, features = ["k2v"] } garage_util = { workspace = true, features = [ "k2v" ] }
garage_api_common.workspace = true garage_api_common.workspace = true
base64.workspace = true base64.workspace = true
+2 -2
View File
@@ -61,7 +61,7 @@ pub async fn handle_read_batch(
resps.push(resp?); resps.push(resp?);
} }
json_ok_response(&resps) Ok(json_ok_response(&resps)?)
} }
async fn handle_read_batch_query( async fn handle_read_batch_query(
@@ -155,7 +155,7 @@ pub async fn handle_delete_batch(
resps.push(resp?); resps.push(resp?);
} }
json_ok_response(&resps) Ok(json_ok_response(&resps)?)
} }
async fn handle_delete_batch_query( async fn handle_delete_batch_query(
+1 -1
View File
@@ -33,7 +33,7 @@ pub async fn handle_read_index(
let (partition_keys, more, next_start) = read_range( let (partition_keys, more, next_start) = read_range(
&garage.k2v.counter_table.table, &garage.k2v.counter_table.table,
bucket_id, &bucket_id,
&prefix, &prefix,
&start, &start,
&end, &end,
+4 -4
View File
@@ -57,23 +57,23 @@ pub fn handle_get_bucket_acl(ctx: ReqCtx) -> Result<Response<ResBody>, Error> {
if kp.allow_owner { if kp.allow_owner {
grants.push(s3_xml::Grant { grants.push(s3_xml::Grant {
grantee: create_grantee(key_p, &api_key), grantee: create_grantee(&key_p, &api_key),
permission: s3_xml::Value("FULL_CONTROL".to_string()), permission: s3_xml::Value("FULL_CONTROL".to_string()),
}); });
} else { } else {
if kp.allow_read { if kp.allow_read {
grants.push(s3_xml::Grant { grants.push(s3_xml::Grant {
grantee: create_grantee(key_p, &api_key), grantee: create_grantee(&key_p, &api_key),
permission: s3_xml::Value("READ".to_string()), permission: s3_xml::Value("READ".to_string()),
}); });
grants.push(s3_xml::Grant { grants.push(s3_xml::Grant {
grantee: create_grantee(key_p, &api_key), grantee: create_grantee(&key_p, &api_key),
permission: s3_xml::Value("READ_ACP".to_string()), permission: s3_xml::Value("READ_ACP".to_string()),
}); });
} }
if kp.allow_write { if kp.allow_write {
grants.push(s3_xml::Grant { grants.push(s3_xml::Grant {
grantee: create_grantee(key_p, &api_key), grantee: create_grantee(&key_p, &api_key),
permission: s3_xml::Value("WRITE".to_string()), permission: s3_xml::Value("WRITE".to_string()),
}); });
} }
+30 -41
View File
@@ -148,18 +148,14 @@ pub async fn handle_copy(
&& (was_multipart || checksum_algorithm != source_checksum_algorithm)); && (was_multipart || checksum_algorithm != source_checksum_algorithm));
let res = if !must_recopy { let res = if !must_recopy {
let dest_info = DestInfo {
key: dest_key,
uuid: dest_uuid,
object_meta: dest_object_meta,
encryption: dest_encryption,
};
// In most cases, we can just copy the metadata and link blocks of the // In most cases, we can just copy the metadata and link blocks of the
// old object from the new object. // old object from the new object.
handle_copy_metaonly( handle_copy_metaonly(
ctx, ctx,
dest_info, dest_key,
dest_uuid,
dest_object_meta,
dest_encryption,
source_version, source_version,
source_version_data, source_version_data,
source_version_meta, source_version_meta,
@@ -181,16 +177,12 @@ pub async fn handle_copy(
checksum_type: checksum_algorithm.map(|_| ChecksumType::FullObject), checksum_type: checksum_algorithm.map(|_| ChecksumType::FullObject),
..dest_object_meta ..dest_object_meta
}; };
let dest_info = DestInfo {
key: dest_key,
uuid: dest_uuid,
object_meta: dest_object_meta,
encryption: dest_encryption,
};
handle_copy_reencrypt( handle_copy_reencrypt(
ctx, ctx,
dest_info, dest_key,
dest_uuid,
dest_object_meta,
dest_encryption,
source_version, source_version,
source_version_data, source_version_data,
source_encryption, source_encryption,
@@ -217,16 +209,12 @@ pub async fn handle_copy(
Ok(resp.body(string_body(xml))?) Ok(resp.body(string_body(xml))?)
} }
struct DestInfo<'a> {
key: &'a str,
uuid: Uuid,
object_meta: ObjectVersionMetaInner,
encryption: EncryptionParams,
}
async fn handle_copy_metaonly( async fn handle_copy_metaonly(
ctx: ReqCtx, ctx: ReqCtx,
dest_info: DestInfo<'_>, dest_key: &str,
dest_uuid: Uuid,
dest_object_meta: ObjectVersionMetaInner,
dest_encryption: EncryptionParams,
source_version: &ObjectVersion, source_version: &ObjectVersion,
source_version_data: &ObjectVersionData, source_version_data: &ObjectVersionData,
source_version_meta: &ObjectVersionMeta, source_version_meta: &ObjectVersionMeta,
@@ -241,13 +229,13 @@ async fn handle_copy_metaonly(
let new_timestamp = now_msec(); let new_timestamp = now_msec();
let new_meta = ObjectVersionMeta { let new_meta = ObjectVersionMeta {
encryption: dest_info.encryption.encrypt_meta(dest_info.object_meta)?, encryption: dest_encryption.encrypt_meta(dest_object_meta)?,
size: source_version_meta.size, size: source_version_meta.size,
etag: source_version_meta.etag.clone(), etag: source_version_meta.etag.clone(),
}; };
let res = SaveStreamResult { let res = SaveStreamResult {
version_uuid: dest_info.uuid, version_uuid: dest_uuid,
version_timestamp: new_timestamp, version_timestamp: new_timestamp,
etag: new_meta.etag.clone(), etag: new_meta.etag.clone(),
}; };
@@ -259,7 +247,7 @@ async fn handle_copy_metaonly(
// bytes is either plaintext before&after or encrypted with the // bytes is either plaintext before&after or encrypted with the
// same keys, so it's ok to just copy it as is // same keys, so it's ok to just copy it as is
let dest_object_version = ObjectVersion { let dest_object_version = ObjectVersion {
uuid: dest_info.uuid, uuid: dest_uuid,
timestamp: new_timestamp, timestamp: new_timestamp,
state: ObjectVersionState::Complete(ObjectVersionData::Inline( state: ObjectVersionState::Complete(ObjectVersionData::Inline(
new_meta, new_meta,
@@ -268,7 +256,7 @@ async fn handle_copy_metaonly(
}; };
let dest_object = Object::new( let dest_object = Object::new(
dest_bucket_id, dest_bucket_id,
dest_info.key.to_string(), dest_key.to_string(),
vec![dest_object_version], vec![dest_object_version],
); );
garage.object_table.insert(&dest_object).await?; garage.object_table.insert(&dest_object).await?;
@@ -286,7 +274,7 @@ async fn handle_copy_metaonly(
// This holds a reference to the object in the Version table // This holds a reference to the object in the Version table
// so that it won't be deleted, e.g. by repair_versions. // so that it won't be deleted, e.g. by repair_versions.
let tmp_dest_object_version = ObjectVersion { let tmp_dest_object_version = ObjectVersion {
uuid: dest_info.uuid, uuid: dest_uuid,
timestamp: new_timestamp, timestamp: new_timestamp,
state: ObjectVersionState::Uploading { state: ObjectVersionState::Uploading {
encryption: new_meta.encryption.clone(), encryption: new_meta.encryption.clone(),
@@ -296,13 +284,11 @@ async fn handle_copy_metaonly(
}; };
let tmp_dest_object = Object::new( let tmp_dest_object = Object::new(
dest_bucket_id, dest_bucket_id,
dest_info.key.to_string(), dest_key.to_string(),
vec![tmp_dest_object_version], vec![tmp_dest_object_version],
); );
garage.object_table.insert(&tmp_dest_object).await?; garage.object_table.insert(&tmp_dest_object).await?;
let dest_uuid = dest_info.uuid;
// Write version in the version table. Even with empty block list, // Write version in the version table. Even with empty block list,
// this means that the BlockRef entries linked to this version cannot be // this means that the BlockRef entries linked to this version cannot be
// marked as deleted (they are marked as deleted only if the Version // marked as deleted (they are marked as deleted only if the Version
@@ -311,7 +297,7 @@ async fn handle_copy_metaonly(
dest_uuid, dest_uuid,
VersionBacklink::Object { VersionBacklink::Object {
bucket_id: dest_bucket_id, bucket_id: dest_bucket_id,
key: dest_info.key.to_string(), key: dest_key.to_string(),
}, },
false, false,
); );
@@ -343,7 +329,7 @@ async fn handle_copy_metaonly(
// with the stuff before, the block's reference counts could be decremented before // with the stuff before, the block's reference counts could be decremented before
// they are incremented again for the new version, leading to data being deleted. // they are incremented again for the new version, leading to data being deleted.
let dest_object_version = ObjectVersion { let dest_object_version = ObjectVersion {
uuid: dest_info.uuid, uuid: dest_uuid,
timestamp: new_timestamp, timestamp: new_timestamp,
state: ObjectVersionState::Complete(ObjectVersionData::FirstBlock( state: ObjectVersionState::Complete(ObjectVersionData::FirstBlock(
new_meta, new_meta,
@@ -352,7 +338,7 @@ async fn handle_copy_metaonly(
}; };
let dest_object = Object::new( let dest_object = Object::new(
dest_bucket_id, dest_bucket_id,
dest_info.key.to_string(), dest_key.to_string(),
vec![dest_object_version], vec![dest_object_version],
); );
garage.object_table.insert(&dest_object).await?; garage.object_table.insert(&dest_object).await?;
@@ -364,7 +350,10 @@ async fn handle_copy_metaonly(
async fn handle_copy_reencrypt( async fn handle_copy_reencrypt(
ctx: ReqCtx, ctx: ReqCtx,
dest_info: DestInfo<'_>, dest_key: &str,
dest_uuid: Uuid,
dest_object_meta: ObjectVersionMetaInner,
dest_encryption: EncryptionParams,
source_version: &ObjectVersion, source_version: &ObjectVersion,
source_version_data: &ObjectVersionData, source_version_data: &ObjectVersionData,
source_encryption: EncryptionParams, source_encryption: EncryptionParams,
@@ -382,11 +371,11 @@ async fn handle_copy_reencrypt(
save_stream( save_stream(
&ctx, &ctx,
dest_info.uuid, dest_uuid,
dest_info.object_meta, dest_object_meta,
dest_info.encryption, dest_encryption,
source_stream.map_err(|e| Error::from(GarageError::from(e))), source_stream.map_err(|e| Error::from(GarageError::from(e))),
&dest_info.key.to_string(), &dest_key.to_string(),
checksum_mode, checksum_mode,
) )
.await .await
@@ -556,7 +545,7 @@ pub async fn handle_upload_part_copy(
// Now, actually copy the blocks // Now, actually copy the blocks
let mut checksummer = Checksummer::init(&Default::default(), !dest_encryption.is_encrypted()) let mut checksummer = Checksummer::init(&Default::default(), !dest_encryption.is_encrypted())
.add_algorithm(dest_object_checksum_algorithm.map(|(algo, _)| algo)); .add(dest_object_checksum_algorithm.map(|(algo, _)| algo));
// First, create a stream that is able to read the source blocks // First, create a stream that is able to read the source blocks
// and extract the subrange if necessary. // and extract the subrange if necessary.
+6 -2
View File
@@ -29,7 +29,7 @@ async fn handle_delete_internal(ctx: &ReqCtx, key: &str) -> Result<(Uuid, Uuid),
.iter() .iter()
.rev() .rev()
.find(|v| !matches!(&v.state, ObjectVersionState::Aborted)) .find(|v| !matches!(&v.state, ObjectVersionState::Aborted))
.or_else(|| object.versions().iter().next_back()); .or_else(|| object.versions().iter().rev().next());
let deleted_version = match deleted_version { let deleted_version = match deleted_version {
Some(dv) => dv.uuid, Some(dv) => dv.uuid,
None => { None => {
@@ -139,7 +139,11 @@ fn parse_delete_objects_xml(xml: &roxmltree::Document) -> Option<DeleteRequest>
key: key_str.to_string(), key: key_str.to_string(),
}); });
} else if item.has_tag_name("Quiet") { } else if item.has_tag_name("Quiet") {
ret.quiet = item.text()? == "true"; if item.text()? == "true" {
ret.quiet = true;
} else {
ret.quiet = false;
}
} else { } else {
return None; return None;
} }
+18 -12
View File
@@ -94,7 +94,10 @@ impl EncryptionParams {
// data blocks are reused as-is. Since Garage v2, we are using // data blocks are reused as-is. Since Garage v2, we are using
// object-specific encryption keys, so we know that if both source // object-specific encryption keys, so we know that if both source
// and destination are encrypted, it can't be with the same key. // and destination are encrypted, it can't be with the same key.
matches!((a, b), (Self::Plaintext, Self::Plaintext)) match (a, b) {
(Self::Plaintext, Self::Plaintext) => true,
_ => false,
}
} }
pub fn new_from_headers( pub fn new_from_headers(
@@ -121,7 +124,7 @@ impl EncryptionParams {
pub fn add_response_headers(&self, resp: &mut http::response::Builder) { pub fn add_response_headers(&self, resp: &mut http::response::Builder) {
if let Self::SseC { client_key_md5, .. } = self { if let Self::SseC { client_key_md5, .. } = self {
let md5 = BASE64_STANDARD.encode(client_key_md5); let md5 = BASE64_STANDARD.encode(&client_key_md5);
resp.headers_mut().unwrap().insert( resp.headers_mut().unwrap().insert(
X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM, X_AMZ_SERVER_SIDE_ENCRYPTION_CUSTOMER_ALGORITHM,
@@ -193,7 +196,7 @@ impl EncryptionParams {
None None
}, },
}; };
let plaintext = enc.decrypt_blob(inner)?; let plaintext = enc.decrypt_blob(&inner)?;
let inner = ObjectVersionMetaInner::decode(&plaintext) let inner = ObjectVersionMetaInner::decode(&plaintext)
.ok_or_internal_error("Could not decode encrypted metadata")?; .ok_or_internal_error("Could not decode encrypted metadata")?;
Ok((enc, Cow::Owned(inner))) Ok((enc, Cow::Owned(inner)))
@@ -245,7 +248,7 @@ impl EncryptionParams {
// So we just put some random bytes. // So we just put some random bytes.
let mut random = [0u8; 16]; let mut random = [0u8; 16];
OsRng.fill_bytes(&mut random); OsRng.fill_bytes(&mut random);
hex::encode(random) hex::encode(&random)
} }
} }
} }
@@ -260,12 +263,12 @@ impl EncryptionParams {
Self::SseC { Self::SseC {
object_key: Some(oek), object_key: Some(oek),
.. ..
} => Some(Aes256Gcm::new(oek)), } => Some(Aes256Gcm::new(&oek)),
Self::SseC { Self::SseC {
client_key, client_key,
object_key: None, object_key: None,
.. ..
} => Some(Aes256Gcm::new(client_key)), } => Some(Aes256Gcm::new(&client_key)),
Self::Plaintext => None, Self::Plaintext => None,
} }
} }
@@ -430,7 +433,7 @@ fn parse_request_headers(
let key_b64 = let key_b64 =
key.ok_or_bad_request("Missing server-side-encryption-customer-key header")?; key.ok_or_bad_request("Missing server-side-encryption-customer-key header")?;
let key_bytes: [u8; 32] = BASE64_STANDARD let key_bytes: [u8; 32] = BASE64_STANDARD
.decode(key_b64) .decode(&key_b64)
.ok_or_bad_request( .ok_or_bad_request(
"Invalid server-side-encryption-customer-key header: invalid base64", "Invalid server-side-encryption-customer-key header: invalid base64",
)? )?
@@ -442,7 +445,7 @@ fn parse_request_headers(
let md5_b64 = let md5_b64 =
md5.ok_or_bad_request("Missing server-side-encryption-customer-key-md5 header")?; md5.ok_or_bad_request("Missing server-side-encryption-customer-key-md5 header")?;
let md5_bytes = BASE64_STANDARD.decode(md5_b64).ok_or_bad_request( let md5_bytes = BASE64_STANDARD.decode(&md5_b64).ok_or_bad_request(
"Invalid server-side-encryption-customer-key-md5 header: invalid bass64", "Invalid server-side-encryption-customer-key-md5 header: invalid bass64",
)?; )?;
@@ -508,7 +511,6 @@ struct DecryptStream {
state: DecryptStreamState, state: DecryptStreamState,
} }
#[expect(clippy::large_enum_variant)]
enum DecryptStreamState { enum DecryptStreamState {
Starting, Starting,
Running(DecryptorLE31<Aes256Gcm>), Running(DecryptorLE31<Aes256Gcm>),
@@ -545,7 +547,7 @@ impl Stream for DecryptStream {
let nonce_size = StreamNonceSize::to_usize(); let nonce_size = StreamNonceSize::to_usize();
if let Some(nonce) = this.buf.take_exact(nonce_size) { if let Some(nonce) = this.buf.take_exact(nonce_size) {
let nonce = Nonce::from_slice(nonce.as_ref()); let nonce = Nonce::from_slice(nonce.as_ref());
*this.state = DecryptStreamState::Running(DecryptorLE31::new(this.key, nonce)); *this.state = DecryptStreamState::Running(DecryptorLE31::new(&this.key, nonce));
break; break;
} }
@@ -585,7 +587,8 @@ impl Stream for DecryptStream {
if matches!(this.state, DecryptStreamState::Done) { if matches!(this.state, DecryptStreamState::Done) {
if !this.buf.is_empty() { if !this.buf.is_empty() {
return Poll::Ready(Some(Err(std::io::Error::other( return Poll::Ready(Some(Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Decrypt: unexpected bytes after last encrypted chunk", "Decrypt: unexpected bytes after last encrypted chunk",
)))); ))));
} }
@@ -619,7 +622,10 @@ impl Stream for DecryptStream {
match res { match res {
Ok(bytes) if bytes.is_empty() => Poll::Ready(None), Ok(bytes) if bytes.is_empty() => Poll::Ready(None),
Ok(bytes) => Poll::Ready(Some(Ok(bytes.into()))), Ok(bytes) => Poll::Ready(Some(Ok(bytes.into()))),
Err(_) => Poll::Ready(Some(Err(std::io::Error::other("Decryption failed")))), Err(_) => Poll::Ready(Some(Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Decryption failed",
)))),
} }
} }
} }
+91 -88
View File
@@ -93,7 +93,7 @@ fn object_headers(
/// Override headers according to specific query parameters, see /// Override headers according to specific query parameters, see
/// section "Overriding response header values through the request" in /// section "Overriding response header values through the request" in
/// <https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html> /// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
fn getobject_override_headers( fn getobject_override_headers(
overrides: GetObjectOverrides, overrides: GetObjectOverrides,
resp: &mut http::response::Builder, resp: &mut http::response::Builder,
@@ -124,7 +124,7 @@ fn handle_http_precondition(
) -> Result<Option<Response<ResBody>>, Error> { ) -> Result<Option<Response<ResBody>>, Error> {
let precondition_headers = PreconditionHeaders::parse(req)?; let precondition_headers = PreconditionHeaders::parse(req)?;
if let Some(status_code) = precondition_headers.check(version, &version_meta.etag)? { if let Some(status_code) = precondition_headers.check(&version, &version_meta.etag)? {
Ok(Some( Ok(Some(
Response::builder() Response::builder()
.status(status_code) .status(status_code)
@@ -189,12 +189,12 @@ pub async fn handle_head_without_ctx(
OekDerivationInfo::for_object(&object, object_version), OekDerivationInfo::for_object(&object, object_version),
)?; )?;
let checksum_mode = checksum_mode(req); let checksum_mode = checksum_mode(&req);
if let Some(part_number) = part_number { if let Some(pn) = part_number {
match version_data { match version_data {
ObjectVersionData::Inline(_, _) => { ObjectVersionData::Inline(_, _) => {
if part_number != 1 { if pn != 1 {
return Err(Error::InvalidPart); return Err(Error::InvalidPart);
} }
let bytes_len = version_meta.size; let bytes_len = version_meta.size;
@@ -223,7 +223,7 @@ pub async fn handle_head_without_ctx(
check_version_not_deleted(&version)?; check_version_not_deleted(&version)?;
let (part_offset, part_end) = let (part_offset, part_end) =
calculate_part_bounds(&version, part_number).ok_or(Error::InvalidPart)?; calculate_part_bounds(&version, pn).ok_or(Error::InvalidPart)?;
Ok(object_headers( Ok(object_headers(
object_version, object_version,
@@ -316,16 +316,7 @@ pub async fn handle_get_without_ctx(
OekDerivationInfo::for_object(&object, last_v), OekDerivationInfo::for_object(&object, last_v),
)?; )?;
let checksum_mode = checksum_mode(req); let checksum_mode = checksum_mode(&req);
let handle_get_info = HandleGetInfo {
garage,
version: last_v,
version_data: last_v_data,
version_meta: last_v_meta,
encryption: enc,
meta_inner: &headers,
};
match (part_number, parse_range_header(req, last_v_meta.size)?) { match (part_number, parse_range_header(req, last_v_meta.size)?) {
(Some(_), Some(_)) => Err(Error::bad_request( (Some(_), Some(_)) => Err(Error::bad_request(
@@ -333,7 +324,12 @@ pub async fn handle_get_without_ctx(
)), )),
(Some(pn), None) => { (Some(pn), None) => {
handle_get_part( handle_get_part(
handle_get_info, garage,
last_v,
last_v_data,
last_v_meta,
enc,
&headers,
pn, pn,
ChecksumMode { ChecksumMode {
// TODO: for multipart uploads, checksums of each part should be stored // TODO: for multipart uploads, checksums of each part should be stored
@@ -346,7 +342,12 @@ pub async fn handle_get_without_ctx(
} }
(None, Some(range)) => { (None, Some(range)) => {
handle_get_range( handle_get_range(
handle_get_info, garage,
last_v,
last_v_data,
last_v_meta,
enc,
&headers,
range.start, range.start,
range.start + range.length, range.start + range.length,
ChecksumMode { ChecksumMode {
@@ -358,14 +359,26 @@ pub async fn handle_get_without_ctx(
) )
.await .await
} }
(None, None) => handle_get_full(handle_get_info, overrides, checksum_mode).await, (None, None) => {
handle_get_full(
garage,
last_v,
last_v_data,
last_v_meta,
enc,
&headers,
overrides,
checksum_mode,
)
.await
}
} }
} }
pub(crate) fn check_version_not_deleted(version: &Version) -> Result<(), Error> { pub(crate) fn check_version_not_deleted(version: &Version) -> Result<(), Error> {
if version.deleted.get() { if version.deleted.get() {
// the version was deleted between when the object_table was consulted // the version was deleted between when the object_table was consulted
// and now, this could mean the object was deleted, or overridden. // and now, this could mean the object was deleted, or overriden.
// Rather than say the key doesn't exist, return a transient error // Rather than say the key doesn't exist, return a transient error
// to signal the client to try again. // to signal the client to try again.
return Err(CommonError::InternalError(UtilError::Message( return Err(CommonError::InternalError(UtilError::Message(
@@ -377,37 +390,28 @@ pub(crate) fn check_version_not_deleted(version: &Version) -> Result<(), Error>
Ok(()) Ok(())
} }
struct HandleGetInfo<'a> {
garage: Arc<Garage>,
version: &'a ObjectVersion,
version_data: &'a ObjectVersionData,
version_meta: &'a ObjectVersionMeta,
encryption: EncryptionParams,
meta_inner: &'a ObjectVersionMetaInner,
}
async fn handle_get_full( async fn handle_get_full(
info: HandleGetInfo<'_>, garage: Arc<Garage>,
version: &ObjectVersion,
version_data: &ObjectVersionData,
version_meta: &ObjectVersionMeta,
encryption: EncryptionParams,
meta_inner: &ObjectVersionMetaInner,
overrides: GetObjectOverrides, overrides: GetObjectOverrides,
checksum_mode: ChecksumMode, checksum_mode: ChecksumMode,
) -> Result<Response<ResBody>, Error> { ) -> Result<Response<ResBody>, Error> {
let mut resp_builder = object_headers( let mut resp_builder = object_headers(
info.version, version,
info.version_meta, version_meta,
info.meta_inner, &meta_inner,
info.encryption, encryption,
checksum_mode, checksum_mode,
) )
.header(CONTENT_LENGTH, format!("{}", info.version_meta.size)) .header(CONTENT_LENGTH, format!("{}", version_meta.size))
.status(StatusCode::OK); .status(StatusCode::OK);
getobject_override_headers(overrides, &mut resp_builder)?; getobject_override_headers(overrides, &mut resp_builder)?;
let stream = full_object_byte_stream( let stream = full_object_byte_stream(garage, version, version_data, encryption);
info.garage,
info.version,
info.version_data,
info.encryption,
);
Ok(resp_builder.body(response_body_from_stream(stream))?) Ok(resp_builder.body(response_body_from_stream(stream))?)
} }
@@ -487,7 +491,12 @@ pub fn full_object_byte_stream(
} }
async fn handle_get_range( async fn handle_get_range(
info: HandleGetInfo<'_>, garage: Arc<Garage>,
version: &ObjectVersion,
version_data: &ObjectVersionData,
version_meta: &ObjectVersionMeta,
encryption: EncryptionParams,
meta_inner: &ObjectVersionMetaInner,
begin: u64, begin: u64,
end: u64, end: u64,
checksum_mode: ChecksumMode, checksum_mode: ChecksumMode,
@@ -495,24 +504,18 @@ async fn handle_get_range(
// Here we do not use getobject_override_headers because we don't // Here we do not use getobject_override_headers because we don't
// want to add any overridden headers (those should not be added // want to add any overridden headers (those should not be added
// when returning PARTIAL_CONTENT) // when returning PARTIAL_CONTENT)
let resp_builder = object_headers( let resp_builder = object_headers(version, version_meta, meta_inner, encryption, checksum_mode)
info.version, .header(CONTENT_LENGTH, format!("{}", end - begin))
info.version_meta, .header(
info.meta_inner, CONTENT_RANGE,
info.encryption, format!("bytes {}-{}/{}", begin, end - 1, version_meta.size),
checksum_mode, )
) .status(StatusCode::PARTIAL_CONTENT);
.header(CONTENT_LENGTH, format!("{}", end - begin))
.header(
CONTENT_RANGE,
format!("bytes {}-{}/{}", begin, end - 1, info.version_meta.size),
)
.status(StatusCode::PARTIAL_CONTENT);
match &info.version_data { match &version_data {
ObjectVersionData::DeleteMarker => unreachable!(), ObjectVersionData::DeleteMarker => unreachable!(),
ObjectVersionData::Inline(_meta, bytes) => { ObjectVersionData::Inline(_meta, bytes) => {
let bytes = info.encryption.decrypt_blob(bytes)?; let bytes = encryption.decrypt_blob(&bytes)?;
if end as usize <= bytes.len() { if end as usize <= bytes.len() {
let body = bytes_body(bytes[begin as usize..end as usize].to_vec().into()); let body = bytes_body(bytes[begin as usize..end as usize].to_vec().into());
Ok(resp_builder.body(body)?) Ok(resp_builder.body(body)?)
@@ -523,47 +526,46 @@ async fn handle_get_range(
} }
} }
ObjectVersionData::FirstBlock(_meta, _first_block_hash) => { ObjectVersionData::FirstBlock(_meta, _first_block_hash) => {
let version = info let version = garage
.garage
.version_table .version_table
.get(&info.version.uuid, &EmptyKey) .get(&version.uuid, &EmptyKey)
.await? .await?
.ok_or(Error::NoSuchKey)?; .ok_or(Error::NoSuchKey)?;
check_version_not_deleted(&version)?; check_version_not_deleted(&version)?;
let body = body_from_blocks_range( let body =
info.garage, body_from_blocks_range(garage, encryption, version.blocks.items(), begin, end);
info.encryption,
version.blocks.items(),
begin,
end,
);
Ok(resp_builder.body(body)?) Ok(resp_builder.body(body)?)
} }
} }
} }
async fn handle_get_part( async fn handle_get_part(
info: HandleGetInfo<'_>, garage: Arc<Garage>,
object_version: &ObjectVersion,
version_data: &ObjectVersionData,
version_meta: &ObjectVersionMeta,
encryption: EncryptionParams,
meta_inner: &ObjectVersionMetaInner,
part_number: u64, part_number: u64,
checksum_mode: ChecksumMode, checksum_mode: ChecksumMode,
) -> Result<Response<ResBody>, Error> { ) -> Result<Response<ResBody>, Error> {
// Same as for get_range, no getobject_override_headers // Same as for get_range, no getobject_override_headers
let resp_builder = object_headers( let resp_builder = object_headers(
info.version, object_version,
info.version_meta, version_meta,
info.meta_inner, meta_inner,
info.encryption, encryption,
checksum_mode, checksum_mode,
) )
.status(StatusCode::PARTIAL_CONTENT); .status(StatusCode::PARTIAL_CONTENT);
match info.version_data { match version_data {
ObjectVersionData::Inline(_, bytes) => { ObjectVersionData::Inline(_, bytes) => {
if part_number != 1 { if part_number != 1 {
return Err(Error::InvalidPart); return Err(Error::InvalidPart);
} }
let bytes = info.encryption.decrypt_blob(bytes)?; let bytes = encryption.decrypt_blob(&bytes)?;
assert_eq!(bytes.len() as u64, info.version_meta.size); assert_eq!(bytes.len() as u64, version_meta.size);
Ok(resp_builder Ok(resp_builder
.header(CONTENT_LENGTH, format!("{}", bytes.len())) .header(CONTENT_LENGTH, format!("{}", bytes.len()))
.header( .header(
@@ -574,10 +576,9 @@ async fn handle_get_part(
.body(bytes_body(bytes.into_owned().into()))?) .body(bytes_body(bytes.into_owned().into()))?)
} }
ObjectVersionData::FirstBlock(_, _) => { ObjectVersionData::FirstBlock(_, _) => {
let version = info let version = garage
.garage
.version_table .version_table
.get(&info.version.uuid, &EmptyKey) .get(&object_version.uuid, &EmptyKey)
.await? .await?
.ok_or(Error::NoSuchKey)?; .ok_or(Error::NoSuchKey)?;
@@ -586,19 +587,14 @@ async fn handle_get_part(
let (begin, end) = let (begin, end) =
calculate_part_bounds(&version, part_number).ok_or(Error::InvalidPart)?; calculate_part_bounds(&version, part_number).ok_or(Error::InvalidPart)?;
let body = body_from_blocks_range( let body =
info.garage, body_from_blocks_range(garage, encryption, version.blocks.items(), begin, end);
info.encryption,
version.blocks.items(),
begin,
end,
);
Ok(resp_builder Ok(resp_builder
.header(CONTENT_LENGTH, format!("{}", end - begin)) .header(CONTENT_LENGTH, format!("{}", end - begin))
.header( .header(
CONTENT_RANGE, CONTENT_RANGE,
format!("bytes {}-{}/{}", begin, end - 1, info.version_meta.size), format!("bytes {}-{}/{}", begin, end - 1, version_meta.size),
) )
.header(X_AMZ_MP_PARTS_COUNT, format!("{}", version.n_parts()?)) .header(X_AMZ_MP_PARTS_COUNT, format!("{}", version.n_parts()?))
.body(body)?) .body(body)?)
@@ -712,7 +708,11 @@ fn body_from_blocks_range(
Some(None) Some(None)
} else { } else {
// The chunk has an intersection with the requested range // The chunk has an intersection with the requested range
let start_in_chunk = begin.saturating_sub(*chunk_offset); let start_in_chunk = if *chunk_offset > begin {
0
} else {
begin - *chunk_offset
};
let end_in_chunk = if *chunk_offset + chunk_len < end { let end_in_chunk = if *chunk_offset + chunk_len < end {
chunk_len chunk_len
} else { } else {
@@ -773,7 +773,10 @@ fn error_stream_item<E: std::fmt::Display>(e: E) -> ByteStream {
} }
fn std_error_from_read_error<E: std::fmt::Display>(e: E) -> std::io::Error { fn std_error_from_read_error<E: std::fmt::Display>(e: E) -> std::io::Error {
std::io::Error::other(format!("Error while reading object data: {}", e)) std::io::Error::new(
std::io::ErrorKind::Other,
format!("Error while reading object data: {}", e),
)
} }
// ---- // ----
+14 -11
View File
@@ -324,31 +324,31 @@ pub async fn handle_list_parts(
size: s3_xml::IntValue(part.size as i64), size: s3_xml::IntValue(part.size as i64),
checksum_crc32: match &checksum { checksum_crc32: match &checksum {
Some(ChecksumValue::Crc32(x)) => { Some(ChecksumValue::Crc32(x)) => {
Some(s3_xml::Value(BASE64_STANDARD.encode(x))) Some(s3_xml::Value(BASE64_STANDARD.encode(&x)))
} }
_ => None, _ => None,
}, },
checksum_crc32c: match &checksum { checksum_crc32c: match &checksum {
Some(ChecksumValue::Crc32c(x)) => { Some(ChecksumValue::Crc32c(x)) => {
Some(s3_xml::Value(BASE64_STANDARD.encode(x))) Some(s3_xml::Value(BASE64_STANDARD.encode(&x)))
} }
_ => None, _ => None,
}, },
checksum_crc64nvme: match &checksum { checksum_crc64nvme: match &checksum {
Some(ChecksumValue::Crc64Nvme(x)) => { Some(ChecksumValue::Crc64Nvme(x)) => {
Some(s3_xml::Value(BASE64_STANDARD.encode(x))) Some(s3_xml::Value(BASE64_STANDARD.encode(&x)))
} }
_ => None, _ => None,
}, },
checksum_sha1: match &checksum { checksum_sha1: match &checksum {
Some(ChecksumValue::Sha1(x)) => { Some(ChecksumValue::Sha1(x)) => {
Some(s3_xml::Value(BASE64_STANDARD.encode(x))) Some(s3_xml::Value(BASE64_STANDARD.encode(&x)))
} }
_ => None, _ => None,
}, },
checksum_sha256: match &checksum { checksum_sha256: match &checksum {
Some(ChecksumValue::Sha256(x)) => { Some(ChecksumValue::Sha256(x)) => {
Some(s3_xml::Value(BASE64_STANDARD.encode(x))) Some(s3_xml::Value(BASE64_STANDARD.encode(&x)))
} }
_ => None, _ => None,
}, },
@@ -598,7 +598,7 @@ impl ListObjectsQuery {
Some("[") => Ok(RangeBegin::IncludingKey { Some("[") => Ok(RangeBegin::IncludingKey {
key: String::from_utf8( key: String::from_utf8(
BASE64_STANDARD BASE64_STANDARD
.decode(&token.as_bytes()[1..]) .decode(token[1..].as_bytes())
.ok_or_bad_request("Invalid continuation token")?, .ok_or_bad_request("Invalid continuation token")?,
)?, )?,
fallback_key: None, fallback_key: None,
@@ -606,7 +606,7 @@ impl ListObjectsQuery {
Some("]") => Ok(RangeBegin::AfterKey { Some("]") => Ok(RangeBegin::AfterKey {
key: String::from_utf8( key: String::from_utf8(
BASE64_STANDARD BASE64_STANDARD
.decode(&token.as_bytes()[1..]) .decode(token[1..].as_bytes())
.ok_or_bad_request("Invalid continuation token")?, .ok_or_bad_request("Invalid continuation token")?,
)?, )?,
}), }),
@@ -725,7 +725,10 @@ impl<K: std::cmp::Ord, V> Accumulator<K, V> {
let object = objects.peek().expect("This iterator can not be empty as it is checked earlier in the code. This is a logic bug, please report it."); let object = objects.peek().expect("This iterator can not be empty as it is checked earlier in the code. This is a logic bug, please report it.");
// Check if this is a common prefix (requires a passed delimiter and its value in the key) // Check if this is a common prefix (requires a passed delimiter and its value in the key)
let pfx = common_prefix(object, query)?; let pfx = match common_prefix(object, query) {
Some(p) => p,
None => return None,
};
assert!(pfx.starts_with(&query.prefix)); assert!(pfx.starts_with(&query.prefix));
// Try to register this prefix // Try to register this prefix
@@ -1014,12 +1017,12 @@ mod tests {
query.common.prefix = "a/".to_string(); query.common.prefix = "a/".to_string();
assert_eq!( assert_eq!(
common_prefix(objs.first().unwrap(), &query.common), common_prefix(objs.get(0).unwrap(), &query.common),
Some("a/b/") Some("a/b/")
); );
query.common.prefix = "a/b/".to_string(); query.common.prefix = "a/b/".to_string();
assert_eq!(common_prefix(objs.first().unwrap(), &query.common), None); assert_eq!(common_prefix(objs.get(0).unwrap(), &query.common), None);
} }
#[test] #[test]
@@ -1040,7 +1043,7 @@ mod tests {
#[test] #[test]
fn test_extract_upload() { fn test_extract_upload() {
let objs = [ let objs = vec![
Object::new( Object::new(
bucket(), bucket(),
"b".to_string(), "b".to_string(),
+18 -14
View File
@@ -43,7 +43,7 @@ pub async fn handle_create_multipart_upload(
bucket_name, bucket_name,
.. ..
} = &ctx; } = &ctx;
let existing_object = garage.object_table.get(bucket_id, key).await?; let existing_object = garage.object_table.get(&bucket_id, &key).await?;
let upload_id = gen_uuid(); let upload_id = gen_uuid();
let timestamp = next_timestamp(existing_object.as_ref()); let timestamp = next_timestamp(existing_object.as_ref());
@@ -57,12 +57,12 @@ pub async fn handle_create_multipart_upload(
// Determine whether object should be encrypted, and if so the key // Determine whether object should be encrypted, and if so the key
let encryption = EncryptionParams::new_from_headers( let encryption = EncryptionParams::new_from_headers(
garage, &garage,
req.headers(), req.headers(),
OekDerivationInfo { OekDerivationInfo {
bucket_id: *bucket_id, bucket_id: *bucket_id,
version_id: upload_id, version_id: upload_id,
object_key: key, object_key: &key,
}, },
)?; )?;
let object_encryption = encryption.encrypt_meta(meta)?; let object_encryption = encryption.encrypt_meta(meta)?;
@@ -157,8 +157,12 @@ pub async fn handle_put_part(
} => (encryption, checksum_algorithm), } => (encryption, checksum_algorithm),
_ => unreachable!(), _ => unreachable!(),
}; };
let (encryption, _) = let (encryption, _) = EncryptionParams::check_decrypt(
EncryptionParams::check_decrypt(garage, &req_head.headers, &object_encryption, oek_params)?; &garage,
&req_head.headers,
&object_encryption,
oek_params,
)?;
// Check object is valid and part can be accepted // Check object is valid and part can be accepted
let first_block = first_block.ok_or_bad_request("Empty body")?; let first_block = first_block.ok_or_bad_request("Empty body")?;
@@ -455,7 +459,7 @@ pub async fn handle_complete_multipart_upload(
None => object_encryption, None => object_encryption,
Some(_) => { Some(_) => {
let (encryption, meta) = EncryptionParams::check_decrypt( let (encryption, meta) = EncryptionParams::check_decrypt(
garage, &garage,
&req_head.headers, &req_head.headers,
&object_encryption, &object_encryption,
oek_params, oek_params,
@@ -499,23 +503,23 @@ pub async fn handle_complete_multipart_upload(
key: s3_xml::Value(key), key: s3_xml::Value(key),
etag: s3_xml::Value(format!("\"{}\"", etag)), etag: s3_xml::Value(format!("\"{}\"", etag)),
checksum_crc32: match &checksum_extra { checksum_crc32: match &checksum_extra {
Some(ChecksumValue::Crc32(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(x))), Some(ChecksumValue::Crc32(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(&x))),
_ => None, _ => None,
}, },
checksum_crc32c: match &checksum_extra { checksum_crc32c: match &checksum_extra {
Some(ChecksumValue::Crc32c(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(x))), Some(ChecksumValue::Crc32c(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(&x))),
_ => None, _ => None,
}, },
checksum_crc64nvme: match &checksum_extra { checksum_crc64nvme: match &checksum_extra {
Some(ChecksumValue::Crc64Nvme(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(x))), Some(ChecksumValue::Crc64Nvme(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(&x))),
_ => None, _ => None,
}, },
checksum_sha1: match &checksum_extra { checksum_sha1: match &checksum_extra {
Some(ChecksumValue::Sha1(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(x))), Some(ChecksumValue::Sha1(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(&x))),
_ => None, _ => None,
}, },
checksum_sha256: match &checksum_extra { checksum_sha256: match &checksum_extra {
Some(ChecksumValue::Sha256(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(x))), Some(ChecksumValue::Sha256(x)) => Some(s3_xml::Value(BASE64_STANDARD.encode(&x))),
_ => None, _ => None,
}, },
checksum_type: match checksum_algorithm { checksum_type: match checksum_algorithm {
@@ -731,7 +735,7 @@ impl MultipartChecksummer {
part_len: u64, part_len: u64,
) -> Result<(), Error> { ) -> Result<(), Error> {
self.md5 self.md5
.update(&hex::decode(etag).ok_or_message("invalid etag hex")?); .update(&hex::decode(&etag).ok_or_message("invalid etag hex")?);
if let Some(extra) = &mut self.extra { if let Some(extra) = &mut self.extra {
extra.update(checksum, part_len)?; extra.update(checksum, part_len)?;
} }
@@ -811,10 +815,10 @@ impl MultipartExtraChecksummer {
} }
}, },
(Self::CompositeSha1(sha1), Some(ChecksumValue::Sha1(x))) => { (Self::CompositeSha1(sha1), Some(ChecksumValue::Sha1(x))) => {
sha1.update(x); sha1.update(&x);
} }
(Self::CompositeSha256(sha256), Some(ChecksumValue::Sha256(x))) => { (Self::CompositeSha256(sha256), Some(ChecksumValue::Sha256(x))) => {
sha256.update(x); sha256.update(&x);
} }
_ => { _ => {
return Err(Error::internal_error(format!( return Err(Error::internal_error(format!(
+7 -5
View File
@@ -505,15 +505,15 @@ mod tests {
let mut conditions = policy_2.into_conditions().unwrap(); let mut conditions = policy_2.into_conditions().unwrap();
assert_eq!( assert_eq!(
conditions.params.remove("acl"), conditions.params.remove(&"acl".to_string()),
Some(vec![Operation::Equal("public-read".into())]) Some(vec![Operation::Equal("public-read".into())])
); );
assert_eq!( assert_eq!(
conditions.params.remove("bucket"), conditions.params.remove(&"bucket".to_string()),
Some(vec![Operation::Equal("johnsmith".into())]) Some(vec![Operation::Equal("johnsmith".into())])
); );
assert_eq!( assert_eq!(
conditions.params.remove("key"), conditions.params.remove(&"key".to_string()),
Some(vec![Operation::StartsWith("user/eric/".into())]) Some(vec![Operation::StartsWith("user/eric/".into())])
); );
assert!(conditions.params.is_empty()); assert!(conditions.params.is_empty());
@@ -536,7 +536,7 @@ mod tests {
let mut conditions = policy_2.into_conditions().unwrap(); let mut conditions = policy_2.into_conditions().unwrap();
assert_eq!( assert_eq!(
conditions.params.remove("acl"), conditions.params.remove(&"acl".to_string()),
Some(vec![Operation::Equal("public-read".into())]) Some(vec![Operation::Equal("public-read".into())])
); );
assert_eq!( assert_eq!(
@@ -544,7 +544,9 @@ mod tests {
vec![Operation::StartsWith("image/".into())] vec![Operation::StartsWith("image/".into())]
); );
assert_eq!( assert_eq!(
conditions.params.remove("success_action_redirect"), conditions
.params
.remove(&"success_action_redirect".to_string()),
Some(vec![Operation::StartsWith("".into())]) Some(vec![Operation::StartsWith("".into())])
); );
assert!(conditions.params.is_empty()); assert!(conditions.params.is_empty());
+3 -4
View File
@@ -91,7 +91,7 @@ pub async fn handle_put(
OekDerivationInfo { OekDerivationInfo {
bucket_id: ctx.bucket_id, bucket_id: ctx.bucket_id,
version_id: version_uuid, version_id: version_uuid,
object_key: key, object_key: &key,
}, },
)?; )?;
@@ -158,7 +158,7 @@ pub(crate) async fn save_stream<S: Stream<Item = Result<Bytes, Error>> + Unpin>(
let mut checksummer = match &checksum_mode { let mut checksummer = match &checksum_mode {
ChecksumMode::Verify(expected) => Checksummer::init(expected, !encryption.is_encrypted()), ChecksumMode::Verify(expected) => Checksummer::init(expected, !encryption.is_encrypted()),
ChecksumMode::Calculate(algo) => { ChecksumMode::Calculate(algo) => {
Checksummer::init(&Default::default(), !encryption.is_encrypted()).add_algorithm(*algo) Checksummer::init(&Default::default(), !encryption.is_encrypted()).add(*algo)
} }
ChecksumMode::VerifyFrom { .. } => { ChecksumMode::VerifyFrom { .. } => {
// Checksums are calculated by the garage_api_common::signature module // Checksums are calculated by the garage_api_common::signature module
@@ -554,7 +554,6 @@ pub(crate) async fn read_and_put_blocks<S: Stream<Item = Result<Bytes, Error>> +
Ok((total_size, checksums, first_block_hash)) Ok((total_size, checksums, first_block_hash))
} }
#[expect(clippy::too_many_arguments)]
async fn put_block_and_meta( async fn put_block_and_meta(
ctx: &ReqCtx, ctx: &ReqCtx,
version: &Version, version: &Version,
@@ -669,7 +668,7 @@ pub(crate) fn extract_metadata_headers(
let mut ret = Vec::new(); let mut ret = Vec::new();
// Preserve standard headers // Preserve standard headers
let standard_header = [ let standard_header = vec![
hyper::header::CONTENT_TYPE, hyper::header::CONTENT_TYPE,
hyper::header::CACHE_CONTROL, hyper::header::CACHE_CONTROL,
hyper::header::CONTENT_DISPOSITION, hyper::header::CONTENT_DISPOSITION,
+3 -3
View File
@@ -355,7 +355,7 @@ impl Endpoint {
if let Some(x_id) = query.x_id.take() { if let Some(x_id) = query.x_id.take() {
if x_id != res.name() { if x_id != res.name() {
// I think AWS ignores the x-id parameter. // I think AWS ignores the x-id parameter.
// Let's make this at least be a warning to help debugging. // Let's make this at least be a warnin to help debugging.
warn!( warn!(
"x-id ({}) does not match parsed endpoint ({})", "x-id ({}) does not match parsed endpoint ({})",
x_id, x_id,
@@ -949,7 +949,7 @@ mod tests {
GET "/?uploads&delimiter=/&prefix=photos/2006/" => ListMultipartUploads GET "/?uploads&delimiter=/&prefix=photos/2006/" => ListMultipartUploads
GET "/?uploads&delimiter=D&encoding-type=EncodingType&key-marker=KeyMarker&max-uploads=1&prefix=Prefix&upload-id-marker=UploadIdMarker" => ListMultipartUploads GET "/?uploads&delimiter=D&encoding-type=EncodingType&key-marker=KeyMarker&max-uploads=1&prefix=Prefix&upload-id-marker=UploadIdMarker" => ListMultipartUploads
GET "/" => ListObjects GET "/" => ListObjects
GET "/?prefix=N&marker=Need&max-keys=40" => ListObjects GET "/?prefix=N&marker=Ned&max-keys=40" => ListObjects
GET "/?delimiter=/" => ListObjects GET "/?delimiter=/" => ListObjects
GET "/?prefix=photos/2006/&delimiter=/" => ListObjects GET "/?prefix=photos/2006/&delimiter=/" => ListObjects
@@ -1011,7 +1011,7 @@ mod tests {
// no bucket, won't work with the rest of the test suite // no bucket, won't work with the rest of the test suite
assert!(matches!( assert!(matches!(
parse("GET", "/", None, None).0, parse("GET", "/", None, None).0,
Endpoint::ListBuckets Endpoint::ListBuckets { .. }
)); ));
assert!(matches!( assert!(matches!(
parse("GET", "/", None, None).0.authorization_type(), parse("GET", "/", None, None).0.authorization_type(),
+3 -3
View File
@@ -213,7 +213,7 @@ impl WebsiteConfiguration {
} }
if self.routing_rules.rules.len() > 1000 { if self.routing_rules.rules.len() > 1000 {
// we will do linear scans, best to avoid overly long configuration. The // we will do linear scans, best to avoid overly long configuration. The
// limit was chosen arbitrarily // limit was choosen arbitrarily
return Err(Error::bad_request( return Err(Error::bad_request(
"Bad XML: RoutingRules can't have more than 1000 child elements", "Bad XML: RoutingRules can't have more than 1000 child elements",
)); ));
@@ -225,7 +225,7 @@ impl WebsiteConfiguration {
pub fn into_garage_website_config(self) -> Result<WebsiteConfig, Error> { pub fn into_garage_website_config(self) -> Result<WebsiteConfig, Error> {
if self.redirect_all_requests_to.is_some() { if self.redirect_all_requests_to.is_some() {
Err(Error::NotImplemented( Err(Error::NotImplemented(
"RedirectAllRequestsTo is not currently implemented in Garage, however its effect can be emulated using a single unconditional RoutingRule.".into(), "RedirectAllRequestsTo is not currently implemented in Garage, however its effect can be emulated using a single inconditional RoutingRule.".into(),
)) ))
} else { } else {
Ok(WebsiteConfig { Ok(WebsiteConfig {
@@ -251,7 +251,7 @@ impl WebsiteConfiguration {
hostname: rule.redirect.hostname.map(|h| h.0), hostname: rule.redirect.hostname.map(|h| h.0),
protocol: rule.redirect.protocol.map(|p| p.0), protocol: rule.redirect.protocol.map(|p| p.0),
// aws default to 301, which i find punitive in case of // aws default to 301, which i find punitive in case of
// misconfiguration (can be permanently cached on the // missconfiguration (can be permanently cached on the
// user agent) // user agent)
http_redirect_code: rule http_redirect_code: rule
.redirect .redirect
+1 -1
View File
@@ -39,4 +39,4 @@ tokio.workspace = true
tokio-util.workspace = true tokio-util.workspace = true
[features] [features]
system-libs = ["zstd/pkg-config"] system-libs = [ "zstd/pkg-config" ]
+1 -1
View File
@@ -89,7 +89,7 @@ impl DataBlock {
return DataBlock::compressed(data_compressed.into()); return DataBlock::compressed(data_compressed.into());
} }
} }
DataBlock::plain(data) DataBlock::plain(data.into())
}) })
.await .await
.unwrap() .unwrap()
+7 -6
View File
@@ -262,7 +262,7 @@ impl DataLayout {
pub(crate) fn primary_block_dir(&self, hash: &Hash) -> PathBuf { pub(crate) fn primary_block_dir(&self, hash: &Hash) -> PathBuf {
let ipart = self.partition_from(hash); let ipart = self.partition_from(hash);
let idir = self.part_prim[ipart] as usize; let idir = self.part_prim[ipart] as usize;
self.block_dir_from(hash, self.data_dirs[idir].path.clone()) self.block_dir_from(hash, &self.data_dirs[idir].path)
} }
pub(crate) fn secondary_block_dirs<'a>( pub(crate) fn secondary_block_dirs<'a>(
@@ -272,7 +272,7 @@ impl DataLayout {
let ipart = self.partition_from(hash); let ipart = self.partition_from(hash);
self.part_sec[ipart] self.part_sec[ipart]
.iter() .iter()
.map(move |idir| self.block_dir_from(hash, self.data_dirs[*idir as usize].path.clone())) .map(move |idir| self.block_dir_from(hash, &self.data_dirs[*idir as usize].path))
} }
fn partition_from(&self, hash: &Hash) -> usize { fn partition_from(&self, hash: &Hash) -> usize {
@@ -283,7 +283,8 @@ impl DataLayout {
% DRIVE_NPART % DRIVE_NPART
} }
fn block_dir_from(&self, hash: &Hash, mut path: PathBuf) -> PathBuf { fn block_dir_from(&self, hash: &Hash, dir: &PathBuf) -> PathBuf {
let mut path = dir.clone();
path.push(hex::encode(&hash.as_slice()[0..1])); path.push(hex::encode(&hash.as_slice()[0..1]));
path.push(hex::encode(&hash.as_slice()[1..2])); path.push(hex::encode(&hash.as_slice()[1..2]));
path path
@@ -325,7 +326,7 @@ fn make_data_dirs(dirs: &DataDirEnum) -> Result<Vec<DataDir>, Error> {
let mut ok = false; let mut ok = false;
for dir in dirs.iter() { for dir in dirs.iter() {
let state = match &dir.capacity { let state = match &dir.capacity {
Some(cap) if !dir.read_only => { Some(cap) if dir.read_only == false => {
let capacity = cap.parse::<bytesize::ByteSize>() let capacity = cap.parse::<bytesize::ByteSize>()
.ok_or_message("invalid capacity value")?.as_u64(); .ok_or_message("invalid capacity value")?.as_u64();
if capacity == 0 { if capacity == 0 {
@@ -336,7 +337,7 @@ fn make_data_dirs(dirs: &DataDirEnum) -> Result<Vec<DataDir>, Error> {
capacity, capacity,
} }
} }
None if dir.read_only => { None if dir.read_only == true => {
DataDirState::ReadOnly DataDirState::ReadOnly
} }
_ => return Err(Error::Message(format!("data directories in data_dir should have a capacity value or be marked read_only, not the case for {}", dir.path.to_string_lossy()))), _ => return Err(Error::Message(format!("data directories in data_dir should have a capacity value or be marked read_only, not the case for {}", dir.path.to_string_lossy()))),
@@ -358,7 +359,7 @@ fn make_data_dirs(dirs: &DataDirEnum) -> Result<Vec<DataDir>, Error> {
} }
fn dir_not_empty(path: &PathBuf) -> Result<bool, Error> { fn dir_not_empty(path: &PathBuf) -> Result<bool, Error> {
for entry in std::fs::read_dir(path)? { for entry in std::fs::read_dir(&path)? {
let dir = entry?; let dir = entry?;
let ft = dir.file_type()?; let ft = dir.file_type()?;
let name = dir.file_name().into_string().ok(); let name = dir.file_name().into_string().ok();
+8 -6
View File
@@ -173,7 +173,7 @@ impl BlockManager {
data_fsync: config.data_fsync, data_fsync: config.data_fsync,
disable_scrub: config.disable_scrub, disable_scrub: config.disable_scrub,
compression_level: config.compression_level, compression_level: config.compression_level,
mutation_lock: [(); MUTEX_COUNT] mutation_lock: vec![(); MUTEX_COUNT]
.iter() .iter()
.map(|_| Mutex::new(BlockManagerLocked())) .map(|_| Mutex::new(BlockManagerLocked()))
.collect::<Vec<_>>(), .collect::<Vec<_>>(),
@@ -344,7 +344,7 @@ impl BlockManager {
/// Returns the set of nodes that should store a copy of a given block. /// Returns the set of nodes that should store a copy of a given block.
/// These are the nodes assigned to the block's hash in the current /// These are the nodes assigned to the block's hash in the current
/// layout version only: since blocks are immutable, we don't need to /// layout version only: since blocks are immutable, we don't need to
/// do complex logic when several layout versions are active at once, /// do complex logic when several layour versions are active at once,
/// just move them directly to the new nodes. /// just move them directly to the new nodes.
pub(crate) fn storage_nodes_of(&self, hash: &Hash) -> Result<Vec<Uuid>, Error> { pub(crate) fn storage_nodes_of(&self, hash: &Hash) -> Result<Vec<Uuid>, Error> {
let cluster_layout = self.system.cluster_layout(); let cluster_layout = self.system.cluster_layout();
@@ -569,10 +569,12 @@ impl BlockManager {
async { async {
match self.find_block(hash).await { match self.find_block(hash).await {
Some(p) => self.read_block_from(hash, &p).await, Some(p) => self.read_block_from(hash, &p).await,
None => Err(Error::Message(format!( None => {
"block {:?} not found on node", return Err(Error::Message(format!(
hash "block {:?} not found on node",
))), hash
)));
}
} }
} }
.bound_record_duration(&self.metrics.block_read_duration) .bound_record_duration(&self.metrics.block_read_duration)
+1 -1
View File
@@ -89,7 +89,7 @@ impl BlockRc {
.transaction(|tx| { .transaction(|tx| {
let mut cnt = 0; let mut cnt = 0;
for f in recalc_fns.iter() { for f in recalc_fns.iter() {
cnt += f(tx, hash)?; cnt += f(&tx, hash)?;
} }
let old_rc = RcEntry::parse_opt(tx.get(&self.rc_table, hash)?); let old_rc = RcEntry::parse_opt(tx.get(&self.rc_table, hash)?);
trace!( trace!(
+1 -1
View File
@@ -558,7 +558,7 @@ impl Worker for RebalanceWorker {
} }
fn status(&self) -> WorkerStatus { fn status(&self) -> WorkerStatus {
let t_cur = self.t_finished.unwrap_or_else(now_msec); let t_cur = self.t_finished.unwrap_or_else(|| now_msec());
let rate = self.moved_bytes / std::cmp::max(1, (t_cur - self.t_started) / 1000); let rate = self.moved_bytes / std::cmp::max(1, (t_cur - self.t_started) / 1000);
let mut freeform = vec![ let mut freeform = vec![
format!("Blocks moved: {}", self.moved), format!("Blocks moved: {}", self.moved),
+1 -1
View File
@@ -466,7 +466,7 @@ impl BlockResyncManager {
// First, check whether we are still supposed to store that // First, check whether we are still supposed to store that
// block in the latest cluster layout version. // block in the latest cluster layout version.
let storage_nodes = manager.storage_nodes_of(hash)?; let storage_nodes = manager.storage_nodes_of(&hash)?;
if !storage_nodes.contains(&manager.system.id) { if !storage_nodes.contains(&manager.system.id) {
info!( info!(
+5 -5
View File
@@ -28,8 +28,8 @@ parking_lot = { workspace = true, optional = true }
mktemp.workspace = true mktemp.workspace = true
[features] [features]
default = ["lmdb", "sqlite"] default = [ "lmdb", "sqlite" ]
bundled-libs = ["rusqlite?/bundled"] bundled-libs = [ "rusqlite?/bundled" ]
lmdb = ["heed"] lmdb = [ "heed" ]
fjall = ["dep:fjall", "dep:parking_lot"] fjall = [ "dep:fjall", "dep:parking_lot" ]
sqlite = ["rusqlite", "r2d2", "r2d2_sqlite"] sqlite = [ "rusqlite", "r2d2", "r2d2_sqlite" ]
+11 -10
View File
@@ -1,6 +1,6 @@
use core::ops::Bound; use core::ops::Bound;
use std::path::Path; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard}; use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard};
@@ -20,7 +20,7 @@ pub use fjall;
// -- // --
pub(crate) fn open_db(path: &Path, opt: &OpenOpt) -> Result<Db> { pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> {
info!("Opening Fjall database at: {}", path.display()); info!("Opening Fjall database at: {}", path.display());
if opt.fsync { if opt.fsync {
return Err(Error( return Err(Error(
@@ -105,14 +105,15 @@ impl IDb for FjallDb {
} }
fn list_trees(&self) -> Result<Vec<String>> { fn list_trees(&self) -> Result<Vec<String>> {
self.keyspace Ok(self
.keyspace
.list_partitions() .list_partitions()
.iter() .iter()
.map(|n| decode_name(n)) .map(|n| decode_name(&n))
.collect::<Result<Vec<_>>>() .collect::<Result<Vec<_>>>()?)
} }
fn snapshot(&self, base_path: &Path) -> Result<()> { fn snapshot(&self, base_path: &PathBuf) -> Result<()> {
std::fs::create_dir_all(base_path)?; std::fs::create_dir_all(base_path)?;
let path = Engine::Fjall.db_path(base_path); let path = Engine::Fjall.db_path(base_path);
@@ -271,7 +272,7 @@ impl<'a> FjallTx<'a> {
fn get_tree(&self, i: usize) -> TxOpResult<&TransactionalPartitionHandle> { fn get_tree(&self, i: usize) -> TxOpResult<&TransactionalPartitionHandle> {
self.trees.get(i).map(|tup| &tup.1).ok_or_else(|| { self.trees.get(i).map(|tup| &tup.1).ok_or_else(|| {
TxOpError(Error( TxOpError(Error(
"invalid tree id (it might have been opened after the transaction started)".into(), "invalid tree id (it might have been openned after the transaction started)".into(),
)) ))
}) })
} }
@@ -287,7 +288,7 @@ impl<'a> ITx for FjallTx<'a> {
} }
fn len(&self, tree_idx: usize) -> TxOpResult<usize> { fn len(&self, tree_idx: usize) -> TxOpResult<usize> {
let tree = self.get_tree(tree_idx)?; let tree = self.get_tree(tree_idx)?;
Ok(self.tx.len(tree)?) Ok(self.tx.len(tree)? as usize)
} }
fn insert(&mut self, tree_idx: usize, key: &[u8], value: &[u8]) -> TxOpResult<()> { fn insert(&mut self, tree_idx: usize, key: &[u8], value: &[u8]) -> TxOpResult<()> {
@@ -324,7 +325,7 @@ impl<'a> ITx for FjallTx<'a> {
let high = clone_bound(high); let high = clone_bound(high);
Ok(Box::new( Ok(Box::new(
self.tx self.tx
.range::<Vec<u8>, ByteVecRangeBounds>(tree, (low, high)) .range::<Vec<u8>, ByteVecRangeBounds>(&tree, (low, high))
.map(iterator_remap_tx), .map(iterator_remap_tx),
)) ))
} }
@@ -339,7 +340,7 @@ impl<'a> ITx for FjallTx<'a> {
let high = clone_bound(high); let high = clone_bound(high);
Ok(Box::new( Ok(Box::new(
self.tx self.tx
.range::<Vec<u8>, ByteVecRangeBounds>(tree, (low, high)) .range::<Vec<u8>, ByteVecRangeBounds>(&tree, (low, high))
.rev() .rev()
.map(iterator_remap_tx), .map(iterator_remap_tx),
)) ))
+4 -4
View File
@@ -17,7 +17,7 @@ use core::ops::{Bound, RangeBounds};
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::Cell; use std::cell::Cell;
use std::path::Path; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use thiserror::Error; use thiserror::Error;
@@ -133,7 +133,7 @@ impl Db {
Err(TxError::Db(tx_e)) Err(TxError::Db(tx_e))
} }
(Err(TxError::Db(tx_e)), Some(Ok(_))) => { (Err(TxError::Db(tx_e)), Some(Ok(_))) => {
// Transaction encounterred a DB error when committing the transaction, // Transaction encounterred a DB error when commiting the transaction,
// after user code was called // after user code was called
Err(TxError::Db(tx_e)) Err(TxError::Db(tx_e))
} }
@@ -147,7 +147,7 @@ impl Db {
} }
} }
pub fn snapshot(&self, path: &Path) -> Result<()> { pub fn snapshot(&self, path: &PathBuf) -> Result<()> {
self.0.snapshot(path) self.0.snapshot(path)
} }
@@ -348,7 +348,7 @@ pub(crate) trait IDb: Send + Sync {
fn engine(&self) -> String; fn engine(&self) -> String;
fn open_tree(&self, name: &str) -> Result<usize>; fn open_tree(&self, name: &str) -> Result<usize>;
fn list_trees(&self) -> Result<Vec<String>>; fn list_trees(&self) -> Result<Vec<String>>;
fn snapshot(&self, path: &Path) -> Result<()>; fn snapshot(&self, path: &PathBuf) -> Result<()>;
fn get(&self, tree: usize, key: &[u8]) -> Result<Option<Value>>; fn get(&self, tree: usize, key: &[u8]) -> Result<Option<Value>>;
fn approximate_len(&self, tree: usize) -> Result<usize>; fn approximate_len(&self, tree: usize) -> Result<usize>;
+12 -13
View File
@@ -3,7 +3,7 @@ use core::ops::Bound;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto; use std::convert::TryInto;
use std::marker::PhantomPinned; use std::marker::PhantomPinned;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use std::pin::Pin; use std::pin::Pin;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
@@ -22,7 +22,7 @@ pub use heed;
pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> { pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> {
info!("Opening LMDB database at: {}", path.display()); info!("Opening LMDB database at: {}", path.display());
if let Err(e) = std::fs::create_dir_all(path) { if let Err(e) = std::fs::create_dir_all(&path) {
return Err(Error( return Err(Error(
format!("Unable to create LMDB data directory: {}", e).into(), format!("Unable to create LMDB data directory: {}", e).into(),
)); ));
@@ -44,15 +44,17 @@ pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> {
env_builder.flag(heed::flags::Flags::MdbNoSync); env_builder.flag(heed::flags::Flags::MdbNoSync);
} }
} }
match env_builder.open(path) { match env_builder.open(&path) {
Err(heed::Error::Io(e)) if e.kind() == std::io::ErrorKind::OutOfMemory => Err(Error( Err(heed::Error::Io(e)) if e.kind() == std::io::ErrorKind::OutOfMemory => {
"OutOfMemory error while trying to open LMDB database. This can happen \ return Err(Error(
"OutOfMemory error while trying to open LMDB database. This can happen \
if your operating system is not allowing you to use sufficient virtual \ if your operating system is not allowing you to use sufficient virtual \
memory address space. Please check that no limit is set (ulimit -v). \ memory address space. Please check that no limit is set (ulimit -v). \
You may also try to set a smaller `lmdb_map_size` configuration parameter. \ You may also try to set a smaller `lmdb_map_size` configuration parameter. \
On 32-bit machines, you should probably switch to another database engine." On 32-bit machines, you should probably switch to another database engine."
.into(), .into(),
)), ))
}
Err(e) => Err(Error(format!("Cannot open LMDB database: {}", e).into())), Err(e) => Err(Error(format!("Cannot open LMDB database: {}", e).into())),
Ok(db) => Ok(LmdbDb::init(db)), Ok(db) => Ok(LmdbDb::init(db)),
} }
@@ -145,7 +147,7 @@ impl IDb for LmdbDb {
Ok(ret2) Ok(ret2)
} }
fn snapshot(&self, base_path: &Path) -> Result<()> { fn snapshot(&self, base_path: &PathBuf) -> Result<()> {
std::fs::create_dir_all(base_path)?; std::fs::create_dir_all(base_path)?;
let path = Engine::Lmdb.db_path(base_path); let path = Engine::Lmdb.db_path(base_path);
self.db self.db
@@ -395,12 +397,9 @@ where
// this reference will only be stored and accessed from the // this reference will only be stored and accessed from the
// returned ValueIter which guarantees that it is destroyed // returned ValueIter which guarantees that it is destroyed
// before the tx it is pointing to. // before the tx it is pointing to.
#[expect(clippy::deref_addrof)] unsafe { &*&raw const *tx }
unsafe {
&*&raw const *tx
}
}; };
let iter = iterfun(tx_lifetime_overextended)?; let iter = iterfun(&tx_lifetime_overextended)?;
*boxed.as_mut().iter() = Some(iter); *boxed.as_mut().iter() = Some(iter);
+25 -9
View File
@@ -1,4 +1,4 @@
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use crate::{Db, Error, Result}; use crate::{Db, Error, Result};
@@ -25,13 +25,20 @@ impl Engine {
} }
/// Return engine-specific DB path from base path /// Return engine-specific DB path from base path
pub fn db_path(&self, base_path: &Path) -> PathBuf { pub fn db_path(&self, base_path: &PathBuf) -> PathBuf {
let suffix = match self { let mut ret = base_path.clone();
Self::Lmdb => "db.lmdb", match self {
Self::Sqlite => "db.sqlite", Self::Lmdb => {
Self::Fjall => "db.fjall", ret.push("db.lmdb");
}; }
base_path.join(suffix) Self::Sqlite => {
ret.push("db.sqlite");
}
Self::Fjall => {
ret.push("db.fjall");
}
}
ret
} }
} }
@@ -61,13 +68,22 @@ impl std::str::FromStr for Engine {
} }
} }
#[derive(Default)]
pub struct OpenOpt { pub struct OpenOpt {
pub fsync: bool, pub fsync: bool,
pub lmdb_map_size: Option<usize>, pub lmdb_map_size: Option<usize>,
pub fjall_block_cache_size: Option<usize>, pub fjall_block_cache_size: Option<usize>,
} }
impl Default for OpenOpt {
fn default() -> Self {
Self {
fsync: false,
lmdb_map_size: None,
fjall_block_cache_size: None,
}
}
}
pub fn open_db(path: &PathBuf, engine: Engine, opt: &OpenOpt) -> Result<Db> { pub fn open_db(path: &PathBuf, engine: Engine, opt: &OpenOpt) -> Result<Db> {
match engine { match engine {
// ---- Sqlite DB ---- // ---- Sqlite DB ----
+7 -7
View File
@@ -1,7 +1,7 @@
use core::ops::Bound; use core::ops::Bound;
use std::marker::PhantomPinned; use std::marker::PhantomPinned;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use std::pin::Pin; use std::pin::Pin;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::sync::{Arc, Mutex, RwLock}; use std::sync::{Arc, Mutex, RwLock};
@@ -23,7 +23,7 @@ pub use rusqlite;
pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> { pub(crate) fn open_db(path: &PathBuf, opt: &OpenOpt) -> Result<Db> {
info!("Opening Sqlite database at: {}", path.display()); info!("Opening Sqlite database at: {}", path.display());
let manager = r2d2_sqlite::SqliteConnectionManager::file(path); let manager = r2d2_sqlite::SqliteConnectionManager::file(path);
SqliteDb::open(manager, opt.fsync) Ok(SqliteDb::new(manager, opt.fsync)?)
} }
// ---- // ----
@@ -62,7 +62,7 @@ pub struct SqliteDb {
} }
impl SqliteDb { impl SqliteDb {
pub fn open(manager: SqliteConnectionManager, sync_mode: bool) -> Result<Db> { pub fn new(manager: SqliteConnectionManager, sync_mode: bool) -> Result<Db> {
let manager = manager.with_init(move |db| { let manager = manager.with_init(move |db| {
db.pragma_update(None, "journal_mode", "WAL")?; db.pragma_update(None, "journal_mode", "WAL")?;
if sync_mode { if sync_mode {
@@ -110,7 +110,7 @@ impl IDb for SqliteDb {
let name = format!("tree_{}", name.replace(':', "_COLON_")); let name = format!("tree_{}", name.replace(':', "_COLON_"));
let mut trees = self.trees.write().unwrap(); let mut trees = self.trees.write().unwrap();
if let Some(i) = trees.iter().position(|x| x.as_ref() == name) { if let Some(i) = trees.iter().position(|x| x.as_ref() == &name) {
Ok(i) Ok(i)
} else { } else {
let db = self.db.get()?; let db = self.db.get()?;
@@ -150,10 +150,10 @@ impl IDb for SqliteDb {
Ok(trees) Ok(trees)
} }
fn snapshot(&self, base_path: &Path) -> Result<()> { fn snapshot(&self, base_path: &PathBuf) -> Result<()> {
std::fs::create_dir_all(base_path)?; std::fs::create_dir_all(base_path)?;
let path = Engine::Sqlite let path = Engine::Sqlite
.db_path(base_path) .db_path(&base_path)
.into_os_string() .into_os_string()
.into_string() .into_string()
.map_err(|_| Error("invalid sqlite path string".into()))?; .map_err(|_| Error("invalid sqlite path string".into()))?;
@@ -308,7 +308,7 @@ impl IDb for SqliteDb {
trace!("transaction done"); trace!("transaction done");
drop(lock); drop(lock);
res return res;
} }
} }
+3 -3
View File
@@ -21,7 +21,7 @@ fn test_suite(db: Db) {
let res = db.transaction::<_, (), _>(|tx| { let res = db.transaction::<_, (), _>(|tx| {
assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), va); assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), va);
let _: () = tx.insert(&tree, ka, vb).unwrap(); assert_eq!(tx.insert(&tree, ka, vb).unwrap(), ());
assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vb); assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vb);
@@ -33,7 +33,7 @@ fn test_suite(db: Db) {
let res = db.transaction::<(), _, _>(|tx| { let res = db.transaction::<(), _, _>(|tx| {
assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vb); assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vb);
let _: () = tx.insert(&tree, ka, vc).unwrap(); assert_eq!(tx.insert(&tree, ka, vc).unwrap(), ());
assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vc); assert_eq!(tx.get(&tree, ka).unwrap().unwrap(), vc);
@@ -145,7 +145,7 @@ fn test_sqlite_db() {
use crate::sqlite_adapter::SqliteDb; use crate::sqlite_adapter::SqliteDb;
let manager = r2d2_sqlite::SqliteConnectionManager::memory(); let manager = r2d2_sqlite::SqliteConnectionManager::memory();
let db = SqliteDb::open(manager, false).unwrap(); let db = SqliteDb::new(manager, false).unwrap();
test_suite(db); test_suite(db);
} }
+13 -17
View File
@@ -86,36 +86,32 @@ k2v-client.workspace = true
[features] [features]
default = ["bundled-libs", "metrics", "lmdb", "sqlite", "k2v"] default = [ "bundled-libs", "metrics", "lmdb", "sqlite", "k2v" ]
k2v = ["garage_util/k2v", "garage_api_k2v", "garage_api_admin/k2v"] k2v = [ "garage_util/k2v", "garage_api_k2v", "garage_api_admin/k2v" ]
# Database engines # Database engines
lmdb = ["garage_model/lmdb"] lmdb = [ "garage_model/lmdb" ]
sqlite = ["garage_model/sqlite"] sqlite = [ "garage_model/sqlite" ]
fjall = ["garage_model/fjall"] fjall = [ "garage_model/fjall" ]
# Automatic registration and discovery via Consul API # Automatic registration and discovery via Consul API
consul-discovery = ["garage_rpc/consul-discovery"] consul-discovery = [ "garage_rpc/consul-discovery" ]
# Automatic registration and discovery via Kubernetes API # Automatic registration and discovery via Kubernetes API
kubernetes-discovery = ["garage_rpc/kubernetes-discovery"] kubernetes-discovery = [ "garage_rpc/kubernetes-discovery" ]
# Prometheus exporter (/metrics endpoint). # Prometheus exporter (/metrics endpoint).
metrics = ["garage_api_admin/metrics", "opentelemetry-prometheus"] metrics = [ "garage_api_admin/metrics", "opentelemetry-prometheus" ]
# Exporter for the OpenTelemetry Collector. # Exporter for the OpenTelemetry Collector.
telemetry-otlp = ["opentelemetry-otlp"] telemetry-otlp = [ "opentelemetry-otlp" ]
# Logging to syslog # Logging to syslog
syslog = ["syslog-tracing"] syslog = [ "syslog-tracing" ]
# Logging to journald # Logging to journald
journald = ["tracing-journald"] journald = [ "tracing-journald" ]
# NOTE: bundled-libs and system-libs should be treat as mutually exclusive; # NOTE: bundled-libs and system-libs should be treat as mutually exclusive;
# exactly one of them should be enabled. # exactly one of them should be enabled.
# Use bundled libsqlite instead of linking against system-provided. # Use bundled libsqlite instead of linking against system-provided.
bundled-libs = ["garage_db/bundled-libs"] bundled-libs = [ "garage_db/bundled-libs" ]
# Link against system-provided libsodium and libzstd. # Link against system-provided libsodium and libzstd.
system-libs = [ system-libs = [ "garage_block/system-libs", "garage_rpc/system-libs", "sodiumoxide/use-pkg-config" ]
"garage_block/system-libs",
"garage_rpc/system-libs",
"sodiumoxide/use-pkg-config",
]
+1 -1
View File
@@ -8,7 +8,7 @@ use garage_db::*;
#[derive(StructOpt, Debug)] #[derive(StructOpt, Debug)]
pub struct ConvertDbOpt { pub struct ConvertDbOpt {
/// Input database path (not the same as metadata_dir, see /// Input database path (not the same as metadata_dir, see
/// <https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#db_engine> /// https://garagehq.deuxfleurs.fr/documentation/reference-manual/configuration/#db-engine-since-v0-8-0)
#[structopt(short = "i")] #[structopt(short = "i")]
input_path: PathBuf, input_path: PathBuf,
/// Input database engine (lmdb or sqlite; limited by db engines /// Input database engine (lmdb or sqlite; limited by db engines
+1 -1
View File
@@ -230,7 +230,7 @@ fn print_token_info(token: &GetAdminTokenInfoResponse) {
format!("Created:\t{}", token.created.unwrap().with_timezone(&Local)), format!("Created:\t{}", token.created.unwrap().with_timezone(&Local)),
format!( format!(
"Validity:\t{}", "Validity:\t{}",
if token.expired { "EXPIRED" } else { "valid" } token.expired.then_some("EXPIRED").unwrap_or("valid")
), ),
format!( format!(
"Expiration:\t{}", "Expiration:\t{}",
+9 -14
View File
@@ -67,9 +67,11 @@ impl Cli {
Some(BlockVersionBacklink::Object { bucket_id, key }) => { Some(BlockVersionBacklink::Object { bucket_id, key }) => {
table.push(format!( table.push(format!(
"{}\t{:.16}{}\t{:.16}\t{}", "{}\t{:.16}{}\t{:.16}\t{}",
if ver.ref_deleted { "deleted" } else { "active" }, ver.ref_deleted.then_some("deleted").unwrap_or("active"),
ver.version_id, ver.version_id,
deleted_to_str(ver.version_deleted), ver.version_deleted
.then_some(" (deleted)")
.unwrap_or_default(),
bucket_id, bucket_id,
key key
)); ));
@@ -83,13 +85,15 @@ impl Cli {
}) => { }) => {
table.push(format!( table.push(format!(
"{}\t{:.16}{}\t{:.16}\t{}\t{:.16}{}", "{}\t{:.16}{}\t{:.16}\t{}\t{:.16}{}",
if ver.ref_deleted { "deleted" } else { "active" }, ver.ref_deleted.then_some("deleted").unwrap_or("active"),
ver.version_id, ver.version_id,
deleted_to_str(ver.version_deleted), ver.version_deleted
.then_some(" (deleted)")
.unwrap_or_default(),
bucket_id.as_deref().unwrap_or(""), bucket_id.as_deref().unwrap_or(""),
key.as_deref().unwrap_or(""), key.as_deref().unwrap_or(""),
upload_id, upload_id,
deleted_to_str(*upload_deleted), upload_deleted.then_some(" (deleted)").unwrap_or_default(),
)); ));
} }
None => { None => {
@@ -163,12 +167,3 @@ impl Cli {
Ok(()) Ok(())
} }
} }
#[must_use]
const fn deleted_to_str(deleted: bool) -> &'static str {
if deleted {
" (deleted)"
} else {
""
}
}
+7 -2
View File
@@ -92,7 +92,12 @@ impl Cli {
.await?; .await?;
// CLI-only checks: the bucket must not have other aliases // CLI-only checks: the bucket must not have other aliases
if bucket.global_aliases.iter().any(|a| *a != opt.name) { if bucket
.global_aliases
.iter()
.find(|a| **a != opt.name)
.is_some()
{
return Err(Error::Message(format!("Bucket {} still has other global aliases. Use `bucket unalias` to delete them one by one.", opt.name))); return Err(Error::Message(format!("Bucket {} still has other global aliases. Use `bucket unalias` to delete them one by one.", opt.name)));
} }
@@ -562,7 +567,7 @@ fn print_bucket_info(bucket: &GetBucketInfoResponse) {
format_table(info); format_table(info);
println!(); println!("");
println!("==== KEYS FOR THIS BUCKET ===="); println!("==== KEYS FOR THIS BUCKET ====");
let mut key_info = vec!["Permissions\tAccess key\t\tLocal aliases".to_string()]; let mut key_info = vec!["Permissions\tAccess key\t\tLocal aliases".to_string()];
key_info.extend(bucket.keys.iter().map(|key| { key_info.extend(bucket.keys.iter().map(|key| {
+2 -2
View File
@@ -283,7 +283,7 @@ fn print_key_info(key: &GetKeyInfoResponse) {
table.extend([ table.extend([
format!( format!(
"Validity:\t{}", "Validity:\t{}",
if key.expired { "EXPIRED" } else { "valid" } key.expired.then_some("EXPIRED").unwrap_or("valid")
), ),
format!( format!(
"Expiration:\t{}", "Expiration:\t{}",
@@ -296,7 +296,7 @@ fn print_key_info(key: &GetKeyInfoResponse) {
]); ]);
format_table(table); format_table(table);
println!(); println!("");
println!("==== BUCKETS FOR THIS KEY ===="); println!("==== BUCKETS FOR THIS KEY ====");
let mut bucket_info = vec!["Permissions\tID\tGlobal aliases\tLocal aliases".to_string()]; let mut bucket_info = vec!["Permissions\tID\tGlobal aliases\tLocal aliases".to_string()];
bucket_info.extend(key.buckets.iter().map(|bucket| { bucket_info.extend(key.buckets.iter().map(|bucket| {
+4 -4
View File
@@ -73,7 +73,7 @@ impl Cli {
let mut actions = vec![]; let mut actions = vec![];
for node in opt.replace.iter() { for node in opt.replace.iter() {
let id = find_matching_node(&status, &layout, node)?; let id = find_matching_node(&status, &layout, &node)?;
actions.push(NodeRoleChange { actions.push(NodeRoleChange {
id, id,
@@ -82,7 +82,7 @@ impl Cli {
} }
for node in opt.node_ids.iter() { for node in opt.node_ids.iter() {
let id = find_matching_node(&status, &layout, node)?; let id = find_matching_node(&status, &layout, &node)?;
let current = get_staged_or_current_role(&id, &layout); let current = get_staged_or_current_role(&id, &layout);
@@ -344,10 +344,10 @@ pub fn get_staged_or_current_role(
None None
} }
pub fn find_matching_node( pub fn find_matching_node<'a>(
status: &GetClusterStatusResponse, status: &GetClusterStatusResponse,
layout: &GetClusterLayoutResponse, layout: &GetClusterLayoutResponse,
pattern: &str, pattern: &'a str,
) -> Result<String, Error> { ) -> Result<String, Error> {
let all_node_ids_iter = status let all_node_ids_iter = status
.nodes .nodes
+1 -1
View File
@@ -168,7 +168,7 @@ pub fn table_list_abbr<T: IntoIterator<Item = S>, S: AsRef<str>>(values: T) -> S
pub fn parse_expires_in(expires_in: &Option<String>) -> Result<Option<DateTime<Utc>>, Error> { pub fn parse_expires_in(expires_in: &Option<String>) -> Result<Option<DateTime<Utc>>, Error> {
expires_in expires_in
.as_ref() .as_ref()
.map(|x| parse_duration::parse::parse(x).map(|dur| Utc::now() + dur)) .map(|x| parse_duration::parse::parse(&x).map(|dur| Utc::now() + dur))
.transpose() .transpose()
.ok_or_message("Invalid duration passed for --expires-in parameter") .ok_or_message("Invalid duration passed for --expires-in parameter")
} }

Some files were not shown because too many files have changed in this diff Show More