diff --git a/Cargo.lock b/Cargo.lock
index ad5d098d..c0b00ffb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1258,7 +1258,6 @@ dependencies = [
"opentelemetry-otlp",
"opentelemetry-prometheus",
"parse_duration",
- "serde",
"serde_json",
"sha1",
"sha2",
@@ -1277,9 +1276,12 @@ version = "1.0.1"
dependencies = [
"argon2",
"async-trait",
+ "bytesize",
"err-derive",
+ "format_table",
"futures",
"garage_api_common",
+ "garage_block",
"garage_model",
"garage_rpc",
"garage_table",
@@ -1289,6 +1291,7 @@ dependencies = [
"hyper 1.6.0",
"opentelemetry",
"opentelemetry-prometheus",
+ "paste",
"prometheus",
"serde",
"serde_json",
diff --git a/Cargo.toml b/Cargo.toml
index fa8f0be0..37127a7d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,6 +67,7 @@ mktemp = "0.5"
nix = { version = "0.29", default-features = false, features = ["fs"] }
nom = "7.1"
parse_duration = "2.1"
+paste = "1.0"
pin-project = "1.0.12"
pnet_datalink = "0.34"
rand = "0.8"
diff --git a/doc/api/garage-admin-v2.html b/doc/api/garage-admin-v2.html
new file mode 100644
index 00000000..d93c2e7d
--- /dev/null
+++ b/doc/api/garage-admin-v2.html
@@ -0,0 +1,24 @@
+
+
+
+ Garage Adminstration API v0
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/doc/api/garage-admin-v2.yml b/doc/api/garage-admin-v2.yml
new file mode 100644
index 00000000..f9e3c10c
--- /dev/null
+++ b/doc/api/garage-admin-v2.yml
@@ -0,0 +1,1336 @@
+openapi: 3.0.0
+info:
+ version: v2.0.0
+ title: Garage Administration API v0+garage-v2.0.0
+ 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. 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:
+ /GetClusterHealth:
+ get:
+ tags:
+ - Nodes
+ operationId: "GetClusterHealth"
+ summary: "Cluster health report"
+ description: |
+ Returns the global status of the cluster, the number of connected nodes (over the number of known ones), the number of healthy storage nodes (over the declared ones), and the number of healthy partitions (over the total).
+ responses:
+ '500':
+ description: |
+ The server can not answer your request because it is in a bad state
+ '200':
+ description: |
+ Information about the queried node, its environment and the current layout
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ status, knownNodes, connectedNodes, storageNodes, storageNodesOk, partitions, partitionsQuorum, partitionsAllOk ]
+ properties:
+ status:
+ type: string
+ example: "healthy"
+ knownNodes:
+ type: integer
+ format: int64
+ example: 4
+ connectedNodes:
+ type: integer
+ format: int64
+ example: 4
+ storageNodes:
+ type: integer
+ format: int64
+ example: 3
+ storageNodesOk:
+ type: integer
+ format: int64
+ example: 3
+ partitions:
+ type: integer
+ format: int64
+ example: 256
+ partitionsQuorum:
+ type: integer
+ format: int64
+ example: 256
+ partitionsAllOk:
+ type: integer
+ format: int64
+ example: 256
+ /GetClusterStatus:
+ get:
+ tags:
+ - Nodes
+ operationId: "GetClusterStatus"
+ summary: "Describe cluster"
+ description: |
+ Returns the cluster's current status, including:
+ - ID of the node being queried and its version of the Garage daemon
+ - Live nodes
+ - Currently configured cluster layout
+ - Staged changes to the cluster layout
+
+ *Capacity is given in bytes*
+ responses:
+ '500':
+ description: |
+ The server can not answer your request because it is in a bad state
+ '200':
+ description: |
+ Information about the queried node, its environment and the current layout
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ node, garageVersion, garageFeatures, rustVersion, dbEngine, knownNodes, layout ]
+ properties:
+ node:
+ type: string
+ example: "ec79480e0ce52ae26fd00c9da684e4fa56658d9c64cdcecb094e936de0bfe71f"
+ garageVersion:
+ type: string
+ example: "v2.0.0"
+ garageFeatures:
+ type: array
+ items:
+ type: string
+ example:
+ - "k2v"
+ - "lmdb"
+ - "sqlite"
+ - "consul-discovery"
+ - "kubernetes-discovery"
+ - "metrics"
+ - "telemetry-otlp"
+ - "bundled-libs"
+ rustVersion:
+ type: string
+ example: "1.68.0"
+ dbEngine:
+ type: string
+ example: "LMDB (using Heed crate)"
+ knownNodes:
+ type: array
+ example:
+ - id: "ec79480e0ce52ae26fd00c9da684e4fa56658d9c64cdcecb094e936de0bfe71f"
+ addr: "10.0.0.11:3901"
+ isUp: true
+ lastSeenSecsAgo: 9
+ hostname: orion
+ - id: "4a6ae5a1d0d33bf895f5bb4f0a418b7dc94c47c0dd2eb108d1158f3c8f60b0ff"
+ addr: "10.0.0.12:3901"
+ isUp: true
+ lastSeenSecsAgo: 13
+ hostname: pegasus
+ - id: "e2ee7984ee65b260682086ec70026165903c86e601a4a5a501c1900afe28d84b"
+ addr: "10.0.0.13:3901"
+ isUp: true
+ lastSeenSecsAgo: 2
+ hostname: neptune
+ items:
+ $ref: '#/components/schemas/NodeNetworkInfo'
+ layout:
+ $ref: '#/components/schemas/ClusterLayout'
+
+ /ConnectClusterNodes:
+ post:
+ tags:
+ - Nodes
+ operationId: "ConnectClusterNodes"
+ summary: "Connect a new node"
+ description: |
+ Instructs this Garage node to connect to other Garage nodes at specified `@`. `node_id` is generated automatically on node start.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: array
+ example:
+ - "ec79480e0ce52ae26fd00c9da684e4fa56658d9c64cdcecb094e936de0bfe71f@10.0.0.11:3901"
+ - "4a6ae5a1d0d33bf895f5bb4f0a418b7dc94c47c0dd2eb108d1158f3c8f60b0ff@10.0.0.12:3901"
+ items:
+ type: string
+
+ responses:
+ '500':
+ description: |
+ The server can not answer your request because it is in a bad state
+ '400':
+ description: |
+ Your request is malformed, check your JSON
+ '200':
+ description: |
+ The request has been handled correctly but it does not mean that all connection requests succeeded; some might have fail, you need to check the body!
+ content:
+ application/json:
+ schema:
+ type: array
+ example:
+ - success: true
+ error:
+ - success: false
+ error: "Handshake error"
+ items:
+ type: object
+ properties:
+ success:
+ type: boolean
+ example: true
+ error:
+ type: string
+ nullable: true
+ example: null
+
+ /GetClusterLayout:
+ get:
+ tags:
+ - Layout
+ operationId: "GetClusterLayout"
+ summary: "Details on the current and staged layout"
+ description: |
+ Returns the cluster's current layout, including:
+ - Currently configured cluster layout
+ - Staged changes to the cluster layout
+
+ *Capacity is given in bytes*
+ *The info returned by this endpoint is a subset of the info returned by `GET /GetClusterStatus`.*
+ responses:
+ '500':
+ description: |
+ The server can not answer your request because it is in a bad state
+ '200':
+ description: |
+ Returns the cluster's current cluster layout:
+ - Currently configured cluster layout
+ - Staged changes to the cluster layout
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ClusterLayout'
+
+ /UpdateClusterLayout:
+ post:
+ tags:
+ - Layout
+ operationId: "UpdateClusterLayout"
+ summary: "Send modifications to the cluster layout"
+ description: |
+ Send modifications to the cluster layout. These modifications will be included in the staged role changes, visible in subsequent calls of `GET /GetClusterHealth`. Once the set of staged changes is satisfactory, the user may call `POST /ApplyClusterLayout` to apply the changed changes, or `POST /RevertClusterLayout` to clear all of the staged changes in the layout.
+
+ Setting the capacity to `null` will configure the node as a gateway.
+ Otherwise, capacity must be now set in bytes (before Garage 0.9 it was arbitrary weights).
+ For example to declare 100GB, you must set `capacity: 100000000000`.
+
+ Garage uses internally the International System of Units (SI), it assumes that 1kB = 1000 bytes, and displays storage as kB, MB, GB (and not KiB, MiB, GiB that assume 1KiB = 1024 bytes).
+ requestBody:
+ description: |
+ To add a new node to the layout or to change the configuration of an existing node, simply set the values you want (`zone`, `capacity`, and `tags`).
+ To remove a node, simply pass the `remove: true` field.
+ This logic is represented in OpenAPI with a "One Of" object.
+
+ Contrary to the CLI that may update only a subset of the fields capacity, zone and tags, when calling this API all of these values must be specified.
+ required: true
+ content:
+ application/json:
+ schema:
+ type: array
+ example:
+ - id: "e2ee7984ee65b260682086ec70026165903c86e601a4a5a501c1900afe28d84b"
+ zone: "geneva"
+ capacity: 100000000000
+ tags:
+ - gateway
+ - id: "4a6ae5a1d0d33bf895f5bb4f0a418b7dc94c47c0dd2eb108d1158f3c8f60b0ff"
+ remove: true
+ items:
+ $ref: '#/components/schemas/NodeRoleChange'
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: "The layout modification has been correctly staged"
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ClusterLayout'
+
+ /ApplyClusterLayout:
+ post:
+ tags:
+ - Layout
+ operationId: "ApplyClusterLayout"
+ summary: "Apply staged layout"
+ description: |
+ Applies to the cluster the layout changes currently registered as staged layout changes.
+
+ *Note: do not try to parse the `message` field of the response, it is given as an array of string specifically because its format is not stable.*
+ requestBody:
+ description: |
+ Similarly to the CLI, the body must include the version of the new layout that will be created, which MUST be 1 + the value of the currently existing layout in the cluster.
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/LayoutVersion'
+
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: "The staged layout has been applied as the new layout of the cluster, a rebalance has been triggered."
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ message, layout ]
+ properties:
+ message:
+ type: array
+ items:
+ type: string
+ example:
+ - "==== COMPUTATION OF A NEW PARTITION ASSIGNATION ===="
+ - ""
+ - "Partitions are replicated 1 times on at least 1 distinct zones."
+ - ""
+ - "Optimal partition size: 419.4 MB (3 B in previous layout)"
+ - "Usable capacity / total cluster capacity: 107.4 GB / 107.4 GB (100.0 %)"
+ - "Effective capacity (replication factor 1): 107.4 GB"
+ - ""
+ - "A total of 0 new copies of partitions need to be transferred."
+ - ""
+ - "dc1 Tags Partitions Capacity Usable capacity\n 6a8e08af2aab1083 a,v 256 (0 new) 107.4 GB 107.4 GB (100.0%)\n TOTAL 256 (256 unique) 107.4 GB 107.4 GB (100.0%)\n\n"
+ layout:
+ $ref: '#/components/schemas/ClusterLayout'
+
+
+ /RevertClusterLayout:
+ post:
+ tags:
+ - Layout
+ operationId: "RevertClusterLayout"
+ summary: "Clear staged layout"
+ description: |
+ Clears all of the staged layout changes.
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: "The staged layout has been cleared, you can start again sending modification from a fresh copy with `POST /UpdateClusterLayout`."
+
+ /ListKeys:
+ get:
+ tags:
+ - Key
+ operationId: "ListKeys"
+ summary: "List all keys"
+ description: |
+ Returns all API access keys in the cluster.
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '200':
+ description: |
+ Returns the key identifier (aka `AWS_ACCESS_KEY_ID`) and its associated, human friendly, name if any (otherwise return an empty string)
+ content:
+ application/json:
+ schema:
+ type: array
+ example:
+ - id: "GK31c2f218a2e44f485b94239e"
+ name: "test-key"
+ - id: "GKe10061ac9c2921f09e4c5540"
+ name: ""
+ items:
+ type: object
+ required: [ id ]
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+
+ /CreateKey:
+ post:
+ tags:
+ - Key
+ operationId: "CreateKey"
+ summary: "Create a new API key"
+ description: |
+ Creates a new API access key.
+ requestBody:
+ description: |
+ You can set a friendly name for this key.
+ If you don't want to, you can set the name to `null`.
+
+ *Note: the secret key is returned in the response.*
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ nullable: true
+ example: "test-key"
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: "The key has been added"
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/KeyInfo'
+
+ /GetKeyInfo:
+ get:
+ tags:
+ - Key
+ operationId: "GetKeyInfo"
+ summary: "Get key information"
+ description: |
+ Return information about a specific key like its identifiers, its permissions and buckets on which it has permissions.
+ You can search by specifying the exact key identifier (`id`) or by specifying a pattern (`search`).
+
+ For confidentiality reasons, the secret key is not returned by default: you must pass the `showSecretKey` query parameter to get it.
+ parameters:
+ - name: id
+ in: query
+ description: |
+ The exact API access key generated by Garage.
+
+ Incompatible with `search`.
+ example: "GK31c2f218a2e44f485b94239e"
+ schema:
+ type: string
+ - name: search
+ in: query
+ description: |
+ A pattern (beginning or full string) corresponding to a key identifier or friendly name.
+
+ Incompatible with `id`.
+ example: "test-k"
+ schema:
+ type: string
+ - name: showSecretKey
+ in: query
+ schema:
+ type: string
+ default: "false"
+ enum:
+ - "false"
+ - "true"
+ example: "false"
+ required: false
+ description: "Wether or not the secret key should be returned in the response"
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '200':
+ description: |
+ Returns information about the key
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/KeyInfo'
+
+ /DeleteKey:
+ post:
+ tags:
+ - Key
+ operationId: "DeleteKey"
+ summary: "Delete a key"
+ description: |
+ Delete a key from the cluster. Its access will be removed from all the buckets. Buckets are not automatically deleted and can be dangling. You should manually delete them before.
+ parameters:
+ - name: id
+ in: query
+ required: true
+ description: "The exact API access key generated by Garage"
+ example: "GK31c2f218a2e44f485b94239e"
+ schema:
+ type: string
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '200':
+ description: "The key has been deleted"
+
+
+ /UpdateKey:
+ post:
+ tags:
+ - Key
+ operationId: "UpdateKey"
+ summary: "Update a key"
+ description: |
+ Updates information about the specified API access key.
+
+ *Note: the secret key is not returned in the response, `null` is sent instead.*
+ parameters:
+ - name: id
+ in: query
+ required: true
+ description: "The exact API access key generated by Garage"
+ example: "GK31c2f218a2e44f485b94239e"
+ schema:
+ type: string
+ requestBody:
+ description: |
+ For a given key, provide a first set with the permissions to grant, and a second set with the permissions to remove
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ example: "test-key"
+ allow:
+ type: object
+ example:
+ properties:
+ createBucket:
+ type: boolean
+ example: true
+ deny:
+ type: object
+ properties:
+ createBucket:
+ type: boolean
+ example: true
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: |
+ Returns information about the key
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/KeyInfo'
+
+
+ /ImportKey:
+ post:
+ tags:
+ - Key
+ operationId: "ImportKey"
+ summary: "Import an existing key"
+ description: |
+ Imports an existing API key. This feature must only be used for migrations and backup restore.
+
+ **Do not use it to generate custom key identifiers or you will break your Garage cluster.**
+ requestBody:
+ description: |
+ Information on the key to import
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ name, accessKeyId, secretAccessKey ]
+ properties:
+ name:
+ type: string
+ example: "test-key"
+ nullable: true
+ accessKeyId:
+ type: string
+ example: "GK31c2f218a2e44f485b94239e"
+ secretAccessKey:
+ type: string
+ example: "b892c0665f0ada8a4755dae98baa3b133590e11dae3bcc1f9d769d67f16c3835"
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Invalid syntax or requested change"
+ '200':
+ description: "The key has been imported into the system"
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/KeyInfo'
+
+ /ListBuckets:
+ get:
+ tags:
+ - Bucket
+ operationId: "ListBuckets"
+ summary: "List all buckets"
+ description: |
+ List all the buckets on the cluster with their UUID and their global and local aliases.
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '200':
+ description: |
+ Returns the UUID of the bucket and all its aliases
+ content:
+ application/json:
+ schema:
+ type: array
+ example:
+ - id: "70dc3bed7fe83a75e46b66e7ddef7d56e65f3c02f9f80b6749fb97eccb5e1033"
+ globalAliases:
+ - "container_registry"
+ - id: "96470e0df00ec28807138daf01915cfda2bee8eccc91dea9558c0b4855b5bf95"
+ localAliases:
+ - alias: "my_documents"
+ accessKeyid: "GK31c2f218a2e44f485b94239e"
+ - id: "d7452a935e663fc1914f3a5515163a6d3724010ce8dfd9e4743ca8be5974f995"
+ globalAliases:
+ - "example.com"
+ - "www.example.com"
+ localAliases:
+ - alias: "corp_website"
+ accessKeyId: "GKe10061ac9c2921f09e4c5540"
+ - alias: "web"
+ accessKeyid: "GK31c2f218a2e44f485b94239e"
+ - id: ""
+ items:
+ type: object
+ required: [ id ]
+ properties:
+ id:
+ type: string
+ globalAliases:
+ type: array
+ items:
+ type: string
+ localAliases:
+ type: array
+ items:
+ type: object
+ required: [ alias, accessKeyId ]
+ properties:
+ alias:
+ type: string
+ accessKeyId:
+ type: string
+
+ /CreateBucket:
+ post:
+ tags:
+ - Bucket
+ operationId: "CreateBucket"
+ summary: "Create a bucket"
+ description: |
+ Creates a new bucket, either with a global alias, a local one, or no alias at all.
+ Technically, you can also specify both `globalAlias` and `localAlias` and that would create two aliases.
+ requestBody:
+ description: |
+ Aliases to put on the new bucket
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ globalAlias:
+ type: string
+ example: "my_documents"
+ localAlias:
+ type: object
+ properties:
+ accessKeyId:
+ type: string
+ alias:
+ type: string
+ allow:
+ type: object
+ properties:
+ read:
+ type: boolean
+ example: true
+ write:
+ type: boolean
+ example: true
+ owner:
+ type: boolean
+ example: true
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "The payload is not formatted correctly"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+ /GetBucketInfo:
+ get:
+ tags:
+ - Bucket
+ operationId: "GetBucketInfo"
+ summary: "Get a bucket"
+ description: |
+ Given a bucket identifier (`id`) or a global alias (`alias`), get its information.
+ It includes its aliases, its web configuration, keys that have some permissions
+ on it, some statistics (number of objects, size), number of dangling multipart uploads,
+ and its quotas (if any).
+ parameters:
+ - name: id
+ in: query
+ description: |
+ The exact bucket identifier, a 32 bytes hexadecimal string.
+
+ Incompatible with `alias`.
+ example: "b4018dc61b27ccb5c64ec1b24f53454bbbd180697c758c4d47a22a8921864a87"
+ schema:
+ type: string
+ - name: alias
+ in: query
+ description: |
+ The exact global alias of one of the existing buckets.
+
+ Incompatible with `id`.
+ example: "my_documents"
+ schema:
+ type: string
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+
+ /DeleteBucket:
+ post:
+ tags:
+ - Bucket
+ operationId: "DeleteBucket"
+ summary: "Delete a bucket"
+ description: |
+ Delete a bucket.Deletes a storage bucket. A bucket cannot be deleted if it is not empty.
+
+ **Warning:** this will delete all aliases associated with the bucket!
+ parameters:
+ - name: id
+ in: query
+ required: true
+ description: "The exact bucket identifier, a 32 bytes hexadecimal string"
+ example: "b4018dc61b27ccb5c64ec1b24f53454bbbd180697c758c4d47a22a8921864a87"
+ schema:
+ type: string
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bucket is not empty"
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Bucket has been deleted
+
+
+
+ /UpdateBucket:
+ post:
+ tags:
+ - Bucket
+ operationId: "UpdateBucket"
+ summary: "Update a bucket"
+ description: |
+ All fields (`websiteAccess` and `quotas`) are optional.
+ If they are present, the corresponding modifications are applied to the bucket, otherwise nothing is changed.
+
+ In `websiteAccess`: if `enabled` is `true`, `indexDocument` must be specified.
+ The field `errorDocument` is optional, if no error document is set a generic
+ error message is displayed when errors happen. Conversely, if `enabled` is
+ `false`, neither `indexDocument` nor `errorDocument` must be specified.
+
+ In `quotas`: new values of `maxSize` and `maxObjects` must both be specified, or set to `null`
+ to remove the quotas. An absent value will be considered the same as a `null`. It is not possible
+ to change only one of the two quotas.
+ parameters:
+ - name: id
+ in: query
+ required: true
+ description: "The exact bucket identifier, a 32 bytes hexadecimal string"
+ example: "b4018dc61b27ccb5c64ec1b24f53454bbbd180697c758c4d47a22a8921864a87"
+ schema:
+ type: string
+ requestBody:
+ description: |
+ Requested changes on the bucket. Both root fields are optionals.
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ websiteAccess:
+ type: object
+ properties:
+ enabled:
+ type: boolean
+ example: true
+ indexDocument:
+ type: string
+ example: "index.html"
+ errorDocument:
+ type: string
+ example: "error/400.html"
+ quotas:
+ type: object
+ properties:
+ maxSize:
+ type: integer
+ format: int64
+ nullable: true
+ example: 19029801
+ maxObjects:
+ type: integer
+ format: int64
+ nullable: true
+ example: null
+
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bad request, check your body."
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+ /CleanupIncompleteUploads:
+ post:
+ tags:
+ - Bucket
+ operationId: "CleanupIncompleteUploads"
+ summary: "Cleanup incomplete uploads in a bucket"
+ description: |
+ Cleanup all incomplete uploads in a bucket that are older than a specified number of seconds
+ requestBody:
+ description: |
+ Bucket id and minimum age of uploads to delete (in seconds)
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [bucketId, olderThanSecs]
+ properties:
+ bucketId:
+ type: string
+ example: "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b"
+ olderThanSecs:
+ type: integer
+ example: "3600"
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "The payload is not formatted correctly"
+ '200':
+ description: "The bucket was cleaned up successfully"
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ uploadsDeleted:
+ type: integer
+ example: 12
+
+ /AllowBucketKey:
+ post:
+ tags:
+ - Permissions
+ operationId: "AllowBucketKey"
+ summary: "Allow key"
+ description: |
+ ⚠️ **DISCLAIMER**: Garage's developers are aware that this endpoint has an unconventional semantic. Be extra careful when implementing it, its behavior is not obvious.
+
+ Allows a key to do read/write/owner operations on a bucket.
+
+ Flags in permissions which have the value true will be activated. Other flags will remain unchanged (ie. they will keep their internal value).
+
+ For example, if you set read to true, the key will be allowed to read the bucket.
+ If you set it to false, the key will keeps its previous read permission.
+ If you want to disallow read for the key, check the DenyBucketKey operation.
+
+ requestBody:
+ description: |
+ Aliases to put on the new bucket
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ bucketId, accessKeyId, permissions ]
+ properties:
+ bucketId:
+ type: string
+ example: "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b"
+ accessKeyId:
+ type: string
+ example: "GK31c2f218a2e44f485b94239e"
+ permissions:
+ type: object
+ required: [ read, write, owner ]
+ properties:
+ read:
+ type: boolean
+ example: true
+ write:
+ type: boolean
+ example: true
+ owner:
+ type: boolean
+ example: true
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bad request, check your request body"
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+ /DenyBucketKey:
+ post:
+ tags:
+ - Permissions
+ operationId: "DenyBucketKey"
+ summary: "Deny key"
+ description: |
+ ⚠️ **DISCLAIMER**: Garage's developers are aware that this endpoint has an unconventional semantic. Be extra careful when implementing it, its behavior is not obvious.
+
+ Denies a key from doing read/write/owner operations on a bucket.
+
+ Flags in permissions which have the value true will be deactivated. Other flags will remain unchanged.
+
+ For example, if you set read to true, the key will be denied from reading.
+ If you set read to false, the key will keep its previous permissions.
+ If you want the key to have the reading permission, check the AllowBucketKey operation.
+
+ requestBody:
+ description: |
+ Aliases to put on the new bucket
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [ bucketId, accessKeyId, permissions ]
+ properties:
+ bucketId:
+ type: string
+ example: "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b"
+ accessKeyId:
+ type: string
+ example: "GK31c2f218a2e44f485b94239e"
+ permissions:
+ type: object
+ required: [ read, write, owner ]
+ properties:
+ read:
+ type: boolean
+ example: true
+ write:
+ type: boolean
+ example: true
+ owner:
+ type: boolean
+ example: true
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bad request, check your request body"
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+ /AddBucketAlias:
+ post:
+ tags:
+ - Bucket aliases
+ operationId: "AddBucketAlias"
+ summary: "Add an alias to a bucket"
+ description: |
+ Add an alias for the target bucket.
+ This can be a local alias if `accessKeyId` is specified,
+ or a global alias otherwise.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [bucketId]
+ properties:
+ bucketId:
+ type: string
+ example: e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b
+ globalAlias:
+ type: string
+ localAlias:
+ type: string
+ example: my_documents
+ accessKeyId:
+ type: string
+ example: GK31c2f218a2e44f485b94239e
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bad request, check your request body"
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+ /RemoveBucketAlias:
+ post:
+ tags:
+ - Bucket aliases
+ operationId: "RemoveBucketAlias"
+ summary: "Remove an alias from a bucket"
+ description: |
+ Remove an alias for the target bucket.
+ This can be a local alias if `accessKeyId` is specified,
+ or a global alias otherwise.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [bucketId]
+ properties:
+ bucketId:
+ type: string
+ example: e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b
+ globalAlias:
+ type: string
+ example: the_bucket
+ localAlias:
+ type: string
+ accessKeyId:
+ type: string
+ responses:
+ '500':
+ description: "The server can not handle your request. Check your connectivity with the rest of the cluster."
+ '400':
+ description: "Bad request, check your request body"
+ '404':
+ description: "Bucket not found"
+ '200':
+ description: Returns exhaustive information about the bucket
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/BucketInfo'
+
+components:
+ securitySchemes:
+ bearerAuth:
+ type: http
+ scheme: bearer
+ schemas:
+ NodeNetworkInfo:
+ type: object
+ required: [ addr, isUp, lastSeenSecsAgo, hostname ]
+ properties:
+ id:
+ type: string
+ example: "6a8e08af2aab1083ebab9b22165ea8b5b9d333b60a39ecd504e85cc1f432c36f"
+ addr:
+ type: string
+ example: "10.0.0.11:3901"
+ isUp:
+ type: boolean
+ example: true
+ lastSeenSecsAgo:
+ type: integer
+ nullable: true
+ example: 9
+ hostname:
+ type: string
+ example: "node1"
+ NodeClusterInfo:
+ type: object
+ required: [ id, zone, tags ]
+ properties:
+ zone:
+ type: string
+ example: dc1
+ capacity:
+ type: integer
+ format: int64
+ nullable: true
+ example: 4
+ tags:
+ type: array
+ description: |
+ User defined tags, put whatever makes sense for you, these tags are not interpreted by Garage
+ example:
+ - gateway
+ - fast
+ items:
+ type: string
+ NodeRoleChange:
+ oneOf:
+ - $ref: '#/components/schemas/NodeRoleRemove'
+ - $ref: '#/components/schemas/NodeRoleUpdate'
+ NodeRoleRemove:
+ type: object
+ required: [ id, remove ]
+ properties:
+ id:
+ type: string
+ example: "6a8e08af2aab1083ebab9b22165ea8b5b9d333b60a39ecd504e85cc1f432c36f"
+ remove:
+ type: boolean
+ example: true
+ NodeRoleUpdate:
+ type: object
+ required: [ id, zone, capacity, tags ]
+ properties:
+ id:
+ type: string
+ example: "6a8e08af2aab1083ebab9b22165ea8b5b9d333b60a39ecd504e85cc1f432c36f"
+ zone:
+ type: string
+ example: "dc1"
+ capacity:
+ type: integer
+ format: int64
+ nullable: true
+ example: 150000000000
+ tags:
+ type: array
+ items:
+ type: string
+ example:
+ - gateway
+ - fast
+
+ ClusterLayout:
+ type: object
+ required: [ version, roles, stagedRoleChanges ]
+ properties:
+ version:
+ type: integer
+ example: 12
+ roles:
+ type: array
+ example:
+ - id: "ec79480e0ce52ae26fd00c9da684e4fa56658d9c64cdcecb094e936de0bfe71f"
+ zone: "madrid"
+ capacity: 300000000000
+ tags:
+ - fast
+ - amd64
+ - id: "4a6ae5a1d0d33bf895f5bb4f0a418b7dc94c47c0dd2eb108d1158f3c8f60b0ff"
+ zone: "geneva"
+ capacity: 700000000000
+ tags:
+ - arm64
+ items:
+ $ref: '#/components/schemas/NodeClusterInfo'
+ stagedRoleChanges:
+ type: array
+ example:
+ - id: "e2ee7984ee65b260682086ec70026165903c86e601a4a5a501c1900afe28d84b"
+ zone: "geneva"
+ capacity: 800000000000
+ tags:
+ - gateway
+ - id: "4a6ae5a1d0d33bf895f5bb4f0a418b7dc94c47c0dd2eb108d1158f3c8f60b0ff"
+ remove: true
+ items:
+ $ref: '#/components/schemas/NodeRoleChange'
+ LayoutVersion:
+ type: object
+ required: [ version ]
+ properties:
+ version:
+ type: integer
+ #format: int64
+ example: 13
+
+ KeyInfo:
+ type: object
+ properties:
+ name:
+ type: string
+ example: "test-key"
+ accessKeyId:
+ type: string
+ example: "GK31c2f218a2e44f485b94239e"
+ secretAccessKey:
+ type: string
+ nullable: true
+ example: "b892c0665f0ada8a4755dae98baa3b133590e11dae3bcc1f9d769d67f16c3835"
+ permissions:
+ type: object
+ properties:
+ createBucket:
+ type: boolean
+ example: false
+ buckets:
+ type: array
+ items:
+ type: object
+ properties:
+ id:
+ type: string
+ example: "70dc3bed7fe83a75e46b66e7ddef7d56e65f3c02f9f80b6749fb97eccb5e1033"
+ globalAliases:
+ type: array
+ items:
+ type: string
+ example: "my-bucket"
+ localAliases:
+ type: array
+ items:
+ type: string
+ example: "GK31c2f218a2e44f485b94239e:localname"
+ permissions:
+ type: object
+ properties:
+ read:
+ type: boolean
+ example: true
+ write:
+ type: boolean
+ example: true
+ owner:
+ type: boolean
+ example: false
+ BucketInfo:
+ type: object
+ properties:
+ id:
+ type: string
+ example: afa8f0a22b40b1247ccd0affb869b0af5cff980924a20e4b5e0720a44deb8d39
+ globalAliases:
+ type: array
+ items:
+ type: string
+ example: "my_documents"
+ websiteAccess:
+ type: boolean
+ example: true
+ websiteConfig:
+ type: object
+ nullable: true
+ properties:
+ indexDocument:
+ type: string
+ example: "index.html"
+ errorDocument:
+ type: string
+ example: "error/400.html"
+ keys:
+ type: array
+ items:
+ $ref: '#/components/schemas/BucketKeyInfo'
+ objects:
+ type: integer
+ format: int64
+ example: 14827
+ bytes:
+ type: integer
+ format: int64
+ example: 13189855625
+ unfinishedUploads:
+ type: integer
+ example: 0
+ quotas:
+ type: object
+ properties:
+ maxSize:
+ nullable: true
+ type: integer
+ format: int64
+ example: null
+ maxObjects:
+ nullable: true
+ type: integer
+ format: int64
+ example: null
+
+
+ BucketKeyInfo:
+ type: object
+ properties:
+ accessKeyId:
+ type: string
+ name:
+ type: string
+ permissions:
+ type: object
+ properties:
+ read:
+ type: boolean
+ example: true
+ write:
+ type: boolean
+ example: true
+ owner:
+ type: boolean
+ example: true
+ bucketLocalAliases:
+ type: array
+ items:
+ type: string
+ example: "my_documents"
+
+
+security:
+ - bearerAuth: []
+
+servers:
+ - description: A local server
+ url: http://localhost:3903/v2/
diff --git a/doc/drafts/admin-api.md b/doc/drafts/admin-api.md
index a614af58..029c7ddd 100644
--- a/doc/drafts/admin-api.md
+++ b/doc/drafts/admin-api.md
@@ -13,8 +13,9 @@ We will bump the version numbers prefixed to each API endpoint each time the syn
or semantics change, meaning that code that relies on these endpoints will break
when changes are introduced.
-The Garage administration API was introduced in version 0.7.2, this document
-does not apply to older versions of Garage.
+The Garage administration API was introduced in version 0.7.2, and was
+changed several times.
+This document applies only to the Garage v2 API (starting with Garage v2.0.0).
## Access control
@@ -52,11 +53,18 @@ Returns an HTTP status 200 if the node is ready to answer user's requests,
and an HTTP status 503 (Service Unavailable) if there are some partitions
for which a quorum of nodes is not available.
A simple textual message is also returned in a body with content-type `text/plain`.
-See `/v1/health` for an API that also returns JSON output.
+See `/v2/GetClusterHealth` for an API that also returns JSON output.
+
+### Other special endpoints
+
+#### CheckDomain `GET /check?domain=`
+
+Checks whether this Garage cluster serves a website for domain ``.
+Returns HTTP 200 Ok if yes, or HTTP 4xx if no website is available for this domain.
### Cluster operations
-#### GetClusterStatus `GET /v1/status`
+#### GetClusterStatus `GET /v2/GetClusterStatus`
Returns the cluster's current status in JSON, including:
@@ -70,7 +78,7 @@ Example response body:
```json
{
"node": "b10c110e4e854e5aa3f4637681befac755154b20059ec163254ddbfae86b09df",
- "garageVersion": "v1.0.1",
+ "garageVersion": "v2.0.0",
"garageFeatures": [
"k2v",
"lmdb",
@@ -169,7 +177,7 @@ Example response body:
}
```
-#### GetClusterHealth `GET /v1/health`
+#### GetClusterHealth `GET /v2/GetClusterHealth`
Returns the cluster's current health in JSON format, with the following variables:
@@ -202,7 +210,7 @@ Example response body:
}
```
-#### ConnectClusterNodes `POST /v1/connect`
+#### ConnectClusterNodes `POST /v2/ConnectClusterNodes`
Instructs this Garage node to connect to other Garage nodes at specified addresses.
@@ -232,7 +240,7 @@ Example response:
]
```
-#### GetClusterLayout `GET /v1/layout`
+#### GetClusterLayout `GET /v2/GetClusterLayout`
Returns the cluster's current layout in JSON, including:
@@ -293,7 +301,7 @@ Example response body:
}
```
-#### UpdateClusterLayout `POST /v1/layout`
+#### UpdateClusterLayout `POST /v2/UpdateClusterLayout`
Send modifications to the cluster layout. These modifications will
be included in the staged role changes, visible in subsequent calls
@@ -330,7 +338,7 @@ This returns the new cluster layout with the proposed staged changes,
as returned by GetClusterLayout.
-#### ApplyClusterLayout `POST /v1/layout/apply`
+#### ApplyClusterLayout `POST /v2/ApplyClusterLayout`
Applies to the cluster the layout changes currently registered as
staged layout changes.
@@ -350,7 +358,7 @@ existing layout in the cluster.
This returns the message describing all the calculations done to compute the new
layout, as well as the description of the layout as returned by GetClusterLayout.
-#### RevertClusterLayout `POST /v1/layout/revert`
+#### RevertClusterLayout `POST /v2/RevertClusterLayout`
Clears all of the staged layout changes.
@@ -374,7 +382,7 @@ as returned by GetClusterLayout.
### Access key operations
-#### ListKeys `GET /v1/key`
+#### ListKeys `GET /v2/ListKeys`
Returns all API access keys in the cluster.
@@ -393,8 +401,8 @@ Example response:
]
```
-#### GetKeyInfo `GET /v1/key?id=`
-#### GetKeyInfo `GET /v1/key?search=`
+#### GetKeyInfo `GET /v2/GetKeyInfo?id=`
+#### GetKeyInfo `GET /v2/GetKeyInfo?search=`
Returns information about the requested API access key.
@@ -468,7 +476,7 @@ Example response:
}
```
-#### CreateKey `POST /v1/key`
+#### CreateKey `POST /v2/CreateKey`
Creates a new API access key.
@@ -483,7 +491,7 @@ Request body format:
This returns the key info, including the created secret key,
in the same format as the result of GetKeyInfo.
-#### ImportKey `POST /v1/key/import`
+#### ImportKey `POST /v2/ImportKey`
Imports an existing API key.
This will check that the imported key is in the valid format, i.e.
@@ -501,7 +509,7 @@ Request body format:
This returns the key info in the same format as the result of GetKeyInfo.
-#### UpdateKey `POST /v1/key?id=`
+#### UpdateKey `POST /v2/UpdateKey?id=`
Updates information about the specified API access key.
@@ -523,14 +531,14 @@ The possible flags in `allow` and `deny` are: `createBucket`.
This returns the key info in the same format as the result of GetKeyInfo.
-#### DeleteKey `DELETE /v1/key?id=`
+#### DeleteKey `POST /v2/DeleteKey?id=`
Deletes an API access key.
### Bucket operations
-#### ListBuckets `GET /v1/bucket`
+#### ListBuckets `GET /v2/ListBuckets`
Returns all storage buckets in the cluster.
@@ -572,8 +580,8 @@ Example response:
]
```
-#### GetBucketInfo `GET /v1/bucket?id=`
-#### GetBucketInfo `GET /v1/bucket?globalAlias=`
+#### GetBucketInfo `GET /v2/GetBucketInfo?id=`
+#### GetBucketInfo `GET /v2/GetBucketInfo?globalAlias=`
Returns information about the requested storage bucket.
@@ -616,7 +624,7 @@ Example response:
}
```
-#### CreateBucket `POST /v1/bucket`
+#### CreateBucket `POST /v2/CreateBucket`
Creates a new storage bucket.
@@ -656,7 +664,7 @@ or no alias at all.
Technically, you can also specify both `globalAlias` and `localAlias` and that would create
two aliases, but I don't see why you would want to do that.
-#### UpdateBucket `PUT /v1/bucket?id=`
+#### UpdateBucket `POST /v2/UpdateBucket?id=`
Updates configuration of the given bucket.
@@ -688,16 +696,38 @@ In `quotas`: new values of `maxSize` and `maxObjects` must both be specified, or
to remove the quotas. An absent value will be considered the same as a `null`. It is not possible
to change only one of the two quotas.
-#### DeleteBucket `DELETE /v1/bucket?id=`
+#### DeleteBucket `POST /v2/DeleteBucket?id=`
Deletes a storage bucket. A bucket cannot be deleted if it is not empty.
Warning: this will delete all aliases associated with the bucket!
+#### CleanupIncompleteUploads `POST /v2/CleanupIncompleteUploads`
+
+Cleanup all incomplete uploads in a bucket that are older than a specified number
+of seconds.
+
+Request body format:
+
+```json
+{
+ "bucketId": "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b",
+ "olderThanSecs": 3600
+}
+```
+
+Response format
+
+```json
+{
+ "uploadsDeleted": 12
+}
+```
+
### Operations on permissions for keys on buckets
-#### BucketAllowKey `POST /v1/bucket/allow`
+#### AllowBucketKey `POST /v2/AllowBucketKey`
Allows a key to do read/write/owner operations on a bucket.
@@ -718,7 +748,7 @@ Request body format:
Flags in `permissions` which have the value `true` will be activated.
Other flags will remain unchanged.
-#### BucketDenyKey `POST /v1/bucket/deny`
+#### DenyBucketKey `POST /v2/DenyBucketKey`
Denies a key from doing read/write/owner operations on a bucket.
@@ -742,19 +772,35 @@ Other flags will remain unchanged.
### Operations on bucket aliases
-#### GlobalAliasBucket `PUT /v1/bucket/alias/global?id=&alias=`
+#### AddBucketAlias `POST /v2/AddBucketAlias`
-Empty body. Creates a global alias for a bucket.
+Creates an alias for a bucket in the namespace of a specific access key.
+To create a global alias, specify the `globalAlias` field.
+To create a local alias, specify the `localAlias` and `accessKeyId` fields.
-#### GlobalUnaliasBucket `DELETE /v1/bucket/alias/global?id=&alias=`
+Request body format:
-Removes a global alias for a bucket.
+```json
+{
+ "bucketId": "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b",
+ "globalAlias": "my-bucket"
+}
+```
-#### LocalAliasBucket `PUT /v1/bucket/alias/local?id=&accessKeyId=&alias=`
+or:
-Empty body. Creates a local alias for a bucket in the namespace of a specific access key.
+```json
+{
+ "bucketId": "e6a14cd6a27f48684579ec6b381c078ab11697e6bc8513b72b2f5307e25fff9b",
+ "accessKeyId": "GK31c2f218a2e44f485b94239e",
+ "localAlias": "my-bucket"
+}
+```
-#### LocalUnaliasBucket `DELETE /v1/bucket/alias/local?id=&accessKeyId&alias=`
+#### RemoveBucketAlias `POST /v2/RemoveBucketAlias`
-Removes a local alias for a bucket in the namespace of a specific access key.
+Removes an alias for a bucket in the namespace of a specific access key.
+To remove a global alias, specify the `globalAlias` field.
+To remove a local alias, specify the `localAlias` and `accessKeyId` fields.
+Request body format: same as AddBucketAlias.
diff --git a/src/api/admin/Cargo.toml b/src/api/admin/Cargo.toml
index adddf306..9ac099e8 100644
--- a/src/api/admin/Cargo.toml
+++ b/src/api/admin/Cargo.toml
@@ -14,7 +14,9 @@ path = "lib.rs"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+format_table.workspace = true
garage_model.workspace = true
+garage_block.workspace = true
garage_table.workspace = true
garage_util.workspace = true
garage_rpc.workspace = true
@@ -22,8 +24,10 @@ garage_api_common.workspace = true
argon2.workspace = true
async-trait.workspace = true
+bytesize.workspace = true
err-derive.workspace = true
hex.workspace = true
+paste.workspace = true
tracing.workspace = true
futures.workspace = true
diff --git a/src/api/admin/api.rs b/src/api/admin/api.rs
new file mode 100644
index 00000000..97cde158
--- /dev/null
+++ b/src/api/admin/api.rs
@@ -0,0 +1,876 @@
+use std::collections::HashMap;
+use std::convert::TryFrom;
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use paste::paste;
+use serde::{Deserialize, Serialize};
+
+use garage_rpc::*;
+
+use garage_model::garage::Garage;
+
+use garage_api_common::common_error::CommonErrorDerivative;
+use garage_api_common::helpers::is_default;
+
+use crate::api_server::{AdminRpc, AdminRpcResponse};
+use crate::error::Error;
+use crate::macros::*;
+use crate::{Admin, RequestHandler};
+
+// This generates the following:
+//
+// - An enum AdminApiRequest that contains a variant for all endpoints
+//
+// - An enum AdminApiResponse that contains a variant for all non-special endpoints.
+// This enum is serialized in api_server.rs, without the enum tag,
+// which gives directly the JSON response corresponding to the API call.
+// This enum does not implement Deserialize as its meaning can be ambiguous.
+//
+// - An enum TaggedAdminApiResponse that contains the same variants, but
+// serializes as a tagged enum. This allows it to be transmitted through
+// Garage RPC and deserialized correctly upon receival.
+// Conversion from untagged to tagged can be done using the `.tagged()` method.
+//
+// - AdminApiRequest::name() that returns the name of the endpoint
+//
+// - impl EndpointHandler for AdminApiHandler, that uses the impl EndpointHandler
+// of each request type below for non-special endpoints
+admin_endpoints![
+ // Special endpoints of the Admin API
+ @special Options,
+ @special CheckDomain,
+ @special Health,
+ @special Metrics,
+
+ // Cluster operations
+ GetClusterStatus,
+ GetClusterHealth,
+ ConnectClusterNodes,
+ GetClusterLayout,
+ UpdateClusterLayout,
+ ApplyClusterLayout,
+ RevertClusterLayout,
+
+ // Access key operations
+ ListKeys,
+ GetKeyInfo,
+ CreateKey,
+ ImportKey,
+ UpdateKey,
+ DeleteKey,
+
+ // Bucket operations
+ ListBuckets,
+ GetBucketInfo,
+ CreateBucket,
+ UpdateBucket,
+ DeleteBucket,
+ CleanupIncompleteUploads,
+
+ // Operations on permissions for keys on buckets
+ AllowBucketKey,
+ DenyBucketKey,
+
+ // Operations on bucket aliases
+ AddBucketAlias,
+ RemoveBucketAlias,
+
+ // Node operations
+ CreateMetadataSnapshot,
+ GetNodeStatistics,
+ GetClusterStatistics,
+ LaunchRepairOperation,
+
+ // Worker operations
+ ListWorkers,
+ GetWorkerInfo,
+ GetWorkerVariable,
+ SetWorkerVariable,
+
+ // Block operations
+ ListBlockErrors,
+ GetBlockInfo,
+ RetryBlockResync,
+ PurgeBlocks,
+];
+
+local_admin_endpoints![
+ // Node operations
+ CreateMetadataSnapshot,
+ GetNodeStatistics,
+ LaunchRepairOperation,
+ // Background workers
+ ListWorkers,
+ GetWorkerInfo,
+ GetWorkerVariable,
+ SetWorkerVariable,
+ // Block operations
+ ListBlockErrors,
+ GetBlockInfo,
+ RetryBlockResync,
+ PurgeBlocks,
+];
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MultiRequest {
+ pub node: String,
+ pub body: RB,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MultiResponse {
+ pub success: HashMap,
+ pub error: HashMap,
+}
+
+// **********************************************
+// Special endpoints
+//
+// These endpoints don't have associated *Response structs
+// because they directly produce an http::Response
+// **********************************************
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct OptionsRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CheckDomainRequest {
+ pub domain: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct HealthRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MetricsRequest;
+
+// **********************************************
+// Cluster operations
+// **********************************************
+
+// ---- GetClusterStatus ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetClusterStatusRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetClusterStatusResponse {
+ pub node: String,
+ pub garage_version: String,
+ pub garage_features: Option>,
+ pub rust_version: String,
+ pub db_engine: String,
+ pub layout_version: u64,
+ pub nodes: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct NodeResp {
+ pub id: String,
+ pub role: Option,
+ pub addr: Option,
+ pub hostname: Option,
+ pub is_up: bool,
+ pub last_seen_secs_ago: Option,
+ pub draining: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data_partition: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub metadata_partition: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NodeRoleResp {
+ pub id: String,
+ pub zone: String,
+ pub capacity: Option,
+ pub tags: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FreeSpaceResp {
+ pub available: u64,
+ pub total: u64,
+}
+
+// ---- GetClusterHealth ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetClusterHealthRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetClusterHealthResponse {
+ pub status: String,
+ pub known_nodes: usize,
+ pub connected_nodes: usize,
+ pub storage_nodes: usize,
+ pub storage_nodes_ok: usize,
+ pub partitions: usize,
+ pub partitions_quorum: usize,
+ pub partitions_all_ok: usize,
+}
+
+// ---- ConnectClusterNodes ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConnectClusterNodesRequest(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConnectClusterNodesResponse(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ConnectNodeResponse {
+ pub success: bool,
+ pub error: Option,
+}
+
+// ---- GetClusterLayout ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetClusterLayoutRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetClusterLayoutResponse {
+ pub version: u64,
+ pub roles: Vec,
+ pub staged_role_changes: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NodeRoleChange {
+ pub id: String,
+ #[serde(flatten)]
+ pub action: NodeRoleChangeEnum,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum NodeRoleChangeEnum {
+ #[serde(rename_all = "camelCase")]
+ Remove { remove: bool },
+ #[serde(rename_all = "camelCase")]
+ Update {
+ zone: String,
+ capacity: Option,
+ tags: Vec,
+ },
+}
+
+// ---- UpdateClusterLayout ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateClusterLayoutRequest(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateClusterLayoutResponse(pub GetClusterLayoutResponse);
+
+// ---- ApplyClusterLayout ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApplyClusterLayoutRequest {
+ pub version: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApplyClusterLayoutResponse {
+ pub message: Vec,
+ pub layout: GetClusterLayoutResponse,
+}
+
+// ---- RevertClusterLayout ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RevertClusterLayoutRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RevertClusterLayoutResponse(pub GetClusterLayoutResponse);
+
+// **********************************************
+// Access key operations
+// **********************************************
+
+// ---- ListKeys ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ListKeysRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ListKeysResponse(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListKeysResponseItem {
+ pub id: String,
+ pub name: String,
+}
+
+// ---- GetKeyInfo ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetKeyInfoRequest {
+ pub id: Option,
+ pub search: Option,
+ pub show_secret_key: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetKeyInfoResponse {
+ pub name: String,
+ pub access_key_id: String,
+ #[serde(skip_serializing_if = "is_default")]
+ pub secret_access_key: Option,
+ pub permissions: KeyPerm,
+ pub buckets: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct KeyPerm {
+ #[serde(default)]
+ pub create_bucket: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct KeyInfoBucketResponse {
+ pub id: String,
+ pub global_aliases: Vec,
+ pub local_aliases: Vec,
+ pub permissions: ApiBucketKeyPerm,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct ApiBucketKeyPerm {
+ #[serde(default)]
+ pub read: bool,
+ #[serde(default)]
+ pub write: bool,
+ #[serde(default)]
+ pub owner: bool,
+}
+
+// ---- CreateKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateKeyRequest {
+ pub name: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CreateKeyResponse(pub GetKeyInfoResponse);
+
+// ---- ImportKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ImportKeyRequest {
+ pub access_key_id: String,
+ pub secret_access_key: String,
+ pub name: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ImportKeyResponse(pub GetKeyInfoResponse);
+
+// ---- UpdateKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateKeyRequest {
+ pub id: String,
+ pub body: UpdateKeyRequestBody,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateKeyResponse(pub GetKeyInfoResponse);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateKeyRequestBody {
+ pub name: Option,
+ pub allow: Option,
+ pub deny: Option,
+}
+
+// ---- DeleteKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DeleteKeyRequest {
+ pub id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DeleteKeyResponse;
+
+// **********************************************
+// Bucket operations
+// **********************************************
+
+// ---- ListBuckets ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ListBucketsRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ListBucketsResponse(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListBucketsResponseItem {
+ pub id: String,
+ pub global_aliases: Vec,
+ pub local_aliases: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BucketLocalAlias {
+ pub access_key_id: String,
+ pub alias: String,
+}
+
+// ---- GetBucketInfo ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetBucketInfoRequest {
+ pub id: Option,
+ pub global_alias: Option,
+ pub search: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetBucketInfoResponse {
+ pub id: String,
+ pub global_aliases: Vec,
+ pub website_access: bool,
+ #[serde(default)]
+ pub website_config: Option,
+ pub keys: Vec,
+ pub objects: i64,
+ pub bytes: i64,
+ pub unfinished_uploads: i64,
+ pub unfinished_multipart_uploads: i64,
+ pub unfinished_multipart_upload_parts: i64,
+ pub unfinished_multipart_upload_bytes: i64,
+ pub quotas: ApiBucketQuotas,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetBucketInfoWebsiteResponse {
+ pub index_document: String,
+ pub error_document: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GetBucketInfoKey {
+ pub access_key_id: String,
+ pub name: String,
+ pub permissions: ApiBucketKeyPerm,
+ pub bucket_local_aliases: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ApiBucketQuotas {
+ pub max_size: Option,
+ pub max_objects: Option,
+}
+
+// ---- CreateBucket ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateBucketRequest {
+ pub global_alias: Option,
+ pub local_alias: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CreateBucketResponse(pub GetBucketInfoResponse);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateBucketLocalAlias {
+ pub access_key_id: String,
+ pub alias: String,
+ #[serde(default)]
+ pub allow: ApiBucketKeyPerm,
+}
+
+// ---- UpdateBucket ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateBucketRequest {
+ pub id: String,
+ pub body: UpdateBucketRequestBody,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpdateBucketResponse(pub GetBucketInfoResponse);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateBucketRequestBody {
+ pub website_access: Option,
+ pub quotas: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct UpdateBucketWebsiteAccess {
+ pub enabled: bool,
+ pub index_document: Option,
+ pub error_document: Option,
+}
+
+// ---- DeleteBucket ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DeleteBucketRequest {
+ pub id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DeleteBucketResponse;
+
+// ---- CleanupIncompleteUploads ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CleanupIncompleteUploadsRequest {
+ pub bucket_id: String,
+ pub older_than_secs: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CleanupIncompleteUploadsResponse {
+ pub uploads_deleted: u64,
+}
+
+// **********************************************
+// Operations on permissions for keys on buckets
+// **********************************************
+
+// ---- AllowBucketKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AllowBucketKeyRequest(pub BucketKeyPermChangeRequest);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AllowBucketKeyResponse(pub GetBucketInfoResponse);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BucketKeyPermChangeRequest {
+ pub bucket_id: String,
+ pub access_key_id: String,
+ pub permissions: ApiBucketKeyPerm,
+}
+
+// ---- DenyBucketKey ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DenyBucketKeyRequest(pub BucketKeyPermChangeRequest);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DenyBucketKeyResponse(pub GetBucketInfoResponse);
+
+// **********************************************
+// Operations on bucket aliases
+// **********************************************
+
+// ---- AddBucketAlias ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AddBucketAliasRequest {
+ pub bucket_id: String,
+ #[serde(flatten)]
+ pub alias: BucketAliasEnum,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AddBucketAliasResponse(pub GetBucketInfoResponse);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum BucketAliasEnum {
+ #[serde(rename_all = "camelCase")]
+ Global { global_alias: String },
+ #[serde(rename_all = "camelCase")]
+ Local {
+ local_alias: String,
+ access_key_id: String,
+ },
+}
+
+// ---- RemoveBucketAlias ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RemoveBucketAliasRequest {
+ pub bucket_id: String,
+ #[serde(flatten)]
+ pub alias: BucketAliasEnum,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RemoveBucketAliasResponse(pub GetBucketInfoResponse);
+
+// **********************************************
+// Node operations
+// **********************************************
+
+// ---- CreateMetadataSnapshot ----
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct LocalCreateMetadataSnapshotRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalCreateMetadataSnapshotResponse;
+
+// ---- GetNodeStatistics ----
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct LocalGetNodeStatisticsRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalGetNodeStatisticsResponse {
+ pub freeform: String,
+}
+
+// ---- GetClusterStatistics ----
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct GetClusterStatisticsRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GetClusterStatisticsResponse {
+ pub freeform: String,
+}
+
+// ---- LaunchRepairOperation ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalLaunchRepairOperationRequest {
+ pub repair_type: RepairType,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RepairType {
+ Tables,
+ Blocks,
+ Versions,
+ MultipartUploads,
+ BlockRefs,
+ BlockRc,
+ Rebalance,
+ Scrub(ScrubCommand),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum ScrubCommand {
+ Start,
+ Pause,
+ Resume,
+ Cancel,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalLaunchRepairOperationResponse;
+
+// **********************************************
+// Worker operations
+// **********************************************
+
+// ---- GetWorkerList ----
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalListWorkersRequest {
+ #[serde(default)]
+ pub busy_only: bool,
+ #[serde(default)]
+ pub error_only: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalListWorkersResponse(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkerInfoResp {
+ pub id: u64,
+ pub name: String,
+ pub state: WorkerStateResp,
+ pub errors: u64,
+ pub consecutive_errors: u64,
+ pub last_error: Option,
+ pub tranquility: Option,
+ pub progress: Option,
+ pub queue_length: Option,
+ pub persistent_errors: Option,
+ pub freeform: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum WorkerStateResp {
+ Busy,
+ Throttled { duration_secs: f32 },
+ Idle,
+ Done,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkerLastError {
+ pub message: String,
+ pub secs_ago: u64,
+}
+
+// ---- GetWorkerList ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalGetWorkerInfoRequest {
+ pub id: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalGetWorkerInfoResponse(pub WorkerInfoResp);
+
+// ---- GetWorkerVariable ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalGetWorkerVariableRequest {
+ pub variable: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalGetWorkerVariableResponse(pub HashMap);
+
+// ---- SetWorkerVariable ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalSetWorkerVariableRequest {
+ pub variable: String,
+ pub value: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalSetWorkerVariableResponse {
+ pub variable: String,
+ pub value: String,
+}
+
+// **********************************************
+// Block operations
+// **********************************************
+
+// ---- ListBlockErrors ----
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct LocalListBlockErrorsRequest;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalListBlockErrorsResponse(pub Vec);
+
+#[derive(Serialize, Deserialize, Clone, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct BlockError {
+ pub block_hash: String,
+ pub refcount: u64,
+ pub error_count: u64,
+ pub last_try_secs_ago: u64,
+ pub next_try_in_secs: u64,
+}
+
+// ---- GetBlockInfo ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalGetBlockInfoRequest {
+ pub block_hash: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalGetBlockInfoResponse {
+ pub block_hash: String,
+ pub refcount: u64,
+ pub versions: Vec,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BlockVersion {
+ pub version_id: String,
+ pub deleted: bool,
+ pub garbage_collected: bool,
+ pub backlink: Option,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum BlockVersionBacklink {
+ Object {
+ bucket_id: String,
+ key: String,
+ },
+ Upload {
+ upload_id: String,
+ upload_deleted: bool,
+ upload_garbage_collected: bool,
+ bucket_id: Option,
+ key: Option,
+ },
+}
+
+// ---- RetryBlockResync ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum LocalRetryBlockResyncRequest {
+ #[serde(rename_all = "camelCase")]
+ All { all: bool },
+ #[serde(rename_all = "camelCase")]
+ Blocks { block_hashes: Vec },
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalRetryBlockResyncResponse {
+ pub count: u64,
+}
+
+// ---- PurgeBlocks ----
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalPurgeBlocksRequest(pub Vec);
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct LocalPurgeBlocksResponse {
+ pub blocks_purged: u64,
+ pub objects_deleted: u64,
+ pub uploads_deleted: u64,
+ pub versions_deleted: u64,
+}
diff --git a/src/api/admin/api_server.rs b/src/api/admin/api_server.rs
index 6f0c474f..37574dcf 100644
--- a/src/api/admin/api_server.rs
+++ b/src/api/admin/api_server.rs
@@ -1,248 +1,162 @@
-use std::collections::HashMap;
+use std::borrow::Cow;
use std::sync::Arc;
use argon2::password_hash::PasswordHash;
-use http::header::{ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN, ALLOW};
-use hyper::{body::Incoming as IncomingBody, Request, Response, StatusCode};
+use http::header::{HeaderValue, ACCESS_CONTROL_ALLOW_ORIGIN, AUTHORIZATION};
+use hyper::{body::Incoming as IncomingBody, Request, Response};
+use serde::{Deserialize, Serialize};
use tokio::sync::watch;
use opentelemetry::trace::SpanRef;
#[cfg(feature = "metrics")]
use opentelemetry_prometheus::PrometheusExporter;
-#[cfg(feature = "metrics")]
-use prometheus::{Encoder, TextEncoder};
use garage_model::garage::Garage;
-use garage_rpc::system::ClusterHealthStatus;
+use garage_rpc::{Endpoint as RpcEndpoint, *};
+use garage_util::background::BackgroundRunner;
use garage_util::error::Error as GarageError;
use garage_util::socket_address::UnixOrTCPSocketAddress;
use garage_api_common::generic_server::*;
use garage_api_common::helpers::*;
-use crate::bucket::*;
-use crate::cluster::*;
+use crate::api::*;
use crate::error::*;
-use crate::key::*;
use crate::router_v0;
-use crate::router_v1::{Authorization, Endpoint};
+use crate::router_v1;
+use crate::Authorization;
+use crate::RequestHandler;
+
+// ---- FOR RPC ----
+
+pub const ADMIN_RPC_PATH: &str = "garage_api/admin/rpc.rs/Rpc";
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum AdminRpc {
+ Proxy(AdminApiRequest),
+ Internal(LocalAdminApiRequest),
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum AdminRpcResponse {
+ ProxyApiOkResponse(TaggedAdminApiResponse),
+ InternalApiOkResponse(LocalAdminApiResponse),
+ ApiErrorResponse {
+ http_code: u16,
+ error_code: String,
+ message: String,
+ },
+}
+
+impl Rpc for AdminRpc {
+ type Response = Result;
+}
+
+impl EndpointHandler for AdminApiServer {
+ async fn handle(
+ self: &Arc,
+ message: &AdminRpc,
+ _from: NodeID,
+ ) -> Result {
+ match message {
+ AdminRpc::Proxy(req) => {
+ info!("Proxied admin API request: {}", req.name());
+ let res = req.clone().handle(&self.garage, &self).await;
+ match res {
+ Ok(res) => Ok(AdminRpcResponse::ProxyApiOkResponse(res.tagged())),
+ Err(e) => Ok(AdminRpcResponse::ApiErrorResponse {
+ http_code: e.http_status_code().as_u16(),
+ error_code: e.code().to_string(),
+ message: e.to_string(),
+ }),
+ }
+ }
+ AdminRpc::Internal(req) => {
+ info!("Internal admin API request: {}", req.name());
+ let res = req.clone().handle(&self.garage, &self).await;
+ match res {
+ Ok(res) => Ok(AdminRpcResponse::InternalApiOkResponse(res)),
+ Err(e) => Ok(AdminRpcResponse::ApiErrorResponse {
+ http_code: e.http_status_code().as_u16(),
+ error_code: e.code().to_string(),
+ message: e.to_string(),
+ }),
+ }
+ }
+ }
+ }
+}
+
+// ---- FOR HTTP ----
pub type ResBody = BoxBody;
pub struct AdminApiServer {
garage: Arc,
#[cfg(feature = "metrics")]
- exporter: PrometheusExporter,
+ pub(crate) exporter: PrometheusExporter,
metrics_token: Option,
admin_token: Option,
+ pub(crate) background: Arc,
+ pub(crate) endpoint: Arc>,
+}
+
+pub enum HttpEndpoint {
+ Old(router_v1::Endpoint),
+ New(String),
}
impl AdminApiServer {
pub fn new(
garage: Arc,
+ background: Arc,
#[cfg(feature = "metrics")] exporter: PrometheusExporter,
- ) -> Self {
+ ) -> Arc {
let cfg = &garage.config.admin;
let metrics_token = cfg.metrics_token.as_deref().map(hash_bearer_token);
let admin_token = cfg.admin_token.as_deref().map(hash_bearer_token);
- Self {
+
+ let endpoint = garage.system.netapp.endpoint(ADMIN_RPC_PATH.into());
+ let admin = Arc::new(Self {
garage,
#[cfg(feature = "metrics")]
exporter,
metrics_token,
admin_token,
- }
+ background,
+ endpoint,
+ });
+ admin.endpoint.set_handler(admin.clone());
+ admin
}
pub async fn run(
- self,
+ self: Arc,
bind_addr: UnixOrTCPSocketAddress,
must_exit: watch::Receiver,
) -> Result<(), GarageError> {
let region = self.garage.config.s3_api.s3_region.clone();
- ApiServer::new(region, self)
+ ApiServer::new(region, ArcAdminApiServer(self))
.run_server(bind_addr, Some(0o220), must_exit)
.await
}
- fn handle_options(&self, _req: &Request) -> Result, Error> {
- Ok(Response::builder()
- .status(StatusCode::NO_CONTENT)
- .header(ALLOW, "OPTIONS, GET, POST")
- .header(ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, GET, POST")
- .header(ACCESS_CONTROL_ALLOW_ORIGIN, "*")
- .body(empty_body())?)
- }
-
- async fn handle_check_domain(
+ async fn handle_http_api(
&self,
req: Request,
+ endpoint: HttpEndpoint,
) -> Result, Error> {
- let query_params: HashMap = req
- .uri()
- .query()
- .map(|v| {
- url::form_urlencoded::parse(v.as_bytes())
- .into_owned()
- .collect()
- })
- .unwrap_or_else(HashMap::new);
+ let auth_header = req.headers().get(AUTHORIZATION).cloned();
- let has_domain_key = query_params.contains_key("domain");
-
- if !has_domain_key {
- return Err(Error::bad_request("No domain query string found"));
- }
-
- let domain = query_params
- .get("domain")
- .ok_or_internal_error("Could not parse domain query string")?;
-
- if self.check_domain(domain).await? {
- Ok(Response::builder()
- .status(StatusCode::OK)
- .body(string_body(format!(
- "Domain '{domain}' is managed by Garage"
- )))?)
- } else {
- Err(Error::bad_request(format!(
- "Domain '{domain}' is not managed by Garage"
- )))
- }
- }
-
- async fn check_domain(&self, domain: &str) -> Result {
- // Resolve bucket from domain name, inferring if the website must be activated for the
- // domain to be valid.
- let (bucket_name, must_check_website) = if let Some(bname) = self
- .garage
- .config
- .s3_api
- .root_domain
- .as_ref()
- .and_then(|rd| host_to_bucket(domain, rd))
- {
- (bname.to_string(), false)
- } else if let Some(bname) = self
- .garage
- .config
- .s3_web
- .as_ref()
- .and_then(|sw| host_to_bucket(domain, sw.root_domain.as_str()))
- {
- (bname.to_string(), true)
- } else {
- (domain.to_string(), true)
+ let request = match endpoint {
+ HttpEndpoint::Old(endpoint_v1) => AdminApiRequest::from_v1(endpoint_v1, req).await?,
+ HttpEndpoint::New(_) => AdminApiRequest::from_request(req).await?,
};
- let bucket_id = match self
- .garage
- .bucket_helper()
- .resolve_global_bucket_name(&bucket_name)
- .await?
- {
- Some(bucket_id) => bucket_id,
- None => return Ok(false),
- };
-
- if !must_check_website {
- return Ok(true);
- }
-
- let bucket = self
- .garage
- .bucket_helper()
- .get_existing_bucket(bucket_id)
- .await?;
-
- let bucket_state = bucket.state.as_option().unwrap();
- let bucket_website_config = bucket_state.website_config.get();
-
- match bucket_website_config {
- Some(_v) => Ok(true),
- None => Ok(false),
- }
- }
-
- fn handle_health(&self) -> Result, Error> {
- let health = self.garage.system.health();
-
- let (status, status_str) = match health.status {
- ClusterHealthStatus::Healthy => (StatusCode::OK, "Garage is fully operational"),
- ClusterHealthStatus::Degraded => (
- StatusCode::OK,
- "Garage is operational but some storage nodes are unavailable",
- ),
- ClusterHealthStatus::Unavailable => (
- StatusCode::SERVICE_UNAVAILABLE,
- "Quorum is not available for some/all partitions, reads and writes will fail",
- ),
- };
- let status_str = format!(
- "{}\nConsult the full health check API endpoint at /v1/health for more details\n",
- status_str
- );
-
- Ok(Response::builder()
- .status(status)
- .header(http::header::CONTENT_TYPE, "text/plain")
- .body(string_body(status_str))?)
- }
-
- fn handle_metrics(&self) -> Result, Error> {
- #[cfg(feature = "metrics")]
- {
- use opentelemetry::trace::Tracer;
-
- let mut buffer = vec![];
- let encoder = TextEncoder::new();
-
- let tracer = opentelemetry::global::tracer("garage");
- let metric_families = tracer.in_span("admin/gather_metrics", |_| {
- self.exporter.registry().gather()
- });
-
- encoder
- .encode(&metric_families, &mut buffer)
- .ok_or_internal_error("Could not serialize metrics")?;
-
- Ok(Response::builder()
- .status(StatusCode::OK)
- .header(http::header::CONTENT_TYPE, encoder.format_type())
- .body(bytes_body(buffer.into()))?)
- }
- #[cfg(not(feature = "metrics"))]
- Err(Error::bad_request(
- "Garage was built without the metrics feature".to_string(),
- ))
- }
-}
-
-impl ApiHandler for AdminApiServer {
- const API_NAME: &'static str = "admin";
- const API_NAME_DISPLAY: &'static str = "Admin";
-
- type Endpoint = Endpoint;
- type Error = Error;
-
- fn parse_endpoint(&self, req: &Request) -> Result {
- if req.uri().path().starts_with("/v0/") {
- let endpoint_v0 = router_v0::Endpoint::from_request(req)?;
- Endpoint::from_v0(endpoint_v0)
- } else {
- Endpoint::from_request(req)
- }
- }
-
- async fn handle(
- &self,
- req: Request,
- endpoint: Endpoint,
- ) -> Result, Error> {
let required_auth_hash =
- match endpoint.authorization_type() {
+ match request.authorization_type() {
Authorization::None => None,
Authorization::MetricsToken => self.metrics_token.as_deref(),
Authorization::AdminToken => match self.admin_token.as_deref() {
@@ -254,7 +168,7 @@ impl ApiHandler for AdminApiServer {
};
if let Some(password_hash) = required_auth_hash {
- match req.headers().get("Authorization") {
+ match auth_header {
None => return Err(Error::forbidden("Authorization token must be provided")),
Some(authorization) => {
verify_bearer_token(&authorization, password_hash)?;
@@ -262,72 +176,59 @@ impl ApiHandler for AdminApiServer {
}
}
- match endpoint {
- Endpoint::Options => self.handle_options(&req),
- Endpoint::CheckDomain => self.handle_check_domain(req).await,
- Endpoint::Health => self.handle_health(),
- Endpoint::Metrics => self.handle_metrics(),
- Endpoint::GetClusterStatus => handle_get_cluster_status(&self.garage).await,
- Endpoint::GetClusterHealth => handle_get_cluster_health(&self.garage).await,
- Endpoint::ConnectClusterNodes => handle_connect_cluster_nodes(&self.garage, req).await,
- // Layout
- Endpoint::GetClusterLayout => handle_get_cluster_layout(&self.garage).await,
- Endpoint::UpdateClusterLayout => handle_update_cluster_layout(&self.garage, req).await,
- Endpoint::ApplyClusterLayout => handle_apply_cluster_layout(&self.garage, req).await,
- Endpoint::RevertClusterLayout => handle_revert_cluster_layout(&self.garage).await,
- // Keys
- Endpoint::ListKeys => handle_list_keys(&self.garage).await,
- Endpoint::GetKeyInfo {
- id,
- search,
- show_secret_key,
- } => {
- let show_secret_key = show_secret_key.map(|x| x == "true").unwrap_or(false);
- handle_get_key_info(&self.garage, id, search, show_secret_key).await
+ match request {
+ AdminApiRequest::Options(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::Metrics(req) => req.handle(&self.garage, &self).await,
+ req => {
+ let res = req.handle(&self.garage, &self).await?;
+ let mut res = json_ok_response(&res)?;
+ res.headers_mut()
+ .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
+ Ok(res)
}
- Endpoint::CreateKey => handle_create_key(&self.garage, req).await,
- Endpoint::ImportKey => handle_import_key(&self.garage, req).await,
- Endpoint::UpdateKey { id } => handle_update_key(&self.garage, id, req).await,
- Endpoint::DeleteKey { id } => handle_delete_key(&self.garage, id).await,
- // Buckets
- Endpoint::ListBuckets => handle_list_buckets(&self.garage).await,
- Endpoint::GetBucketInfo { id, global_alias } => {
- handle_get_bucket_info(&self.garage, id, global_alias).await
- }
- Endpoint::CreateBucket => handle_create_bucket(&self.garage, req).await,
- Endpoint::DeleteBucket { id } => handle_delete_bucket(&self.garage, id).await,
- Endpoint::UpdateBucket { id } => handle_update_bucket(&self.garage, id, req).await,
- // Bucket-key permissions
- Endpoint::BucketAllowKey => {
- handle_bucket_change_key_perm(&self.garage, req, true).await
- }
- Endpoint::BucketDenyKey => {
- handle_bucket_change_key_perm(&self.garage, req, false).await
- }
- // Bucket aliasing
- Endpoint::GlobalAliasBucket { id, alias } => {
- handle_global_alias_bucket(&self.garage, id, alias).await
- }
- Endpoint::GlobalUnaliasBucket { id, alias } => {
- handle_global_unalias_bucket(&self.garage, id, alias).await
- }
- Endpoint::LocalAliasBucket {
- id,
- access_key_id,
- alias,
- } => handle_local_alias_bucket(&self.garage, id, access_key_id, alias).await,
- Endpoint::LocalUnaliasBucket {
- id,
- access_key_id,
- alias,
- } => handle_local_unalias_bucket(&self.garage, id, access_key_id, alias).await,
}
}
}
-impl ApiEndpoint for Endpoint {
- fn name(&self) -> &'static str {
- Endpoint::name(self)
+struct ArcAdminApiServer(Arc);
+
+impl ApiHandler for ArcAdminApiServer {
+ const API_NAME: &'static str = "admin";
+ const API_NAME_DISPLAY: &'static str = "Admin";
+
+ type Endpoint = HttpEndpoint;
+ type Error = Error;
+
+ fn parse_endpoint(&self, req: &Request) -> Result {
+ if req.uri().path().starts_with("/v0/") {
+ let endpoint_v0 = router_v0::Endpoint::from_request(req)?;
+ let endpoint_v1 = router_v1::Endpoint::from_v0(endpoint_v0)?;
+ Ok(HttpEndpoint::Old(endpoint_v1))
+ } else if req.uri().path().starts_with("/v1/") {
+ let endpoint_v1 = router_v1::Endpoint::from_request(req)?;
+ Ok(HttpEndpoint::Old(endpoint_v1))
+ } else {
+ Ok(HttpEndpoint::New(req.uri().path().to_string()))
+ }
+ }
+
+ async fn handle(
+ &self,
+ req: Request,
+ endpoint: HttpEndpoint,
+ ) -> Result, Error> {
+ self.0.handle_http_api(req, endpoint).await
+ }
+}
+
+impl ApiEndpoint for HttpEndpoint {
+ fn name(&self) -> Cow<'static, str> {
+ match self {
+ Self::Old(endpoint_v1) => Cow::Borrowed(endpoint_v1.name()),
+ Self::New(path) => Cow::Owned(path.clone()),
+ }
}
fn add_span_attributes(&self, _span: SpanRef<'_>) {}
diff --git a/src/api/admin/block.rs b/src/api/admin/block.rs
new file mode 100644
index 00000000..73d186a6
--- /dev/null
+++ b/src/api/admin/block.rs
@@ -0,0 +1,274 @@
+use std::sync::Arc;
+
+use garage_util::data::*;
+use garage_util::error::Error as GarageError;
+use garage_util::time::now_msec;
+
+use garage_table::EmptyKey;
+
+use garage_model::garage::Garage;
+use garage_model::s3::object_table::*;
+use garage_model::s3::version_table::*;
+
+use garage_api_common::common_error::CommonErrorDerivative;
+
+use crate::api::*;
+use crate::error::*;
+use crate::{Admin, RequestHandler};
+
+impl RequestHandler for LocalListBlockErrorsRequest {
+ type Response = LocalListBlockErrorsResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let errors = garage.block_manager.list_resync_errors()?;
+ let now = now_msec();
+ let errors = errors
+ .into_iter()
+ .map(|e| BlockError {
+ block_hash: hex::encode(&e.hash),
+ refcount: e.refcount,
+ error_count: e.error_count,
+ last_try_secs_ago: now.saturating_sub(e.last_try) / 1000,
+ next_try_in_secs: e.next_try.saturating_sub(now) / 1000,
+ })
+ .collect();
+ Ok(LocalListBlockErrorsResponse(errors))
+ }
+}
+
+impl RequestHandler for LocalGetBlockInfoRequest {
+ type Response = LocalGetBlockInfoResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let hash = find_block_hash_by_prefix(garage, &self.block_hash)?;
+ let refcount = garage.block_manager.get_block_rc(&hash)?;
+ let block_refs = garage
+ .block_ref_table
+ .get_range(&hash, None, None, 10000, Default::default())
+ .await?;
+ let mut versions = vec![];
+ for br in block_refs {
+ if let Some(v) = garage.version_table.get(&br.version, &EmptyKey).await? {
+ let bl = match &v.backlink {
+ VersionBacklink::MultipartUpload { upload_id } => {
+ if let Some(u) = garage.mpu_table.get(upload_id, &EmptyKey).await? {
+ BlockVersionBacklink::Upload {
+ upload_id: hex::encode(&upload_id),
+ upload_deleted: u.deleted.get(),
+ upload_garbage_collected: false,
+ bucket_id: Some(hex::encode(&u.bucket_id)),
+ key: Some(u.key.to_string()),
+ }
+ } else {
+ BlockVersionBacklink::Upload {
+ upload_id: hex::encode(&upload_id),
+ upload_deleted: true,
+ upload_garbage_collected: true,
+ bucket_id: None,
+ key: None,
+ }
+ }
+ }
+ VersionBacklink::Object { bucket_id, key } => BlockVersionBacklink::Object {
+ bucket_id: hex::encode(&bucket_id),
+ key: key.to_string(),
+ },
+ };
+ versions.push(BlockVersion {
+ version_id: hex::encode(&br.version),
+ deleted: v.deleted.get(),
+ garbage_collected: false,
+ backlink: Some(bl),
+ });
+ } else {
+ versions.push(BlockVersion {
+ version_id: hex::encode(&br.version),
+ deleted: true,
+ garbage_collected: true,
+ backlink: None,
+ });
+ }
+ }
+ Ok(LocalGetBlockInfoResponse {
+ block_hash: hex::encode(&hash),
+ refcount,
+ versions,
+ })
+ }
+}
+
+impl RequestHandler for LocalRetryBlockResyncRequest {
+ type Response = LocalRetryBlockResyncResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ match self {
+ Self::All { all: true } => {
+ let blocks = garage.block_manager.list_resync_errors()?;
+ for b in blocks.iter() {
+ garage.block_manager.resync.clear_backoff(&b.hash)?;
+ }
+ Ok(LocalRetryBlockResyncResponse {
+ count: blocks.len() as u64,
+ })
+ }
+ Self::All { all: false } => Err(Error::bad_request("nonsense")),
+ Self::Blocks { block_hashes } => {
+ for hash in block_hashes.iter() {
+ let hash = hex::decode(hash).ok_or_bad_request("invalid hash")?;
+ let hash = Hash::try_from(&hash).ok_or_bad_request("invalid hash")?;
+ garage.block_manager.resync.clear_backoff(&hash)?;
+ }
+ Ok(LocalRetryBlockResyncResponse {
+ count: block_hashes.len() as u64,
+ })
+ }
+ }
+ }
+}
+
+impl RequestHandler for LocalPurgeBlocksRequest {
+ type Response = LocalPurgeBlocksResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let mut obj_dels = 0;
+ let mut mpu_dels = 0;
+ let mut ver_dels = 0;
+
+ for hash in self.0.iter() {
+ let hash = hex::decode(hash).ok_or_bad_request("invalid hash")?;
+ let hash = Hash::try_from(&hash).ok_or_bad_request("invalid hash")?;
+ let block_refs = garage
+ .block_ref_table
+ .get_range(&hash, None, None, 10000, Default::default())
+ .await?;
+
+ for br in block_refs {
+ if let Some(version) = garage.version_table.get(&br.version, &EmptyKey).await? {
+ handle_block_purge_version_backlink(
+ garage,
+ &version,
+ &mut obj_dels,
+ &mut mpu_dels,
+ )
+ .await?;
+
+ if !version.deleted.get() {
+ let deleted_version = Version::new(version.uuid, version.backlink, true);
+ garage.version_table.insert(&deleted_version).await?;
+ ver_dels += 1;
+ }
+ }
+ }
+ }
+
+ Ok(LocalPurgeBlocksResponse {
+ blocks_purged: self.0.len() as u64,
+ versions_deleted: ver_dels,
+ objects_deleted: obj_dels,
+ uploads_deleted: mpu_dels,
+ })
+ }
+}
+
+fn find_block_hash_by_prefix(garage: &Arc, prefix: &str) -> Result {
+ if prefix.len() < 4 {
+ return Err(Error::bad_request(
+ "Please specify at least 4 characters of the block hash",
+ ));
+ }
+
+ let prefix_bin = hex::decode(&prefix[..prefix.len() & !1]).ok_or_bad_request("invalid hash")?;
+
+ let iter = garage
+ .block_ref_table
+ .data
+ .store
+ .range(&prefix_bin[..]..)
+ .map_err(GarageError::from)?;
+ let mut found = None;
+ for item in iter {
+ let (k, _v) = item.map_err(GarageError::from)?;
+ let hash = Hash::try_from(&k[..32]).unwrap();
+ if &hash.as_slice()[..prefix_bin.len()] != prefix_bin {
+ break;
+ }
+ if hex::encode(hash.as_slice()).starts_with(prefix) {
+ match &found {
+ Some(x) if *x == hash => (),
+ Some(_) => {
+ return Err(Error::bad_request(format!(
+ "Several blocks match prefix `{}`",
+ prefix
+ )));
+ }
+ None => {
+ found = Some(hash);
+ }
+ }
+ }
+ }
+
+ found.ok_or_else(|| Error::NoSuchBlock(prefix.to_string()))
+}
+
+async fn handle_block_purge_version_backlink(
+ garage: &Arc,
+ version: &Version,
+ obj_dels: &mut u64,
+ mpu_dels: &mut u64,
+) -> Result<(), Error> {
+ let (bucket_id, key, ov_id) = match &version.backlink {
+ VersionBacklink::Object { bucket_id, key } => (*bucket_id, key.clone(), version.uuid),
+ VersionBacklink::MultipartUpload { upload_id } => {
+ if let Some(mut mpu) = garage.mpu_table.get(upload_id, &EmptyKey).await? {
+ if !mpu.deleted.get() {
+ mpu.parts.clear();
+ mpu.deleted.set();
+ garage.mpu_table.insert(&mpu).await?;
+ *mpu_dels += 1;
+ }
+ (mpu.bucket_id, mpu.key.clone(), *upload_id)
+ } else {
+ return Ok(());
+ }
+ }
+ };
+
+ if let Some(object) = garage.object_table.get(&bucket_id, &key).await? {
+ let ov = object.versions().iter().rev().find(|v| v.is_complete());
+ if let Some(ov) = ov {
+ if ov.uuid == ov_id {
+ let del_uuid = gen_uuid();
+ let deleted_object = Object::new(
+ bucket_id,
+ key,
+ vec![ObjectVersion {
+ uuid: del_uuid,
+ timestamp: ov.timestamp + 1,
+ state: ObjectVersionState::Complete(ObjectVersionData::DeleteMarker),
+ }],
+ );
+ garage.object_table.insert(&deleted_object).await?;
+ *obj_dels += 1;
+ }
+ }
+ }
+
+ Ok(())
+}
diff --git a/src/api/admin/bucket.rs b/src/api/admin/bucket.rs
index 2537bfc9..d2bb62e0 100644
--- a/src/api/admin/bucket.rs
+++ b/src/api/admin/bucket.rs
@@ -1,8 +1,6 @@
use std::collections::HashMap;
use std::sync::Arc;
-
-use hyper::{body::Incoming as IncomingBody, Request, Response, StatusCode};
-use serde::{Deserialize, Serialize};
+use std::time::Duration;
use garage_util::crdt::*;
use garage_util::data::*;
@@ -18,102 +16,97 @@ use garage_model::s3::mpu_table;
use garage_model::s3::object_table::*;
use garage_api_common::common_error::CommonError;
-use garage_api_common::helpers::*;
-use crate::api_server::ResBody;
+use crate::api::*;
use crate::error::*;
-use crate::key::ApiBucketKeyPerm;
+use crate::{Admin, RequestHandler};
-pub async fn handle_list_buckets(garage: &Arc) -> Result, Error> {
- let buckets = garage
- .bucket_table
- .get_range(
- &EmptyKey,
- None,
- Some(DeletedFilter::NotDeleted),
- 10000,
- EnumerationOrder::Forward,
- )
- .await?;
+impl RequestHandler for ListBucketsRequest {
+ type Response = ListBucketsResponse;
- let res = buckets
- .into_iter()
- .map(|b| {
- let state = b.state.as_option().unwrap();
- ListBucketResultItem {
- id: hex::encode(b.id),
- global_aliases: state
- .aliases
- .items()
- .iter()
- .filter(|(_, _, a)| *a)
- .map(|(n, _, _)| n.to_string())
- .collect::>(),
- local_aliases: state
- .local_aliases
- .items()
- .iter()
- .filter(|(_, _, a)| *a)
- .map(|((k, n), _, _)| BucketLocalAlias {
- access_key_id: k.to_string(),
- alias: n.to_string(),
- })
- .collect::>(),
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let buckets = garage
+ .bucket_table
+ .get_range(
+ &EmptyKey,
+ None,
+ Some(DeletedFilter::NotDeleted),
+ 10000,
+ EnumerationOrder::Forward,
+ )
+ .await?;
+
+ let res = buckets
+ .into_iter()
+ .map(|b| {
+ let state = b.state.as_option().unwrap();
+ ListBucketsResponseItem {
+ id: hex::encode(b.id),
+ global_aliases: state
+ .aliases
+ .items()
+ .iter()
+ .filter(|(_, _, a)| *a)
+ .map(|(n, _, _)| n.to_string())
+ .collect::>(),
+ local_aliases: state
+ .local_aliases
+ .items()
+ .iter()
+ .filter(|(_, _, a)| *a)
+ .map(|((k, n), _, _)| BucketLocalAlias {
+ access_key_id: k.to_string(),
+ alias: n.to_string(),
+ })
+ .collect::>(),
+ }
+ })
+ .collect::>();
+
+ Ok(ListBucketsResponse(res))
+ }
+}
+
+impl RequestHandler for GetBucketInfoRequest {
+ type Response = GetBucketInfoResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let bucket_id = match (self.id, self.global_alias, self.search) {
+ (Some(id), None, None) => parse_bucket_id(&id)?,
+ (None, Some(ga), None) => garage
+ .bucket_helper()
+ .resolve_global_bucket_name(&ga)
+ .await?
+ .ok_or_else(|| HelperError::NoSuchBucket(ga.to_string()))?,
+ (None, None, Some(search)) => {
+ garage
+ .bucket_helper()
+ .admin_get_existing_matching_bucket(&search)
+ .await?
}
- })
- .collect::>();
+ _ => {
+ return Err(Error::bad_request(
+ "Either id, globalAlias or search must be provided (but not several of them)",
+ ));
+ }
+ };
- Ok(json_ok_response(&res)?)
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ListBucketResultItem {
- id: String,
- global_aliases: Vec,
- local_aliases: Vec,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct BucketLocalAlias {
- access_key_id: String,
- alias: String,
-}
-
-#[derive(Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct ApiBucketQuotas {
- max_size: Option,
- max_objects: Option,
-}
-
-pub async fn handle_get_bucket_info(
- garage: &Arc,
- id: Option,
- global_alias: Option,
-) -> Result, Error> {
- let bucket_id = match (id, global_alias) {
- (Some(id), None) => parse_bucket_id(&id)?,
- (None, Some(ga)) => garage
- .bucket_helper()
- .resolve_global_bucket_name(&ga)
- .await?
- .ok_or_else(|| HelperError::NoSuchBucket(ga.to_string()))?,
- _ => {
- return Err(Error::bad_request(
- "Either id or globalAlias must be provided (but not both)",
- ));
- }
- };
-
- bucket_info_results(garage, bucket_id).await
+ bucket_info_results(garage, bucket_id).await
+ }
}
async fn bucket_info_results(
garage: &Arc,
bucket_id: Uuid,
-) -> Result, Error> {
+) -> Result {
let bucket = garage
.bucket_helper()
.get_existing_bucket(bucket_id)
@@ -176,301 +169,295 @@ async fn bucket_info_results(
let state = bucket.state.as_option().unwrap();
let quotas = state.quotas.get();
- let res =
- GetBucketInfoResult {
- id: hex::encode(bucket.id),
- global_aliases: state
- .aliases
- .items()
- .iter()
- .filter(|(_, _, a)| *a)
- .map(|(n, _, _)| n.to_string())
- .collect::>(),
- website_access: state.website_config.get().is_some(),
- website_config: state.website_config.get().clone().map(|wsc| {
- GetBucketInfoWebsiteResult {
- index_document: wsc.index_document,
- error_document: wsc.error_document,
+ let res = GetBucketInfoResponse {
+ id: hex::encode(bucket.id),
+ global_aliases: state
+ .aliases
+ .items()
+ .iter()
+ .filter(|(_, _, a)| *a)
+ .map(|(n, _, _)| n.to_string())
+ .collect::>(),
+ website_access: state.website_config.get().is_some(),
+ website_config: state.website_config.get().clone().map(|wsc| {
+ GetBucketInfoWebsiteResponse {
+ index_document: wsc.index_document,
+ error_document: wsc.error_document,
+ }
+ }),
+ keys: relevant_keys
+ .into_values()
+ .map(|key| {
+ let p = key.state.as_option().unwrap();
+ GetBucketInfoKey {
+ access_key_id: key.key_id,
+ name: p.name.get().to_string(),
+ permissions: p
+ .authorized_buckets
+ .get(&bucket.id)
+ .map(|p| ApiBucketKeyPerm {
+ read: p.allow_read,
+ write: p.allow_write,
+ owner: p.allow_owner,
+ })
+ .unwrap_or_default(),
+ bucket_local_aliases: p
+ .local_aliases
+ .items()
+ .iter()
+ .filter(|(_, _, b)| *b == Some(bucket.id))
+ .map(|(n, _, _)| n.to_string())
+ .collect::>(),
}
- }),
- keys: relevant_keys
- .into_values()
- .map(|key| {
- let p = key.state.as_option().unwrap();
- GetBucketInfoKey {
- access_key_id: key.key_id,
- name: p.name.get().to_string(),
- permissions: p
- .authorized_buckets
- .get(&bucket.id)
- .map(|p| ApiBucketKeyPerm {
- read: p.allow_read,
- write: p.allow_write,
- owner: p.allow_owner,
- })
- .unwrap_or_default(),
- bucket_local_aliases: p
- .local_aliases
- .items()
- .iter()
- .filter(|(_, _, b)| *b == Some(bucket.id))
- .map(|(n, _, _)| n.to_string())
- .collect::>(),
- }
- })
- .collect::>(),
- objects: *counters.get(OBJECTS).unwrap_or(&0),
- bytes: *counters.get(BYTES).unwrap_or(&0),
- unfinished_uploads: *counters.get(UNFINISHED_UPLOADS).unwrap_or(&0),
- unfinished_multipart_uploads: *mpu_counters.get(mpu_table::UPLOADS).unwrap_or(&0),
- unfinished_multipart_upload_parts: *mpu_counters.get(mpu_table::PARTS).unwrap_or(&0),
- unfinished_multipart_upload_bytes: *mpu_counters.get(mpu_table::BYTES).unwrap_or(&0),
- quotas: ApiBucketQuotas {
- max_size: quotas.max_size,
- max_objects: quotas.max_objects,
- },
- };
+ })
+ .collect::>(),
+ objects: *counters.get(OBJECTS).unwrap_or(&0),
+ bytes: *counters.get(BYTES).unwrap_or(&0),
+ unfinished_uploads: *counters.get(UNFINISHED_UPLOADS).unwrap_or(&0),
+ unfinished_multipart_uploads: *mpu_counters.get(mpu_table::UPLOADS).unwrap_or(&0),
+ unfinished_multipart_upload_parts: *mpu_counters.get(mpu_table::PARTS).unwrap_or(&0),
+ unfinished_multipart_upload_bytes: *mpu_counters.get(mpu_table::BYTES).unwrap_or(&0),
+ quotas: ApiBucketQuotas {
+ max_size: quotas.max_size,
+ max_objects: quotas.max_objects,
+ },
+ };
- Ok(json_ok_response(&res)?)
+ Ok(res)
}
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GetBucketInfoResult {
- id: String,
- global_aliases: Vec,
- website_access: bool,
- #[serde(default)]
- website_config: Option,
- keys: Vec,
- objects: i64,
- bytes: i64,
- unfinished_uploads: i64,
- unfinished_multipart_uploads: i64,
- unfinished_multipart_upload_parts: i64,
- unfinished_multipart_upload_bytes: i64,
- quotas: ApiBucketQuotas,
-}
+impl RequestHandler for CreateBucketRequest {
+ type Response = CreateBucketResponse;
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GetBucketInfoWebsiteResult {
- index_document: String,
- error_document: Option,
-}
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let helper = garage.locked_helper().await;
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GetBucketInfoKey {
- access_key_id: String,
- name: String,
- permissions: ApiBucketKeyPerm,
- bucket_local_aliases: Vec,
-}
+ if let Some(ga) = &self.global_alias {
+ if !is_valid_bucket_name(ga) {
+ return Err(Error::bad_request(format!(
+ "{}: {}",
+ ga, INVALID_BUCKET_NAME_MESSAGE
+ )));
+ }
-pub async fn handle_create_bucket(
- garage: &Arc,
- req: Request,
-) -> Result, Error> {
- let req = parse_json_body::(req).await?;
-
- let helper = garage.locked_helper().await;
-
- if let Some(ga) = &req.global_alias {
- if !is_valid_bucket_name(ga) {
- return Err(Error::bad_request(format!(
- "{}: {}",
- ga, INVALID_BUCKET_NAME_MESSAGE
- )));
- }
-
- if let Some(alias) = garage.bucket_alias_table.get(&EmptyKey, ga).await? {
- if alias.state.get().is_some() {
- return Err(CommonError::BucketAlreadyExists.into());
+ if let Some(alias) = garage.bucket_alias_table.get(&EmptyKey, ga).await? {
+ if alias.state.get().is_some() {
+ return Err(CommonError::BucketAlreadyExists.into());
+ }
}
}
- }
- if let Some(la) = &req.local_alias {
- if !is_valid_bucket_name(&la.alias) {
- return Err(Error::bad_request(format!(
- "{}: {}",
- la.alias, INVALID_BUCKET_NAME_MESSAGE
- )));
+ if let Some(la) = &self.local_alias {
+ if !is_valid_bucket_name(&la.alias) {
+ return Err(Error::bad_request(format!(
+ "{}: {}",
+ la.alias, INVALID_BUCKET_NAME_MESSAGE
+ )));
+ }
+
+ let key = helper.key().get_existing_key(&la.access_key_id).await?;
+ let state = key.state.as_option().unwrap();
+ if matches!(state.local_aliases.get(&la.alias), Some(_)) {
+ return Err(Error::bad_request("Local alias already exists"));
+ }
}
- let key = helper.key().get_existing_key(&la.access_key_id).await?;
- let state = key.state.as_option().unwrap();
- if matches!(state.local_aliases.get(&la.alias), Some(_)) {
- return Err(Error::bad_request("Local alias already exists"));
+ let bucket = Bucket::new();
+ garage.bucket_table.insert(&bucket).await?;
+
+ if let Some(ga) = &self.global_alias {
+ helper.set_global_bucket_alias(bucket.id, ga).await?;
}
+
+ if let Some(la) = &self.local_alias {
+ helper
+ .set_local_bucket_alias(bucket.id, &la.access_key_id, &la.alias)
+ .await?;
+
+ if la.allow.read || la.allow.write || la.allow.owner {
+ helper
+ .set_bucket_key_permissions(
+ bucket.id,
+ &la.access_key_id,
+ BucketKeyPerm {
+ timestamp: now_msec(),
+ allow_read: la.allow.read,
+ allow_write: la.allow.write,
+ allow_owner: la.allow.owner,
+ },
+ )
+ .await?;
+ }
+ }
+
+ Ok(CreateBucketResponse(
+ bucket_info_results(garage, bucket.id).await?,
+ ))
}
+}
- let bucket = Bucket::new();
- garage.bucket_table.insert(&bucket).await?;
+impl RequestHandler for DeleteBucketRequest {
+ type Response = DeleteBucketResponse;
- if let Some(ga) = &req.global_alias {
- helper.set_global_bucket_alias(bucket.id, ga).await?;
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let helper = garage.locked_helper().await;
+
+ let bucket_id = parse_bucket_id(&self.id)?;
+
+ let mut bucket = helper.bucket().get_existing_bucket(bucket_id).await?;
+ let state = bucket.state.as_option().unwrap();
+
+ // Check bucket is empty
+ if !helper.bucket().is_bucket_empty(bucket_id).await? {
+ return Err(CommonError::BucketNotEmpty.into());
+ }
+
+ // --- done checking, now commit ---
+ // 1. delete authorization from keys that had access
+ for (key_id, perm) in bucket.authorized_keys() {
+ if perm.is_any() {
+ helper
+ .set_bucket_key_permissions(bucket.id, key_id, BucketKeyPerm::NO_PERMISSIONS)
+ .await?;
+ }
+ }
+ // 2. delete all local aliases
+ for ((key_id, alias), _, active) in state.local_aliases.items().iter() {
+ if *active {
+ helper
+ .unset_local_bucket_alias(bucket.id, key_id, alias)
+ .await?;
+ }
+ }
+ // 3. delete all global aliases
+ for (alias, _, active) in state.aliases.items().iter() {
+ if *active {
+ helper.purge_global_bucket_alias(bucket.id, alias).await?;
+ }
+ }
+
+ // 4. delete bucket
+ bucket.state = Deletable::delete();
+ garage.bucket_table.insert(&bucket).await?;
+
+ Ok(DeleteBucketResponse)
}
+}
- if let Some(la) = &req.local_alias {
- helper
- .set_local_bucket_alias(bucket.id, &la.access_key_id, &la.alias)
+impl RequestHandler for UpdateBucketRequest {
+ type Response = UpdateBucketResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let bucket_id = parse_bucket_id(&self.id)?;
+
+ let mut bucket = garage
+ .bucket_helper()
+ .get_existing_bucket(bucket_id)
.await?;
- if la.allow.read || la.allow.write || la.allow.owner {
- helper
- .set_bucket_key_permissions(
- bucket.id,
- &la.access_key_id,
- BucketKeyPerm {
- timestamp: now_msec(),
- allow_read: la.allow.read,
- allow_write: la.allow.write,
- allow_owner: la.allow.owner,
- },
- )
- .await?;
- }
- }
+ let state = bucket.state.as_option_mut().unwrap();
- bucket_info_results(garage, bucket.id).await
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct CreateBucketRequest {
- global_alias: Option,
- local_alias: Option,
-}
-
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct CreateBucketLocalAlias {
- access_key_id: String,
- alias: String,
- #[serde(default)]
- allow: ApiBucketKeyPerm,
-}
-
-pub async fn handle_delete_bucket(
- garage: &Arc,
- id: String,
-) -> Result, Error> {
- let helper = garage.locked_helper().await;
-
- let bucket_id = parse_bucket_id(&id)?;
-
- let mut bucket = helper.bucket().get_existing_bucket(bucket_id).await?;
- let state = bucket.state.as_option().unwrap();
-
- // Check bucket is empty
- if !helper.bucket().is_bucket_empty(bucket_id).await? {
- return Err(CommonError::BucketNotEmpty.into());
- }
-
- // --- done checking, now commit ---
- // 1. delete authorization from keys that had access
- for (key_id, perm) in bucket.authorized_keys() {
- if perm.is_any() {
- helper
- .set_bucket_key_permissions(bucket.id, key_id, BucketKeyPerm::NO_PERMISSIONS)
- .await?;
- }
- }
- // 2. delete all local aliases
- for ((key_id, alias), _, active) in state.local_aliases.items().iter() {
- if *active {
- helper
- .unset_local_bucket_alias(bucket.id, key_id, alias)
- .await?;
- }
- }
- // 3. delete all global aliases
- for (alias, _, active) in state.aliases.items().iter() {
- if *active {
- helper.purge_global_bucket_alias(bucket.id, alias).await?;
- }
- }
-
- // 4. delete bucket
- bucket.state = Deletable::delete();
- garage.bucket_table.insert(&bucket).await?;
-
- Ok(Response::builder()
- .status(StatusCode::NO_CONTENT)
- .body(empty_body())?)
-}
-
-pub async fn handle_update_bucket(
- garage: &Arc,
- id: String,
- req: Request,
-) -> Result, Error> {
- let req = parse_json_body::(req).await?;
- let bucket_id = parse_bucket_id(&id)?;
-
- let mut bucket = garage
- .bucket_helper()
- .get_existing_bucket(bucket_id)
- .await?;
-
- let state = bucket.state.as_option_mut().unwrap();
-
- if let Some(wa) = req.website_access {
- if wa.enabled {
- state.website_config.update(Some(WebsiteConfig {
- index_document: wa.index_document.ok_or_bad_request(
- "Please specify indexDocument when enabling website access.",
- )?,
- error_document: wa.error_document,
- }));
- } else {
- if wa.index_document.is_some() || wa.error_document.is_some() {
- return Err(Error::bad_request(
- "Cannot specify indexDocument or errorDocument when disabling website access.",
- ));
+ if let Some(wa) = self.body.website_access {
+ if wa.enabled {
+ state.website_config.update(Some(WebsiteConfig {
+ index_document: wa.index_document.ok_or_bad_request(
+ "Please specify indexDocument when enabling website access.",
+ )?,
+ error_document: wa.error_document,
+ }));
+ } else {
+ if wa.index_document.is_some() || wa.error_document.is_some() {
+ return Err(Error::bad_request(
+ "Cannot specify indexDocument or errorDocument when disabling website access.",
+ ));
+ }
+ state.website_config.update(None);
}
- state.website_config.update(None);
}
+
+ if let Some(q) = self.body.quotas {
+ state.quotas.update(BucketQuotas {
+ max_size: q.max_size,
+ max_objects: q.max_objects,
+ });
+ }
+
+ garage.bucket_table.insert(&bucket).await?;
+
+ Ok(UpdateBucketResponse(
+ bucket_info_results(garage, bucket_id).await?,
+ ))
}
-
- if let Some(q) = req.quotas {
- state.quotas.update(BucketQuotas {
- max_size: q.max_size,
- max_objects: q.max_objects,
- });
- }
-
- garage.bucket_table.insert(&bucket).await?;
-
- bucket_info_results(garage, bucket_id).await
}
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct UpdateBucketRequest {
- website_access: Option,
- quotas: Option,
-}
+impl RequestHandler for CleanupIncompleteUploadsRequest {
+ type Response = CleanupIncompleteUploadsResponse;
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct UpdateBucketWebsiteAccess {
- enabled: bool,
- index_document: Option,
- error_document: Option,
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let duration = Duration::from_secs(self.older_than_secs);
+
+ let bucket_id = parse_bucket_id(&self.bucket_id)?;
+
+ let count = garage
+ .bucket_helper()
+ .cleanup_incomplete_uploads(&bucket_id, duration)
+ .await?;
+
+ Ok(CleanupIncompleteUploadsResponse {
+ uploads_deleted: count as u64,
+ })
+ }
}
// ---- BUCKET/KEY PERMISSIONS ----
+impl RequestHandler for AllowBucketKeyRequest {
+ type Response = AllowBucketKeyResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let res = handle_bucket_change_key_perm(garage, self.0, true).await?;
+ Ok(AllowBucketKeyResponse(res))
+ }
+}
+
+impl RequestHandler for DenyBucketKeyRequest {
+ type Response = DenyBucketKeyResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let res = handle_bucket_change_key_perm(garage, self.0, false).await?;
+ Ok(DenyBucketKeyResponse(res))
+ }
+}
+
pub async fn handle_bucket_change_key_perm(
garage: &Arc,
- req: Request,
+ req: BucketKeyPermChangeRequest,
new_perm_flag: bool,
-) -> Result, Error> {
- let req = parse_json_body::(req).await?;
-
+) -> Result {
let helper = garage.locked_helper().await;
let bucket_id = parse_bucket_id(&req.bucket_id)?;
@@ -503,76 +490,74 @@ pub async fn handle_bucket_change_key_perm(
bucket_info_results(garage, bucket.id).await
}
-#[derive(Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct BucketKeyPermChangeRequest {
- bucket_id: String,
- access_key_id: String,
- permissions: ApiBucketKeyPerm,
-}
-
// ---- BUCKET ALIASES ----
-pub async fn handle_global_alias_bucket(
- garage: &Arc,
- bucket_id: String,
- alias: String,
-) -> Result, Error> {
- let bucket_id = parse_bucket_id(&bucket_id)?;
+impl RequestHandler for AddBucketAliasRequest {
+ type Response = AddBucketAliasResponse;
- let helper = garage.locked_helper().await;
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let bucket_id = parse_bucket_id(&self.bucket_id)?;
- helper.set_global_bucket_alias(bucket_id, &alias).await?;
+ let helper = garage.locked_helper().await;
- bucket_info_results(garage, bucket_id).await
+ match self.alias {
+ BucketAliasEnum::Global { global_alias } => {
+ helper
+ .set_global_bucket_alias(bucket_id, &global_alias)
+ .await?;
+ }
+ BucketAliasEnum::Local {
+ local_alias,
+ access_key_id,
+ } => {
+ helper
+ .set_local_bucket_alias(bucket_id, &access_key_id, &local_alias)
+ .await?;
+ }
+ }
+
+ Ok(AddBucketAliasResponse(
+ bucket_info_results(garage, bucket_id).await?,
+ ))
+ }
}
-pub async fn handle_global_unalias_bucket(
- garage: &Arc,
- bucket_id: String,
- alias: String,
-) -> Result, Error> {
- let bucket_id = parse_bucket_id(&bucket_id)?;
+impl RequestHandler for RemoveBucketAliasRequest {
+ type Response = RemoveBucketAliasResponse;
- let helper = garage.locked_helper().await;
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let bucket_id = parse_bucket_id(&self.bucket_id)?;
- helper.unset_global_bucket_alias(bucket_id, &alias).await?;
+ let helper = garage.locked_helper().await;
- bucket_info_results(garage, bucket_id).await
-}
+ match self.alias {
+ BucketAliasEnum::Global { global_alias } => {
+ helper
+ .unset_global_bucket_alias(bucket_id, &global_alias)
+ .await?;
+ }
+ BucketAliasEnum::Local {
+ local_alias,
+ access_key_id,
+ } => {
+ helper
+ .unset_local_bucket_alias(bucket_id, &access_key_id, &local_alias)
+ .await?;
+ }
+ }
-pub async fn handle_local_alias_bucket(
- garage: &Arc,
- bucket_id: String,
- access_key_id: String,
- alias: String,
-) -> Result, Error> {
- let bucket_id = parse_bucket_id(&bucket_id)?;
-
- let helper = garage.locked_helper().await;
-
- helper
- .set_local_bucket_alias(bucket_id, &access_key_id, &alias)
- .await?;
-
- bucket_info_results(garage, bucket_id).await
-}
-
-pub async fn handle_local_unalias_bucket(
- garage: &Arc,
- bucket_id: String,
- access_key_id: String,
- alias: String,
-) -> Result, Error> {
- let bucket_id = parse_bucket_id(&bucket_id)?;
-
- let helper = garage.locked_helper().await;
-
- helper
- .unset_local_bucket_alias(bucket_id, &access_key_id, &alias)
- .await?;
-
- bucket_info_results(garage, bucket_id).await
+ Ok(RemoveBucketAliasResponse(
+ bucket_info_results(garage, bucket_id).await?,
+ ))
+ }
}
// ---- HELPER ----
diff --git a/src/api/admin/cluster.rs b/src/api/admin/cluster.rs
index ffa0fa71..cb1fa493 100644
--- a/src/api/admin/cluster.rs
+++ b/src/api/admin/cluster.rs
@@ -1,10 +1,6 @@
use std::collections::HashMap;
-use std::net::SocketAddr;
use std::sync::Arc;
-use hyper::{body::Incoming as IncomingBody, Request, Response};
-use serde::{Deserialize, Serialize};
-
use garage_util::crdt::*;
use garage_util::data::*;
@@ -12,158 +8,182 @@ use garage_rpc::layout;
use garage_model::garage::Garage;
-use garage_api_common::helpers::{json_ok_response, parse_json_body};
-
-use crate::api_server::ResBody;
+use crate::api::*;
use crate::error::*;
+use crate::{Admin, RequestHandler};
-pub async fn handle_get_cluster_status(garage: &Arc) -> Result, Error> {
- let layout = garage.system.cluster_layout();
- let mut nodes = garage
- .system
- .get_known_nodes()
- .into_iter()
- .map(|i| {
- (
- i.id,
- NodeResp {
- id: hex::encode(i.id),
- addr: i.addr,
- hostname: i.status.hostname,
- is_up: i.is_up,
- last_seen_secs_ago: i.last_seen_secs_ago,
- data_partition: i
- .status
- .data_disk_avail
- .map(|(avail, total)| FreeSpaceResp {
- available: avail,
- total,
+impl RequestHandler for GetClusterStatusRequest {
+ type Response = GetClusterStatusResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let layout = garage.system.cluster_layout();
+ let mut nodes = garage
+ .system
+ .get_known_nodes()
+ .into_iter()
+ .map(|i| {
+ (
+ i.id,
+ NodeResp {
+ id: hex::encode(i.id),
+ addr: i.addr,
+ hostname: i.status.hostname,
+ is_up: i.is_up,
+ last_seen_secs_ago: i.last_seen_secs_ago,
+ data_partition: i.status.data_disk_avail.map(|(avail, total)| {
+ FreeSpaceResp {
+ available: avail,
+ total,
+ }
}),
- metadata_partition: i.status.meta_disk_avail.map(|(avail, total)| {
- FreeSpaceResp {
- available: avail,
- total,
- }
- }),
- ..Default::default()
- },
- )
- })
- .collect::>();
+ metadata_partition: i.status.meta_disk_avail.map(|(avail, total)| {
+ FreeSpaceResp {
+ available: avail,
+ total,
+ }
+ }),
+ ..Default::default()
+ },
+ )
+ })
+ .collect::>();
- for (id, _, role) in layout.current().roles.items().iter() {
- if let layout::NodeRoleV(Some(r)) = role {
- let role = NodeRoleResp {
- id: hex::encode(id),
- zone: r.zone.to_string(),
- capacity: r.capacity,
- tags: r.tags.clone(),
- };
- match nodes.get_mut(id) {
- None => {
- nodes.insert(
- *id,
- NodeResp {
- id: hex::encode(id),
- role: Some(role),
- ..Default::default()
- },
- );
- }
- Some(n) => {
- n.role = Some(role);
- }
- }
- }
- }
-
- for ver in layout.versions().iter().rev().skip(1) {
- for (id, _, role) in ver.roles.items().iter() {
+ for (id, _, role) in layout.current().roles.items().iter() {
if let layout::NodeRoleV(Some(r)) = role {
- if r.capacity.is_some() {
- if let Some(n) = nodes.get_mut(id) {
- if n.role.is_none() {
- n.draining = true;
- }
- } else {
+ let role = NodeRoleResp {
+ id: hex::encode(id),
+ zone: r.zone.to_string(),
+ capacity: r.capacity,
+ tags: r.tags.clone(),
+ };
+ match nodes.get_mut(id) {
+ None => {
nodes.insert(
*id,
NodeResp {
id: hex::encode(id),
- draining: true,
+ role: Some(role),
..Default::default()
},
);
}
+ Some(n) => {
+ n.role = Some(role);
+ }
}
}
}
- }
- let mut nodes = nodes.into_values().collect::>();
- nodes.sort_by(|x, y| x.id.cmp(&y.id));
+ for ver in layout.versions().iter().rev().skip(1) {
+ for (id, _, role) in ver.roles.items().iter() {
+ if let layout::NodeRoleV(Some(r)) = role {
+ if r.capacity.is_some() {
+ if let Some(n) = nodes.get_mut(id) {
+ if n.role.is_none() {
+ n.draining = true;
+ }
+ } else {
+ nodes.insert(
+ *id,
+ NodeResp {
+ id: hex::encode(id),
+ draining: true,
+ ..Default::default()
+ },
+ );
+ }
+ }
+ }
+ }
+ }
- let res = GetClusterStatusResponse {
- node: hex::encode(garage.system.id),
- garage_version: garage_util::version::garage_version(),
- garage_features: garage_util::version::garage_features(),
- rust_version: garage_util::version::rust_version(),
- db_engine: garage.db.engine(),
- layout_version: layout.current().version,
- nodes,
- };
+ let mut nodes = nodes.into_values().collect::>();
+ nodes.sort_by(|x, y| x.id.cmp(&y.id));
- Ok(json_ok_response(&res)?)
-}
-
-pub async fn handle_get_cluster_health(garage: &Arc) -> Result, Error> {
- use garage_rpc::system::ClusterHealthStatus;
- let health = garage.system.health();
- let health = ClusterHealth {
- status: match health.status {
- ClusterHealthStatus::Healthy => "healthy",
- ClusterHealthStatus::Degraded => "degraded",
- ClusterHealthStatus::Unavailable => "unavailable",
- },
- known_nodes: health.known_nodes,
- connected_nodes: health.connected_nodes,
- storage_nodes: health.storage_nodes,
- storage_nodes_ok: health.storage_nodes_ok,
- partitions: health.partitions,
- partitions_quorum: health.partitions_quorum,
- partitions_all_ok: health.partitions_all_ok,
- };
- Ok(json_ok_response(&health)?)
-}
-
-pub async fn handle_connect_cluster_nodes(
- garage: &Arc,
- req: Request,
-) -> Result, Error> {
- let req = parse_json_body::, _, Error>(req).await?;
-
- let res = futures::future::join_all(req.iter().map(|node| garage.system.connect(node)))
- .await
- .into_iter()
- .map(|r| match r {
- Ok(()) => ConnectClusterNodesResponse {
- success: true,
- error: None,
- },
- Err(e) => ConnectClusterNodesResponse {
- success: false,
- error: Some(format!("{}", e)),
- },
+ Ok(GetClusterStatusResponse {
+ node: hex::encode(garage.system.id),
+ garage_version: garage_util::version::garage_version().to_string(),
+ garage_features: garage_util::version::garage_features()
+ .map(|features| features.iter().map(ToString::to_string).collect()),
+ rust_version: garage_util::version::rust_version().to_string(),
+ db_engine: garage.db.engine(),
+ layout_version: layout.current().version,
+ nodes,
})
- .collect::>();
-
- Ok(json_ok_response(&res)?)
+ }
}
-pub async fn handle_get_cluster_layout(garage: &Arc) -> Result, Error> {
- let res = format_cluster_layout(garage.system.cluster_layout().inner());
+impl RequestHandler for GetClusterHealthRequest {
+ type Response = GetClusterHealthResponse;
- Ok(json_ok_response(&res)?)
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ use garage_rpc::system::ClusterHealthStatus;
+ let health = garage.system.health();
+ let health = GetClusterHealthResponse {
+ status: match health.status {
+ ClusterHealthStatus::Healthy => "healthy",
+ ClusterHealthStatus::Degraded => "degraded",
+ ClusterHealthStatus::Unavailable => "unavailable",
+ }
+ .to_string(),
+ known_nodes: health.known_nodes,
+ connected_nodes: health.connected_nodes,
+ storage_nodes: health.storage_nodes,
+ storage_nodes_ok: health.storage_nodes_ok,
+ partitions: health.partitions,
+ partitions_quorum: health.partitions_quorum,
+ partitions_all_ok: health.partitions_all_ok,
+ };
+ Ok(health)
+ }
+}
+
+impl RequestHandler for ConnectClusterNodesRequest {
+ type Response = ConnectClusterNodesResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ let res = futures::future::join_all(self.0.iter().map(|node| garage.system.connect(node)))
+ .await
+ .into_iter()
+ .map(|r| match r {
+ Ok(()) => ConnectNodeResponse {
+ success: true,
+ error: None,
+ },
+ Err(e) => ConnectNodeResponse {
+ success: false,
+ error: Some(format!("{}", e)),
+ },
+ })
+ .collect::>();
+ Ok(ConnectClusterNodesResponse(res))
+ }
+}
+
+impl RequestHandler for GetClusterLayoutRequest {
+ type Response = GetClusterLayoutResponse;
+
+ async fn handle(
+ self,
+ garage: &Arc,
+ _admin: &Admin,
+ ) -> Result {
+ Ok(format_cluster_layout(
+ garage.system.cluster_layout().inner(),
+ ))
+ }
}
fn format_cluster_layout(layout: &layout::LayoutHistory) -> GetClusterLayoutResponse {
@@ -213,199 +233,98 @@ fn format_cluster_layout(layout: &layout::LayoutHistory) -> GetClusterLayoutResp
// ----
-#[derive(Debug, Clone, Copy, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ClusterHealth {
- status: &'static str,
- known_nodes: usize,
- connected_nodes: usize,
- storage_nodes: usize,
- storage_nodes_ok: usize,
- partitions: usize,
- partitions_quorum: usize,
- partitions_all_ok: usize,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GetClusterStatusResponse {
- node: String,
- garage_version: &'static str,
- garage_features: Option<&'static [&'static str]>,
- rust_version: &'static str,
- db_engine: String,
- layout_version: u64,
- nodes: Vec,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ApplyClusterLayoutResponse {
- message: Vec,
- layout: GetClusterLayoutResponse,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct ConnectClusterNodesResponse {
- success: bool,
- error: Option,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct GetClusterLayoutResponse {
- version: u64,
- roles: Vec,
- staged_role_changes: Vec,
-}
-
-#[derive(Serialize)]
-#[serde(rename_all = "camelCase")]
-struct NodeRoleResp {
- id: String,
- zone: String,
- capacity: Option,
- tags: Vec,
-}
-
-#[derive(Serialize, Default)]
-#[serde(rename_all = "camelCase")]
-struct FreeSpaceResp {
- available: u64,
- total: u64,
-}
-
-#[derive(Serialize, Default)]
-#[serde(rename_all = "camelCase")]
-struct NodeResp {
- id: String,
- role: Option