From 45645a996411c92808d76d006f0d7ca724c56c7e Mon Sep 17 00:00:00 2001 From: l-nmch Date: Wed, 11 Nov 2026 20:34:04 +0100 Subject: [PATCH] feat(quota): one set of limits for every tenant, with 2 profiles Every tenant has the same limits (2 instances, 2 vCPU, 4 GiB, 128 GiB of disk, 2 networks) now that the Tenant composition ignores spec.plan. The API reads one set from internal/quota instead of the plan of the tenant, checks a third network as before, and refuses a third profile with a 409 quota_exceeded. The quota answer and GET /v1/limits carry the profiles. MAX_PROFILES_PER_TENANT is no longer read: the limit is the quota's 2. A deployment that still sets it starts as before. The plan of a tenant is kept as it is read and is deprecated: it limits nothing. --- .github/workflows/docker.yml | 1 - cmd/phorge-api/main.go | 2 +- docs/README.md | 2 +- docs/reference/configuration.md | 7 +- docs/reference/endpoints.md | 4 +- docs/reference/images-and-instances.md | 8 +- docs/reference/limits-and-quotas.md | 30 +++--- docs/reference/networks.md | 2 +- docs/reference/tenants.md | 7 +- internal/api/api.go | 8 +- internal/api/instances.go | 8 +- internal/api/keyscopes_test.go | 5 +- internal/api/networks.go | 8 +- internal/api/networks_test.go | 13 ++- internal/api/profiles.go | 28 +++--- internal/api/profiles_test.go | 23 +++-- internal/api/quota.go | 8 +- internal/api/quota_test.go | 78 ++++++++++++--- internal/api/selfservice_test.go | 4 +- internal/api/tenants.go | 16 ++-- internal/api/tenants_test.go | 2 +- internal/config/config.go | 37 ++++--- internal/config/config_test.go | 17 ++-- internal/openapi/openapi.yaml | 51 ++++++---- internal/quota/quota.go | 69 ++++++------- internal/quota/quota_test.go | 128 +++++++++++-------------- internal/status/message.go | 12 +-- internal/tenants/tenants.go | 3 +- 28 files changed, 313 insertions(+), 268 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 007ca36..02d98e6 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -59,7 +59,6 @@ jobs: -e RATE_LIMIT_WRITES_PER_MINUTE=60 \ -e RATE_LIMIT_BURST=10 \ -e MAX_IMAGES_PER_TENANT=20 \ - -e MAX_PROFILES_PER_TENANT=20 \ -e INCUS_URL=https://incus.example.org \ -e INCUS_CLIENT_ID=ci-incus \ -e OIDC_TOKEN_URL=https://auth.example.org/application/o/token/ \ diff --git a/cmd/phorge-api/main.go b/cmd/phorge-api/main.go index 4cb6857..cb51f98 100644 --- a/cmd/phorge-api/main.go +++ b/cmd/phorge-api/main.go @@ -73,7 +73,7 @@ func main() { InstanceBootGrace: cfg.InstanceBootGrace, InstanceStuckAfter: cfg.InstanceStuckAfter, KeyMaxLifetime: cfg.APIKeyMaxLifetime, MaxTenantsPerUser: cfg.MaxTenantsPerUser, - RateLimitPerMinute: cfg.RateLimitPerMinute, RateLimitBurst: cfg.RateLimitBurst, MaxImagesPerTenant: cfg.MaxImagesPerTenant, MaxProfilesPerTenant: cfg.MaxProfilesPerTenant, + RateLimitPerMinute: cfg.RateLimitPerMinute, RateLimitBurst: cfg.RateLimitBurst, MaxImagesPerTenant: cfg.MaxImagesPerTenant, }, }) srv := &http.Server{Addr: cfg.ListenAddr, Handler: srvAPI.Handler(), ReadHeaderTimeout: 10 * time.Second} diff --git a/docs/README.md b/docs/README.md index 8fadadc..3197b5f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,7 +23,7 @@ Pages are grouped by what the reader wants, following [the organization's docume | [Networks](reference/networks.md) | Behavior of the network routes | | [Memberships and API keys](reference/memberships-and-api-keys.md) | Roles and personal keys | | [Terminal](reference/terminal.md) | Opening, protocol, closing codes and limits of a terminal | -| [Limits and quotas](reference/limits-and-quotas.md) | The plan of a tenant, the images, the rate of a caller | +| [Limits and quotas](reference/limits-and-quotas.md) | What every tenant may hold, the images, the rate of a caller | ## Explanation diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index e20456b..717153f 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1,7 +1,7 @@ --- type: reference audience: operator who deploys or configures the API -verified: 2026-11-06 +verified: 2026-11-11 --- # Configuration @@ -22,8 +22,7 @@ Configuration is read from the environment and the process refuses to start, lis | `INSTANCE_BOOT_GRACE` | yes | How long after a creation or a start a stop is refused (`409`, `starting`): a stop sent while the guest boots is lost and then hangs, and nothing Incus or Crossplane report says when the system inside listens (measured: the address and the interfaces are there before the agent). `0` never refuses | | `INSTANCE_STUCK_AFTER` | yes | How long a start or a stop may last before it is reported in `problems` | | `API_KEY_MAX_LIFETIME` | yes | The longest an API key lives: its `expiresAt` is capped to it. `0` caps nothing. A key always has an expiry, whatever the value | -| `MAX_PROFILES_PER_TENANT` | yes | How many profiles the users of a tenant may make (the three every tenant has do not count). Over it the answer is `409` with the code `quota_exceeded`. `0` is no limit | -| `MAX_TENANTS_PER_USER` | yes | How many tenants a person may own, whoever created them. Any person signed in with Authentik creates their own, with the `small` plan. Over it the answer is `409` with the code `quota_exceeded`. `0` is no limit | +| `MAX_TENANTS_PER_USER` | yes | How many tenants a person may own, whoever created them. Any person signed in with Authentik creates their own. Over it the answer is `409` with the code `quota_exceeded`. `0` is no limit | | `RATE_LIMIT_WRITES_PER_MINUTE` | yes | How many requests that create, change or delete one caller (a person or a key) may send a minute. Over it the answer is `429` with `Retry-After`. `0` limits nothing. It is kept in the memory of one replica: with several, a caller gets the limit of each | | `RATE_LIMIT_BURST` | yes | How many such requests a caller may send at once before the rate applies, at least `1` | | `MAX_IMAGES_PER_TENANT` | yes | How many images a tenant may hold. Over it the answer is `409` with the code `quota_exceeded`. `0` is no limit | @@ -38,3 +37,5 @@ Configuration is read from the environment and the process refuses to start, lis | `TERMINAL_RECHECK_INTERVAL` | yes | How often the right of the person and the state of the instance are checked again while a terminal is open, at least `1s`. Incus does not end a session whose right was removed, so the API does | Nothing that decides how the API behaves has a default in the code: a value is written in the deployment, where it is seen. The format constants (the `apikey-` prefix of the account of a key, the names of the annotations, how long creating a key waits for Crossplane) stay in the code. + +`MAX_PROFILES_PER_TENANT` is no longer read: how many profiles a tenant may make is the same limit for every tenant, 2, written in the code (see [Limits and quotas](limits-and-quotas.md)). A deployment that still sets it starts as before, the variable is ignored, and it can be removed from the deployment. diff --git a/docs/reference/endpoints.md b/docs/reference/endpoints.md index b15e1be..f35bc33 100644 --- a/docs/reference/endpoints.md +++ b/docs/reference/endpoints.md @@ -13,9 +13,9 @@ verified: 2026-11-08 | `GET /v1/whoami` | Who the credential stands for | | `GET /v1/limits` | What the API enforces on a request: the bounds of an instance and the value each takes when a request leaves it out, the longest names, and the ceilings of the deployment (profiles and images per tenant, tenants per person). Any credential; nothing about a tenant | | `GET /v1/tenants`, `GET /v1/tenants/{t}` | The tenants you hold a role on | -| `POST /v1/tenants`, `PATCH /v1/tenants/{t}`, `DELETE /v1/tenants/{t}` | Create a tenant for yourself (plan `small`), rename and delete it (its admins, the owner among them) | +| `POST /v1/tenants`, `PATCH /v1/tenants/{t}`, `DELETE /v1/tenants/{t}` | Create a tenant for yourself (every tenant has the same limits), rename and delete it (its admins, the owner among them) | | `GET`, `POST /v1/tenants/{t}/images`, `GET`, `DELETE /v1/tenants/{t}/images/{name}` | The images of a tenant: read with a role or a key tuple (`images:read`), write with `operator` or `images:write` | -| `GET /v1/tenants/{t}/quota` | What the plan of the tenant allows (instances, vCPU, memory, disk, networks) and what it holds. Read with the right of the instances | +| `GET /v1/tenants/{t}/quota` | What a tenant may hold (instances, vCPU, memory, disk, networks, profiles; the same for every tenant) and what it holds. Read with the right of the instances | | `GET`, `POST /v1/tenants/{t}/profiles`, `GET`, `DELETE /v1/tenants/{t}/profiles/{name}` | The sizes an instance can take: the profiles `s`, `m` and `l` every tenant is created with, and the ones its users make. Read with any role or `profiles:read`, write with `operator` or `profiles:write` | | `GET`, `POST /v1/tenants/{t}/networks`, `GET`, `PATCH`, `DELETE /v1/tenants/{t}/networks/{name}` | The networks of a tenant, which comes without one: read with a role (`viewer` and above) or `networks:read`, write with `operator` or `networks:write` | | `GET`, `POST /v1/tenants/{t}/memberships`, `GET`, `DELETE /v1/tenants/{t}/memberships/{name}` | The roles of the users: admins of the tenant, and the keys with `memberships:read` and `memberships:write` on it | diff --git a/docs/reference/images-and-instances.md b/docs/reference/images-and-instances.md index 1bc99db..7580216 100644 --- a/docs/reference/images-and-instances.md +++ b/docs/reference/images-and-instances.md @@ -1,7 +1,7 @@ --- type: reference audience: developer or operator who works with images and virtual machines through the API -verified: 2026-11-08 +verified: 2026-11-11 --- # Images and instances @@ -13,10 +13,10 @@ Both live in the namespace `t-` of the `phorge.fr` group. - **Deleting an image** that instances start from is a `409` that names them. Delete them first. - **Instances**: `cpu` 1 to 16, `memoryMiB` 256 to 65536, `diskGiB` 1 to 500, the rest is what the platform decides (what is not given is not sent). `PATCH` changes `running` (start and stop keep the same VM), `networks`, `cpu`, `memoryMiB`, `diskGiB` and `sshPublicKeys`, applied live. The memory of a **running** instance can only be raised: Incus refuses a lower one (`failed to resize memfd`), so the API answers `409` with the code `running` and the request is not sent, whether it comes by `memoryMiB` or by a profile that comes to less. To lower it, stop the instance, change the memory, then start it again: a change of size never starts or stops an instance by itself, the power state changes only when the request asks for it with `running`. The image, `nesting` and `secureBoot` cannot change: delete and create. - **The settings of an instance are read as they are in force.** `nesting`, `secureBoot` and `sshPublicKeys` of an instance read through the API are what the VM has, not only what the object says. The `Instance` kind has no default for them: an absent field means the instance did not say, and its profile, or else the default (nesting off, secure boot on, no key), applies. The platform writes the value in force in `status.nesting`, `status.secureBoot` and `status.sshPublicKeys`. The API reads each one from `spec` when the object says it (an instance created before the change has the three stored, written by the old defaults), else from `status`, else from the default, so an instance created without `secureBoot` is shown with `secureBoot: true` before and after the platform stops defaulting it. The field being absent is what counts, never its value: an absent `secureBoot` is not `false`. `spec` comes first because the API writes it (`PATCH` of `sshPublicKeys`) and the status follows a moment later, so the reply to a change shows the new keys; once the status has caught up both are the same, because what the instance says wins over its profile. A request that does not give these fields sends none of them. -- **The quota of the plan is checked by the API first**: a request that would pass it is refused with `409` and the code `quota_exceeded`, before Incus is asked (see [Limits and quotas](limits-and-quotas.md)). Incus stays the authority, and a refusal of its own, such as `Reached maximum number of instances`, comes back as the `problems` of the instance, in words (`This tenant has reached the maximum number of instances of its plan.`), and the instance becomes `Failed` after three minutes. Stopped VMs count. An instance whose first start failed is stuck: delete it and create it again. +- **The limits of the tenant are checked by the API first**: a request that would pass it is refused with `409` and the code `quota_exceeded`, before Incus is asked (see [Limits and quotas](limits-and-quotas.md)). Incus stays the authority, and a refusal of its own, such as `Reached maximum number of instances`, comes back as the `problems` of the instance, in words (`This tenant has reached the maximum number of instances it is allowed.`), and the instance becomes `Failed` after three minutes. Stopped VMs count. An instance whose first start failed is stuck: delete it and create it again. - **SSH keys are checked strictly.** The composition writes them into the cloud-init of the VM with a plain `printf`, one `- ` line per key, indented by two spaces, and nothing else protects it: a line break in a key would add a line of cloud-init, a command run as root in the VM. A key is accepted only as ` ` and at most a one word comment of letters, digits and `@._+=/-`. - **An instance is on one or several networks of its tenant** (`networks`, a list of 1 to 8, see [Networks](networks.md)): named in the request, or the only one of the tenant. `PATCH` replaces the list, live, without a restart. `network` is the deprecated way to give one. - **The size of an instance is a profile or its own values, never both.** `profile` is one of `GET /v1/tenants/{t}/profiles` (`s` 1 vCPU, 2 GiB, 64 GiB; `m` 2, 4, 128; `l` 4, 8, 256); the other way is `cpu`, `memoryMiB` and `diskGiB`, and what a request leaves out takes 1, 1024 and 10 (the Crossplane kind has no defaults, the API completes the size). A profile with a value is `422`, so is a profile that does not exist, and the answer lists the profiles. The body of an instance carries its `profile` and, in every case, the `cpu`, `memoryMiB` and `diskGiB` it comes to. `GET /v1/limits` has the bounds. - **A size changes in place**: `PATCH` with a `profile` moves the instance to it and removes its own values; an instance that has a profile leaves it by being given the three values together (a value alone is `422`, it would sit next to the profile). Incus applies it live on a stopped instance. -- **The resources of a plan hold two instances of its own profile size** (`small` two `s`, `medium` two `m`, `large` two `l`), and the count of instances is 2, 4 and 6: an instance that asks for more than what is left is refused with the limit it passes, before Incus is asked (see [Limits and quotas](limits-and-quotas.md)). -- **A user makes their own profiles** (`POST /v1/tenants/{t}/profiles`): CPU, memory and disk, all three given, under a name of 1 to 32 characters (`s`, `m`, `l` and `default` are taken, `422`). They are listed after the three every tenant has, with a phase and what is wrong in words. An instance takes one as it takes `s`, `m` or `l`, and counts in the quota what it comes to. Deleting one is refused (`409`, `in_use`) while an instance has it, and names the instances; `s`, `m` and `l` are not changed nor deleted (`403`). A tenant holds at most `MAX_PROFILES_PER_TENANT` of them. A profile may also say two settings of an instance, `secureBoot` and `sshPublicKeys` (up to 20, checked as the keys of an instance, see the item on SSH keys). They are written on the object only when the request gives them: a profile that does not say one has none, and the body shows none, so an absent `secureBoot` is not `false`. An empty list is the same as none. An instance takes the settings of its profile unless it says its own: keys given by the instance replace the profile's, they do not add to them. A profile never has a network nor `nesting` (Incus refuses nesting on a profile of a tenant project, so nesting stays a setting of the instance): a request with either is `400`, an unknown field. Changing a profile in place is not in the API: make another one and move the instances to it. +- **The resources of every tenant hold two instances of the profile `s`, or one `m`**: 2 instances, 2 vCPU, 4 GiB of memory and 128 GiB of disk, the same for every tenant. An instance that asks for more than what is left is refused with the limit it passes, before Incus is asked (see [Limits and quotas](limits-and-quotas.md)). +- **A user makes their own profiles** (`POST /v1/tenants/{t}/profiles`): CPU, memory and disk, all three given, under a name of 1 to 32 characters (`s`, `m`, `l` and `default` are taken, `422`). They are listed after the three every tenant has, with a phase and what is wrong in words. An instance takes one as it takes `s`, `m` or `l`, and counts in the quota what it comes to. Deleting one is refused (`409`, `in_use`) while an instance has it, and names the instances; `s`, `m` and `l` are not changed nor deleted (`403`). A tenant holds at most 2 of them (the same for every tenant, a third is `409`, `quota_exceeded`, `this tenant has 2 profiles out of 2 allowed (s, m and l do not count): delete one first`). A profile may also say two settings of an instance, `secureBoot` and `sshPublicKeys` (up to 20, checked as the keys of an instance, see the item on SSH keys). They are written on the object only when the request gives them: a profile that does not say one has none, and the body shows none, so an absent `secureBoot` is not `false`. An empty list is the same as none. An instance takes the settings of its profile unless it says its own: keys given by the instance replace the profile's, they do not add to them. A profile never has a network nor `nesting` (Incus refuses nesting on a profile of a tenant project, so nesting stays a setting of the instance): a request with either is `400`, an unknown field. Changing a profile in place is not in the API: make another one and move the instances to it. diff --git a/docs/reference/limits-and-quotas.md b/docs/reference/limits-and-quotas.md index 0de053d..9f9f68d 100644 --- a/docs/reference/limits-and-quotas.md +++ b/docs/reference/limits-and-quotas.md @@ -1,37 +1,39 @@ --- type: reference audience: developer or operator who needs to know what a caller or a tenant may do, and how the API says no -verified: 2026-11-08 +verified: 2026-11-11 --- # Limits and quotas -Three things bound what one caller or one tenant can create. Each has its own answer. +Four things bound what one caller or one tenant can create. Each has its own answer. | What | Where it is decided | Answer when it is passed | |---|---|---| -| What a tenant holds: instances, vCPU, memory, disk, networks | The plan of the tenant (`small`, `medium`, `large`), which Incus enforces as limits of the tenant's project, and which the API checks first | `409`, code `quota_exceeded`, a message that says which limit | +| What a tenant holds: instances, vCPU, memory, disk, networks | The same limits for every tenant, which Incus enforces as limits of the tenant's project and which the API checks first | `409`, code `quota_exceeded`, a message that says which limit | +| How many profiles its users make | The same limits for every tenant, checked by the API (Incus has no limit for it) | `409`, code `quota_exceeded`, a message that says which limit | | How many images a tenant holds | `MAX_IMAGES_PER_TENANT`, checked by the API | `409`, code `quota_exceeded` | -| How many profiles its users make | `MAX_PROFILES_PER_TENANT`, checked by the API | `409`, code `quota_exceeded` | | How fast one caller writes | `RATE_LIMIT_WRITES_PER_MINUTE` and `RATE_LIMIT_BURST`, checked by the API | `429`, code `rate_limited`, header `Retry-After` in seconds | -## The plan of a tenant +## What a tenant may hold -| Plan | Instances | vCPU | Memory | Disk | Networks | +There is one set of limits and every tenant has it: + +| Instances | vCPU | Memory | Disk | Networks | Profiles | |---|---|---|---|---|---| -| `small` | 2 | 2 | 4 GiB | 128 GiB | 1 | -| `medium` | 4 | 4 | 8 GiB | 256 GiB | 2 | -| `large` | 6 | 8 | 16 GiB | 512 GiB | 3 | +| 2 | 2 | 4 GiB | 128 GiB | 2 | 2 | + +The CPU, the memory and the disk hold two instances of the profile `s`, or one `m`. The profiles are the ones the users of the tenant make: `s`, `m` and `l` are created with every tenant, nobody changes them, and they are not counted. The disk of the Incus project is 128 GiB plus 512 MiB for each of the 2 VMs (the state of a VM), 132096 MiB; the API checks the 128 GiB. -The CPU, the memory and the disk of each plan hold two instances of its own profile size: `small` two `s`, `medium` two `m`, `large` two `l`. The count of instances is the plan's own (2, 4 and 6), for instances smaller than the profile. +`GET /v1/tenants/{t}/quota` answers the limits and what the tenant holds (`used`), with the profiles in both. A stopped instance counts, as it does for Incus; an instance that has a profile counts what the profile comes to, one of the three every tenant has or one its users made. `GET /v1/limits` says the same number for the profiles (`profile.maxPerTenant`, 2). The numbers are written twice, here (`internal/quota`) and in the Tenant composition of Hangar; a test of each side says the same numbers. -`GET /v1/tenants/{t}/quota` answers the plan, the limits and what the tenant holds (`used`). A stopped instance counts, as it does for Incus; an instance that has a profile counts what the profile comes to, one of the three every tenant has or one its users made. The table is written twice, here and in the Tenant composition of Hangar; a test of each side says the same numbers. +Creating an instance, a network or a profile that would pass a limit is refused by the API before Incus is asked, and the message says which and what to do: `this tenant has 2 instances out of 2 allowed: delete one first`, `this tenant has 2 networks out of 2 allowed: delete one first`, `this tenant has 2 profiles out of 2 allowed (s, m and l do not count): delete one first`, `this instance needs 200 GiB of disk and the tenant has 0 out of 128 GiB allowed`. The count of instances comes first, then the CPU, the memory and the disk. Incus stays the authority: a request that the API lets through can still be refused there (a `PATCH` that grows an instance is only checked by Incus), and its refusal is told in words in `problems` of the object. An object that is being deleted still counts, as it does for Incus, until it is gone. -Creating an instance or a network that would pass a limit is refused by the API before Incus is asked, and the message says which: `this tenant has 2 instances out of 2 allowed by its plan small: delete one first`, `this instance needs 200 GiB of disk and the tenant has 0 out of 128 GiB allowed by its plan small`. The count comes first, then the CPU, the memory and the disk. Incus stays the authority: a request that the API lets through can still be refused there (a `PATCH` that grows an instance is only checked by Incus), and its refusal is told in words in `problems` of the object. +A profile bigger than what is left is refused with the limit it passes when an instance takes it: a `l`, or a third `s`. -The plan of a tenant is not changed through the API: the platform administrators raise the limits of a tenant on request, on its `Tenant` object. +### The plan is deprecated -A profile bigger than what is left of a plan is refused with the limit it passes: a `l` on a `small` plan, or a third `s` on it. The numbers of the plans are written twice, in the Tenant composition of Hangar and in `internal/quota`, and a test of each says the same. +There used to be three plans (`small`, `medium`, `large`) that set these limits, and only the platform administrators changed them. There is no choice of plan any more: the `plan` of a tenant limits nothing and changing it changes no limit. It is still in the body of a tenant and in the answer of the quota, and a plan other than `small` is refused with `403` on creation and on change, as before; a tenant is created without one. It stays only until the console stops reading it, then it is removed from the API. An existing tenant has the same limits as a new one, whatever plan it was created with. ## The rate diff --git a/docs/reference/networks.md b/docs/reference/networks.md index 6dae46d..8170c73 100644 --- a/docs/reference/networks.md +++ b/docs/reference/networks.md @@ -12,7 +12,7 @@ A network is a `Network` object of the `phorge.fr` group in the tenant's namespa - **The range is the user's choice**: `ipv4` is the address of the network with a prefix, such as `10.77.1.0/24`, in a private range (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`), with a prefix from `/16` to `/29`. A host address (`10.77.1.5/24`), a public or IPv6 range or a prefix out of bounds is refused with `422`. The gateway is the first host of the range. Without `ipv4` Incus chooses the range. The range is checked against the platform's own ranges (`range_reserved`, `409`) and against the networks of every tenant (`range_in_use`, `409`, without saying whose): Incus accepts two networks on the same range, and their instances would not tell them apart. The answer carries `ipv4` once it is known: the range the user chose is there at once, and the range Incus chose is read from Incus when a network is read (`GET` of one network or of the list), with the token of the person: the API trades it at Authentik for a token of Incus, kept for a few minutes, and reads the state of the networks of the project with it (the address and the netmask of the gateway: Incus gives a person who only views the project an empty config, and the state is what they may see). Incus decides what the person sees. It is an addition to the answer, not a condition of it: for a key, a person Incus does not let see the project, a network Incus does not know yet, or an Incus that does not answer, `ipv4` is absent and the call succeeds. The answer to the create does not have it for a range Incus chooses. - **IPv6** is a local range too: `ipv6` is a `/64` in `fd00::/8`, given as the address of the network (`fd42:1:2:3::/64`), and Incus takes `::1` as the gateway. A global range, another prefix or a host address is refused with `422`, and a range another network already has with `409` (`range_in_use`). Without `ipv6` Incus chooses one, and the answer carries it like `ipv4`. - **Edit** (`PATCH`, `202`) changes the `description`, `ipv4` and `ipv6`; what is absent stays. The ranges get the checks of the creation, a range the network has already does not count against itself, and giving the same range again changes nothing. **A range that was given cannot be removed** (the cluster refuses it, as Incus would keep the old one): give another range, or delete the network. **Changing `ipv4` cuts the running instances of the network off** until they ask for an address again (measured: a running VM is cut off until it runs its DHCP client again), so the API refuses it with `409` and the code `running` while an instance runs on the network, naming the instances. Stop them (or take them off the network), change the range, then start them: nothing is stopped for the user, see [Images and instances](images-and-instances.md), and a stopped instance takes the new range when it starts. When Incus chose the range and the API cannot read it, a new range counts as a change. Changing `ipv6` cuts nobody (the running instances learn it from the router advertisements within a minute), so it is accepted while they run. -- **The plan limits how many** (`small` 1, `medium` 2, `large` 3): the next one never becomes ready and `problems` says `This tenant has reached the maximum number of networks of its plan.` +- **A tenant holds at most 2 networks**, the same for every tenant: a third is refused by the API before Incus is asked, with `409`, the code `quota_exceeded` and `this tenant has 2 networks out of 2 allowed: delete one first` (see [Limits and quotas](limits-and-quotas.md)). A network that Incus refuses all the same says `This tenant has reached the maximum number of networks it is allowed.` in `problems`. - **Delete** is done in the foreground: `202`, then the network stays as `Deleting` until Incus has deleted it. A network that an instance is attached to, whichever of its networks it is, is refused with `409` and the names of the instances: delete them first. For a few seconds after the last one is gone, Crossplane still refuses, with a `409` that names nobody; the deletion Crossplane refused is replayed by itself once the last instance is gone. - **An instance is attached to one or several networks** (`networks` on the instance, one NIC each in this order: `eth0`, `eth1`, ... in the VM; `network` is the deprecated way to give one, and the first of `networks` is still read in it). Give 1 to 8 names, none twice. When a request to create an instance names none, the only network of the tenant is used; with none the request is refused (`422`, `the tenant has no network: create one first`), with several it is too and the networks are listed. A network that is not `Ready` yet is refused (`409`, `network_not_ready`), as an image is. Each network of the instance has its addresses (`ipv4`, `ipv6`) in `networks` once the VM has them. `PATCH networks` replaces the list, live: a network added is plugged into the running VM and one taken out is unplugged, the VM is not stopped or restarted (a NIC that is plugged in is `down` in the guest until the guest configures it, a restart does it). A network that joins must exist and be `Ready`; one the instance already has is left alone. - **Who may**: reading is for every role of the tenant (`viewer` and above) or a key with `networks:read`, writing for `operator` and `admin` or a key with `networks:write`. diff --git a/docs/reference/tenants.md b/docs/reference/tenants.md index 9164a16..eaf9118 100644 --- a/docs/reference/tenants.md +++ b/docs/reference/tenants.md @@ -1,14 +1,15 @@ --- type: reference audience: developer or operator who works with tenants through the API -verified: 2026-11-08 +verified: 2026-11-11 --- # Tenants A tenant is a `Tenant` object of the `phorge.fr` group in `phorge-system` (`internal/kube/tenants.go`); Crossplane makes its namespace `t-`, its Incus project, and its network. -- **Create** is for any person signed in with Authentik, for themselves: the owner is the caller (`owner` is left out or is their own email, another one is `403`), the plan is `small` (another one is `403`: the platform administrators change a plan on request, where the platform is run), and a person owns at most `MAX_TENANTS_PER_USER` tenants (`409`, `quota_exceeded`, counted by owner, whoever created them). A key never creates a tenant. `GET /v1/whoami` says `canCreateTenants`. It answers `202` with a `Location`: poll it until `phase` is `Ready`. `phase` is `Provisioning`, `Ready`, `Deleting`, or `Failed` when the tenant has not become ready for 3 minutes and either `problems` says what is wrong in words made for the user (a limit of the plan that is reached, or that the platform could not complete a step yet) or the platform could not apply what makes the tenant for 3 minutes (the same rule holds for every kind: an object whose composition fails is `Failed` with a sentence that the platform administrators can see why, instead of staying `Provisioning`). It never carries what Crossplane, a provider or Incus report: those stay in `status.problems` of the object, for the administrators. -- **Patch** changes `displayName`: the admins of the tenant, the owner among them, do. The `plan` is not changed through the API (`403`): a person who needs another one asks the platform administrators, who change it on the `Tenant` object. A key never patches a tenant unless it holds `tenants:write`. The owner cannot change (it is an OpenFGA tuple): a body that holds it is refused. To hand a tenant over, give the new person the `admin` role with a membership. +- **Create** is for any person signed in with Authentik, for themselves: the owner is the caller (`owner` is left out or is their own email, another one is `403`), every tenant has the same limits (2 instances, 2 vCPU, 4 GiB of memory, 128 GiB of disk, 2 networks and 2 profiles, see [Limits and quotas](limits-and-quotas.md)) so a body leaves `plan` out, and a person owns at most `MAX_TENANTS_PER_USER` tenants (`409`, `quota_exceeded`, counted by owner, whoever created them). A key never creates a tenant. `GET /v1/whoami` says `canCreateTenants`. It answers `202` with a `Location`: poll it until `phase` is `Ready`. `phase` is `Provisioning`, `Ready`, `Deleting`, or `Failed` when the tenant has not become ready for 3 minutes and either `problems` says what is wrong in words made for the user (a limit that is reached, or that the platform could not complete a step yet) or the platform could not apply what makes the tenant for 3 minutes (the same rule holds for every kind: an object whose composition fails is `Failed` with a sentence that the platform administrators can see why, instead of staying `Provisioning`). It never carries what Crossplane, a provider or Incus report: those stay in `status.problems` of the object, for the administrators. +- **Patch** changes `displayName`: the admins of the tenant, the owner among them, do. The `plan` is deprecated and changes no limit, since every tenant has the same ones: a body that gives it is `403`, as it always was. A key never patches a tenant unless it holds `tenants:write`. The owner cannot change (it is an OpenFGA tuple): a body that holds it is refused. To hand a tenant over, give the new person the `admin` role with a membership. - **Delete** is for the admins of the tenant, the owner among them. It removes what the tenant holds first (its instances, then its memberships, then its networks, then the profiles its users made, then its images), then the tenant, all in the foreground: `202`, then the tenant stays as `Deleting` until everything it is made of is gone (about two minutes, longer with a virtual machine to stop), and a `404` on a later get means the person no longer sees the tenant: it is gone or about to be, since the rights of the person (the owner tuple) go with the tenant a little before its last resources do (measured: the `404` came while the tenant was still `Deleting`). Stop polling on it, and do not take it for proof that Incus is empty. It destroys the virtual machines of the tenant. The order is not cosmetic: the platform deletes what a tenant holds in its namespace only while the namespace exists, so the tenant waits for them (see the Hangar issue 185). - Whoever cannot read a tenant is told it does not exist (`404`), whoever can but may not do this gets `403`. Bodies are JSON only, 64 KiB at most, with no field the API does not know. +- **The `plan` is deprecated.** There is no choice of plan: every tenant has the same limits, whatever its `plan`. The field stays in the body of a tenant (`small` for a new one, what the object holds for an existing one) and in the answer of `GET /v1/tenants/{t}/quota`, only so that what reads it keeps working until the console stops using it; it is then removed from the API. A creation without a plan works, and a plan other than `small` on creation or on change is `403`. diff --git a/internal/api/api.go b/internal/api/api.go index 8f8ddc1..b5cdf86 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -35,9 +35,9 @@ type Settings struct { // RateLimitPerMinute is how many requests that create, change or delete a caller may send a minute, in bursts of RateLimitBurst; // 0 limits nothing. RateLimitPerMinute, RateLimitBurst int - // MaxImagesPerTenant is how many images a tenant may hold, and MaxProfilesPerTenant how many profiles its users may make; 0 is - // no limit. - MaxImagesPerTenant, MaxProfilesPerTenant int + // MaxImagesPerTenant is how many images a tenant may hold, 0 is no limit. The other limits of a tenant are the same for every + // one, in internal/quota. + MaxImagesPerTenant int } // Deps is what the routes need. @@ -76,7 +76,7 @@ func Register(s *server.Server, d Deps) { authn := func(h http.Handler) http.Handler { return d.Auth.Middleware(limited(limiter, h)) } (&tenantRoutes{base: b, store: d.Tenants, settings: d.Settings}).register(s, authn) (&imageRoutes{base: b, store: d.Images, instances: d.Instances, settings: d.Settings}).register(s, authn) - (&profileRoutes{base: b, store: d.Profiles, instances: d.Instances, settings: d.Settings}).register(s, authn) + (&profileRoutes{base: b, store: d.Profiles, instances: d.Instances}).register(s, authn) ("aRoutes{base: b, instances: d.Instances, networks: d.Networks, profiles: d.Profiles}).register(s, authn) networks := &networkRoutes{base: b, store: d.Networks, instances: d.Instances, profiles: d.Profiles} if d.Terminal != nil { diff --git a/internal/api/instances.go b/internal/api/instances.go index 7a81a19..9358ee5 100644 --- a/internal/api/instances.go +++ b/internal/api/instances.go @@ -196,9 +196,9 @@ func (i *instanceRoutes) create(w http.ResponseWriter, r *http.Request) { return } req.Networks, req.Network = nws, "" - // The plan limits the count and the total of CPU, memory and disk: say which before asking Incus, who would leave an instance + // The limits of the tenant hold the count and the total of CPU, memory and disk: say which before asking Incus, who would leave an instance // that never becomes ready. The profiles the users made are read for it, an instance counts what its profile comes to. - plan, used, made, ok := holdings(w, r, &i.base, i.store, i.networks, i.profiles, tenant) + _, used, made, ok := holdings(w, r, &i.base, i.store, i.networks, i.profiles, tenant) if !ok { return } @@ -211,7 +211,7 @@ func (i *instanceRoutes) create(w http.ResponseWriter, r *http.Request) { // A size is complete: the XRD has no defaults, so what the request left out takes the ones of the API. req = req.WithDefaultSize() cpu, mem, disk := quota.SizeAsked(req, made) - if e := quota.CheckInstance(plan, used, cpu, mem, disk); e != nil { + if e := quota.CheckInstance(used, cpu, mem, disk); e != nil { quotaExceeded(w, e) return } @@ -226,7 +226,7 @@ func (i *instanceRoutes) create(w http.ResponseWriter, r *http.Request) { return } i.log.Info("instance created", "tenant", tenant, "instance", in.Name, "by", id.Subject) - // Accepted, not created: it takes about a minute. The quota of the plan is Incus's, its refusal comes back in problems. + // Accepted, not created: it takes about a minute. The quota of the tenant is Incus's, its refusal comes back in problems. w.Header().Set("Location", "/v1/tenants/"+tenant+"/instances/"+in.Name) writeJSON(w, http.StatusAccepted, i.body(in, made)) } diff --git a/internal/api/keyscopes_test.go b/internal/api/keyscopes_test.go index a515ad5..a76a290 100644 --- a/internal/api/keyscopes_test.go +++ b/internal/api/keyscopes_test.go @@ -10,8 +10,7 @@ import ( // What the scopes of a key let it do on the routes, with the tuples the ApiKey composition writes for them (one per scope and tenant): // the key passes the routes of its scopes and only those. func TestAKeyWithTheScopesOfTheNetworksTheProfilesAndTheTenantPassesTheirRoutes(t *testing.T) { - e := newEnv(t) - e.networks.put("demo", readyNetwork("lan")) + e := newEnv(t) // the tenant has a network, net: the key makes a second one, the most there is room for e.profiles.put("demo", madeProfile("web", 1, 1024, 10)) e.images.put("demo", readyImage("debian")) for _, c := range []struct { @@ -20,7 +19,7 @@ func TestAKeyWithTheScopesOfTheNetworksTheProfilesAndTheTenantPassesTheirRoutes( }{ // the networks {"GET", "/v1/tenants/demo/networks", "", http.StatusOK}, - {"GET", "/v1/tenants/demo/networks/lan", "", http.StatusOK}, + {"GET", "/v1/tenants/demo/networks/net", "", http.StatusOK}, {"POST", "/v1/tenants/demo/networks", `{"name":"two"}`, http.StatusAccepted}, {"DELETE", "/v1/tenants/demo/networks/two", "", http.StatusAccepted}, // the profiles diff --git a/internal/api/networks.go b/internal/api/networks.go index 7f1a3a2..d40f745 100644 --- a/internal/api/networks.go +++ b/internal/api/networks.go @@ -147,12 +147,12 @@ func (n *networkRoutes) create(w http.ResponseWriter, r *http.Request) { return } tenant := r.PathValue("t") - // The plan limits how many: say it before asking, with a code, instead of leaving a network that never becomes ready. - plan, used, _, ok := holdings(w, r, &n.base, n.instances, n.store, n.profiles, tenant) + // The tenant is limited in how many: say it before asking, with a code, instead of leaving a network that never becomes ready. + _, used, _, ok := holdings(w, r, &n.base, n.instances, n.store, n.profiles, tenant) if !ok { return } - if e := quota.CheckNetwork(plan, used); e != nil { + if e := quota.CheckNetwork(used); e != nil { quotaExceeded(w, e) return } @@ -169,7 +169,7 @@ func (n *networkRoutes) create(w http.ResponseWriter, r *http.Request) { return } n.log.Info("network created", "tenant", tenant, "network", nw.Name, "by", id.Subject) - // Accepted, not created: Incus takes a few seconds, and the plan's limit on networks is Incus's, its refusal comes back in + // Accepted, not created: Incus takes a few seconds, and the limit on networks is Incus's, its refusal comes back in // problems. w.Header().Set("Location", "/v1/tenants/"+tenant+"/networks/"+nw.Name) writeJSON(w, http.StatusAccepted, n.body(nw)) diff --git a/internal/api/networks_test.go b/internal/api/networks_test.go index 504b7c0..8fc99ab 100644 --- a/internal/api/networks_test.go +++ b/internal/api/networks_test.go @@ -17,7 +17,7 @@ func readyNetwork(name string) compute.Network { } func TestNetworksWhoMayDoWhat(t *testing.T) { - const coll, item = "/v1/tenants/demo/networks", "/v1/tenants/demo/networks/lan" + const coll, item = "/v1/tenants/demo/networks", "/v1/tenants/demo/networks/net" create := `{"name":"new"}` tests := []struct { who string @@ -35,8 +35,7 @@ func TestNetworksWhoMayDoWhat(t *testing.T) { } for _, tt := range tests { t.Run(tt.who, func(t *testing.T) { - e := newEnv(t) - e.networks.put("demo", readyNetwork("lan")) + e := newEnv(t) // the tenant has a network, net, and room for one more for _, c := range []struct { method, path, body string want int @@ -266,11 +265,11 @@ func TestCreateInstanceCompletesItsSize(t *testing.T) { cpu, mem, dsk int }{ "no size": {`{"name":"a","image":"debian"}`, 1, 1024, 10}, - "only a cpu": {`{"name":"b","image":"debian","cpu":4}`, 4, 1024, 10}, + "only a cpu": {`{"name":"b","image":"debian","cpu":2}`, 2, 1024, 10}, "only a disk": {`{"name":"c","image":"debian","diskGiB":50}`, 1, 1024, 50}, "all three": {`{"name":"d","image":"debian","cpu":2,"memoryMiB":2048,"diskGiB":20}`, 2, 2048, 20}, } { - // a tenant of its own for each case: a plan holds two instances + // a tenant of its own for each case: the limits hold two instances e := newEnv(t) e.images.put("demo", readyImage("debian")) if code := call(t, e, "POST", "/v1/tenants/demo/instances", "user", tt.body); code != http.StatusAccepted { @@ -357,8 +356,8 @@ func TestCreateNetworkRefusesARangeAnotherTenantHas(t *testing.T) { if code := call(t, e, "POST", "/v1/tenants/demo/networks", "operator", `{"name":"lan","ipv4":"10.78.5.0/24"}`); code != http.StatusAccepted { t.Errorf("a free range: status %d, want 202", code) } - // Without a range there is nothing to compare: Incus chooses. - if code := call(t, e, "POST", "/v1/tenants/demo/networks", "operator", `{"name":"auto"}`); code != http.StatusAccepted { + // Without a range there is nothing to compare: Incus chooses. A tenant of its own: demo now has the two networks it may. + if code := call(t, newEnv(t), "POST", "/v1/tenants/demo/networks", "operator", `{"name":"auto"}`); code != http.StatusAccepted { t.Errorf("no range: status %d, want 202", code) } } diff --git a/internal/api/profiles.go b/internal/api/profiles.go index 1ce99f9..b61b8b5 100644 --- a/internal/api/profiles.go +++ b/internal/api/profiles.go @@ -23,7 +23,6 @@ type profileRoutes struct { base store compute.ProfileStore instances compute.InstanceStore - settings Settings } func (p *profileRoutes) register(s *server.Server, authn func(http.Handler) http.Handler) { @@ -114,17 +113,16 @@ func (p *profileRoutes) create(w http.ResponseWriter, r *http.Request) { return } tenant := r.PathValue("t") - // A tenant holds a few profiles, not a thousand: each one is an object of the cluster and a profile of Incus. - if max := p.settings.MaxProfilesPerTenant; max > 0 { - have, err := p.store.List(r.Context(), tenant) - if err != nil { - p.storeError(w, err, "profile") - return - } - if e := quota.CheckCount("profiles", len(have), max, "this tenant holds too many profiles"); e != nil { - quotaExceeded(w, e) - return - } + // A tenant holds a few profiles, not a thousand: each one is an object of the cluster and a profile of Incus, which has no limit + // for it. The profiles every tenant has (s, m and l) are not in the list of the store, nor counted. + have, err := p.store.List(r.Context(), tenant) + if err != nil { + p.storeError(w, err, "profile") + return + } + if e := quota.CheckProfile(quota.Used{Profiles: len(have)}); e != nil { + quotaExceeded(w, e) + return } pr, err := p.store.Create(r.Context(), tenant, req) if errors.Is(err, resource.ErrNotFound) { @@ -204,7 +202,7 @@ type limitsBody struct { Profile struct { MaxNameLength int `json:"maxNameLength"` MaxDescriptionLength int `json:"maxDescriptionLength"` - // MaxPerTenant is how many profiles the users of a tenant may make, 0 is no limit. + // MaxPerTenant is how many profiles the users of a tenant may make: the limit of every tenant, see GET /v1/tenants/{t}/quota. MaxPerTenant int `json:"maxPerTenant"` } `json:"profile"` Image struct { @@ -218,7 +216,7 @@ type limitsBody struct { } // limits answers GET /v1/limits: what the API enforces on a request, and the ceilings the deployment sets. It holds nothing about a -// tenant: the plan of a tenant is a limit of its own, see GET /v1/tenants/{t}/quota. +// tenant: what a tenant may hold is a limit of its own, see GET /v1/tenants/{t}/quota. func limits(s Settings) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { l := compute.CurrentLimits() @@ -227,7 +225,7 @@ func limits(s Settings) http.Handler { b.Instance.MaxSSHKeys, b.Instance.MaxNameLength = l.MaxSSHKeys, 63 b.Network.MaxNameLength, b.Network.MaxDescriptionLength = l.MaxNetworkName, l.MaxNetworkDescription b.Profile.MaxNameLength, b.Profile.MaxDescriptionLength = 32, compute.MaxProfileDescription - b.Profile.MaxPerTenant = s.MaxProfilesPerTenant + b.Profile.MaxPerTenant = quota.PerTenant.Profiles b.Image.MaxPerTenant = s.MaxImagesPerTenant b.Tenant.MaxPerUser = s.MaxTenantsPerUser writeJSON(w, http.StatusOK, b) diff --git a/internal/api/profiles_test.go b/internal/api/profiles_test.go index 3ffb220..81c5bc9 100644 --- a/internal/api/profiles_test.go +++ b/internal/api/profiles_test.go @@ -46,16 +46,17 @@ func TestTheBuiltinProfilesDescribeTheirOwnNumbers(t *testing.T) { func TestLimitsPublishTheCeilingsOfTheDeployment(t *testing.T) { set := testSettings - set.MaxProfilesPerTenant, set.MaxImagesPerTenant, set.MaxTenantsPerUser = 7, 9, 3 + set.MaxImagesPerTenant, set.MaxTenantsPerUser = 9, 3 e := newEnvWith(t, set) var body limitsBody mustDecode(t, e.do(t, "GET", "/v1/limits", "mallory", ""), &body) - if body.Profile.MaxPerTenant != 7 || body.Image.MaxPerTenant != 9 || body.Tenant.MaxPerUser != 3 { + // the profiles are limited the same for every tenant, by the quota and not by the deployment + if body.Profile.MaxPerTenant != 2 || body.Image.MaxPerTenant != 9 || body.Tenant.MaxPerUser != 3 { t.Errorf("ceilings = %+v %+v %+v", body.Profile, body.Image, body.Tenant) } // 0 is no limit and is said as 0 mustDecode(t, newEnv(t).do(t, "GET", "/v1/limits", "mallory", ""), &body) - if body.Profile.MaxPerTenant != 0 || body.Image.MaxPerTenant != 0 || body.Tenant.MaxPerUser != 0 { + if body.Profile.MaxPerTenant != 2 || body.Image.MaxPerTenant != 0 || body.Tenant.MaxPerUser != 0 { t.Errorf("no limit set, got %+v %+v %+v", body.Profile, body.Image, body.Tenant) } } @@ -397,17 +398,15 @@ func TestMakeAProfileRefusesBadSettings(t *testing.T) { } } -func TestATenantHoldsAtMostSomeProfiles(t *testing.T) { - s := testSettings - s.MaxProfilesPerTenant = 2 - e := newEnvWith(t, s) +func TestATenantHoldsAtMostTwoProfiles(t *testing.T) { + e := newEnv(t) e.profiles.put("demo", madeProfile("one", 1, 1024, 10)) const sz = `"cpu":1,"memoryMiB":1024,"diskGiB":10` if code := call(t, e, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"two",`+sz+`}`); code != http.StatusAccepted { t.Fatalf("the second: status %d", code) } rec := e.do(t, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"three",`+sz+`}`) - if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"quota_exceeded"`) || !strings.Contains(rec.Body.String(), "2 out of 2") { + if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), `"quota_exceeded"`) || !strings.Contains(rec.Body.String(), "2 profiles out of 2 allowed") { t.Errorf("the third: status %d: %s", rec.Code, rec.Body) } } @@ -454,20 +453,20 @@ func TestDeleteAProfileInUseNamesTheInstances(t *testing.T) { func TestAnInstanceTakesAProfileTheUserMade(t *testing.T) { e := newEnv(t) e.images.put("demo", readyImage("debian")) - e.profiles.put("demo", madeProfile("web", 3, 3072, 30)) + e.profiles.put("demo", madeProfile("web", 2, 2048, 30)) rec := e.do(t, "POST", "/v1/tenants/demo/instances", "user", `{"name":"web1","image":"debian","profile":"web"}`) if rec.Code != http.StatusAccepted { t.Fatalf("status %d: %s", rec.Code, rec.Body) } var body instanceBody mustDecode(t, rec, &body) - if body.Profile != "web" || body.CPU != 3 || body.MemoryMiB != 3072 || body.DiskGiB != 30 { + if body.Profile != "web" || body.CPU != 2 || body.MemoryMiB != 2048 || body.DiskGiB != 30 { t.Errorf("body = %+v: the profile, and what the user's own profile comes to", body) } // the list and one by one say it too var got instanceBody mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/instances/web1", "viewer", ""), &got) - if got.CPU != 3 { + if got.CPU != 2 { t.Errorf("get: %+v", got) } var list struct { @@ -498,7 +497,7 @@ func TestAProfileTheUserMadeCountsInTheQuota(t *testing.T) { e := newEnv(t) withTiny(e) e.networks.put("tiny", readyNetwork("net")) - e.profiles.put("tiny", madeProfile("big", 1, 1024, 200)) // the small plan holds 128 GiB of disk + e.profiles.put("tiny", madeProfile("big", 1, 1024, 200)) // a tenant holds 128 GiB of disk rec := e.do(t, "POST", "/v1/tenants/tiny/instances", "operator", `{"name":"a","image":"debian","profile":"big"}`) if rec.Code != http.StatusConflict || !strings.Contains(quotaCode(t, rec.Body.String()), "200 GiB of disk") { t.Errorf("status %d: %s", rec.Code, rec.Body) diff --git a/internal/api/quota.go b/internal/api/quota.go index ab4c6b0..a522999 100644 --- a/internal/api/quota.go +++ b/internal/api/quota.go @@ -14,7 +14,8 @@ import ( "github.com/phorge-fr/phorge-api/internal/tenants" ) -// quotaRoutes tell a tenant what its plan allows and what it holds, so that a client draws what is left. +// quotaRoutes tell a tenant what it is allowed to hold, the same for every tenant, and what it holds, so that a client draws what is +// left. type quotaRoutes struct { base instances compute.InstanceStore @@ -27,6 +28,7 @@ func (q *quotaRoutes) register(s *server.Server, authn func(http.Handler) http.H } type quotaBody struct { + // Plan is deprecated: it changes no limit, and goes when the console stops reading it. Plan tenants.Plan `json:"plan"` Limits quota.Limits `json:"limits"` Used quota.Used `json:"used"` @@ -38,10 +40,10 @@ func (q *quotaRoutes) get(w http.ResponseWriter, r *http.Request) { if !ok { return } - writeJSON(w, http.StatusOK, quotaBody{Plan: plan, Limits: quota.LimitsOf(plan), Used: used}) + writeJSON(w, http.StatusOK, quotaBody{Plan: plan, Limits: quota.PerTenant, Used: used}) } -// holdings reads the plan of a tenant, what it holds, and the profiles its users made (an instance counts what its profile comes to), +// holdings reads the plan of a tenant (deprecated, it limits nothing), what it holds, and the profiles its users made (an instance counts what its profile comes to), // or answers. func holdings(w http.ResponseWriter, r *http.Request, b *base, instances compute.InstanceStore, networks compute.NetworkStore, profiles compute.ProfileStore, tenant string) (tenants.Plan, quota.Used, []compute.Profile, bool) { tn, err := b.tenants.Get(r.Context(), tenant) diff --git a/internal/api/quota_test.go b/internal/api/quota_test.go index ff71313..ec750ad 100644 --- a/internal/api/quota_test.go +++ b/internal/api/quota_test.go @@ -10,30 +10,54 @@ import ( "github.com/phorge-fr/phorge-api/internal/tenants" ) -// tiny is a tenant of the small plan (1 instance, 2 vCPU, 4 GiB, 20 GiB, 1 network) that alice may use as she uses demo. +// tiny is a tenant like any other (2 instances, 2 vCPU, 4 GiB, 128 GiB, 2 networks, 2 profiles) that alice may use as she uses demo. func withTiny(e *env) { e.store.tenants["tiny"] = tenants.Tenant{Name: "tiny", Owner: "alice@example.org", Plan: tenants.Small, CreatedAt: now, Ready: true, NotReadySince: now} - for _, rel := range []string{"can_read_tenant", "can_read_instances", "can_write_instances", "can_read_images", "can_write_images", "can_read_networks", "can_write_networks"} { + for _, rel := range []string{"can_read_tenant", "can_read_instances", "can_write_instances", "can_read_images", "can_write_images", "can_read_networks", "can_write_networks", "can_read_profiles", "can_write_profiles"} { e.fga.grants["user:operator@example.org "+rel+" tenant:tiny"] = true } e.fga.objects["user:operator@example.org"] = append(e.fga.objects["user:operator@example.org"], "tenant:tiny") e.images.put("tiny", readyImage("debian")) } -func TestQuotaSaysWhatThePlanAllowsAndWhatTheTenantHolds(t *testing.T) { +func TestQuotaSaysWhatEveryTenantMayHoldAndWhatItHolds(t *testing.T) { e := newEnv(t) e.instances.put("demo", compute.Instance{Name: "a", Image: "debian", CPU: 2, MemoryMiB: 2048, DiskGiB: 20}) e.instances.put("demo", compute.Instance{Name: "b", Image: "debian", Profile: "m", Running: false}) // stopped: it counts var got quotaBody mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/quota", "viewer", ""), &got) - if got.Plan != tenants.Large || got.Limits != (quota.Limits{Instances: 6, VCPU: 8, MemoryMiB: 16384, DiskGiB: 512, Networks: 3}) { + // the plan of demo is large and the limits are the same as for every tenant: the plan is shown, deprecated, and limits nothing + if got.Plan != tenants.Large || got.Limits != (quota.Limits{Instances: 2, VCPU: 2, MemoryMiB: 4096, DiskGiB: 128, Networks: 2, Profiles: 2}) { t.Errorf("plan and limits: %+v", got) } - if want := (quota.Used{Instances: 2, VCPU: 4, MemoryMiB: 2048 + 4096, DiskGiB: 148, Networks: 1}); got.Used != want { + if want := (quota.Used{Instances: 2, VCPU: 4, MemoryMiB: 2048 + 4096, DiskGiB: 148, Networks: 1, Profiles: 0}); got.Used != want { t.Errorf("used = %+v, want %+v (the network of the test environment, the stopped VM, the profile)", got.Used, want) } } +// The plan of a tenant is kept in the answer and limits nothing: a small one and a large one have the same limits. +func TestThePlanOfATenantChangesNoLimit(t *testing.T) { + e := newEnv(t) + withTiny(e) // small, demo is large + var small, large quotaBody + mustDecode(t, e.do(t, "GET", "/v1/tenants/tiny/quota", "operator", ""), &small) + mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/quota", "viewer", ""), &large) + if small.Plan != tenants.Small || large.Plan != tenants.Large || small.Limits != large.Limits || small.Limits != quota.PerTenant { + t.Errorf("small %+v, large %+v: the limits are the same, whatever the plan", small, large) + } +} + +// The profiles are in what a tenant holds, but the three every tenant has are not. +func TestQuotaCountsTheProfilesTheUsersMade(t *testing.T) { + e := newEnv(t) + e.profiles.put("demo", madeProfile("one", 1, 1024, 10)) + var got quotaBody + mustDecode(t, e.do(t, "GET", "/v1/tenants/demo/quota", "viewer", ""), &got) + if got.Used.Profiles != 1 || got.Limits.Profiles != 2 { + t.Errorf("profiles used %d of %d, want 1 of 2: s, m and l are not counted", got.Used.Profiles, got.Limits.Profiles) + } +} + func TestQuotaWhoMayRead(t *testing.T) { for who, want := range map[string]int{"viewer": 200, "user": 200, "operator": 200, "admin": 200, "svc_images": 403, "mallory": 404, "": 401} { if code := call(t, newEnv(t), "GET", "/v1/tenants/demo/quota", who, ""); code != want { @@ -53,11 +77,11 @@ func quotaCode(t *testing.T, body string) string { return body } -func TestAnInstanceThatWouldPassThePlanIsRefusedWithTheLimit(t *testing.T) { +func TestAnInstanceThatWouldPassTheLimitsIsRefusedWithTheLimit(t *testing.T) { e := newEnv(t) withTiny(e) e.networks.put("tiny", readyNetwork("net")) - // 2 instances allowed on the small plan + // 2 instances are allowed for _, n := range []string{"a", "b"} { if code := call(t, e, "POST", "/v1/tenants/tiny/instances", "operator", `{"name":"`+n+`","image":"debian"}`); code != http.StatusAccepted { t.Fatalf("instance %s: status %d", n, code) @@ -72,7 +96,7 @@ func TestAnInstanceThatWouldPassThePlanIsRefusedWithTheLimit(t *testing.T) { } } -func TestAnInstanceBiggerThanThePlanIsRefusedBeforeIncusSeesIt(t *testing.T) { +func TestAnInstanceBiggerThanTheLimitsIsRefusedBeforeIncusSeesIt(t *testing.T) { for name, tt := range map[string]struct{ body, want string }{ "a disk": {`{"name":"a","image":"debian","diskGiB":200}`, "200 GiB of disk and the tenant has 0 out of 128 GiB"}, "a profile that is too big": {`{"name":"a","image":"debian","profile":"l"}`, "4 vCPU"}, @@ -89,21 +113,45 @@ func TestAnInstanceBiggerThanThePlanIsRefusedBeforeIncusSeesIt(t *testing.T) { } } -func TestASecondNetworkOnASmallPlanIsRefusedWithTheLimit(t *testing.T) { +func TestAThirdNetworkIsRefusedWithTheLimit(t *testing.T) { e := newEnv(t) withTiny(e) - if code := call(t, e, "POST", "/v1/tenants/tiny/networks", "operator", `{"name":"one"}`); code != http.StatusAccepted { - t.Fatalf("the first network: status %d", code) + for _, n := range []string{"one", "two"} { + if code := call(t, e, "POST", "/v1/tenants/tiny/networks", "operator", `{"name":"`+n+`"}`); code != http.StatusAccepted { + t.Fatalf("network %s: status %d", n, code) + } } - rec := e.do(t, "POST", "/v1/tenants/tiny/networks", "operator", `{"name":"two"}`) - if rec.Code != http.StatusConflict || !strings.Contains(quotaCode(t, rec.Body.String()), "1 network out of 1") { - t.Errorf("the second: status %d: %s", rec.Code, rec.Body) + rec := e.do(t, "POST", "/v1/tenants/tiny/networks", "operator", `{"name":"three"}`) + if rec.Code != http.StatusConflict || !strings.Contains(quotaCode(t, rec.Body.String()), "2 networks out of 2 allowed: delete one first") { + t.Errorf("the third: status %d: %s", rec.Code, rec.Body) } - if len(e.networks.created) != 1 { + if len(e.networks.created) != 2 { t.Errorf("the refused network reached the store") } } +func TestAThirdProfileIsRefusedWithTheLimit(t *testing.T) { + e := newEnv(t) + withTiny(e) + const sz = `"cpu":1,"memoryMiB":1024,"diskGiB":10` + for _, n := range []string{"one", "two"} { + if code := call(t, e, "POST", "/v1/tenants/tiny/profiles", "operator", `{"name":"`+n+`",`+sz+`}`); code != http.StatusAccepted { + t.Fatalf("profile %s: status %d", n, code) + } + } + rec := e.do(t, "POST", "/v1/tenants/tiny/profiles", "operator", `{"name":"three",`+sz+`}`) + if rec.Code != http.StatusConflict || !strings.Contains(quotaCode(t, rec.Body.String()), "2 profiles out of 2 allowed (s, m and l do not count): delete one first") { + t.Errorf("the third: status %d: %s", rec.Code, rec.Body) + } + if len(e.profiles.created) != 2 { + t.Errorf("the refused profile reached the store: %d created", len(e.profiles.created)) + } + // s, m and l are not counted: the two above came next to them, and the profile of another tenant is not this one's + if code := call(t, e, "POST", "/v1/tenants/demo/profiles", "operator", `{"name":"one",`+sz+`}`); code != http.StatusAccepted { + t.Errorf("a profile of another tenant: status %d", code) + } +} + func TestATenantHoldsAtMostSomeImages(t *testing.T) { s := testSettings s.MaxImagesPerTenant = 2 diff --git a/internal/api/selfservice_test.go b/internal/api/selfservice_test.go index 8ff0288..634d7d4 100644 --- a/internal/api/selfservice_test.go +++ b/internal/api/selfservice_test.go @@ -39,8 +39,8 @@ func TestAPersonCannotCreateATenantForSomeoneElseOrWithABiggerPlan(t *testing.T) e := newEnvWith(t, usersMay()) for name, tt := range map[string]struct{ body, want string }{ "for someone else": {`{"name":"x1","owner":"bob@example.org"}`, "only create a tenant for yourself"}, - "a bigger plan": {`{"name":"x2","plan":"large"}`, "small plan"}, - "a medium plan": {`{"name":"x3","plan":"medium"}`, "small plan"}, + "a bigger plan": {`{"name":"x2","plan":"large"}`, "no choice of plan"}, + "a medium plan": {`{"name":"x3","plan":"medium"}`, "no choice of plan"}, } { rec := e.do(t, "POST", "/v1/tenants", "mallory", tt.body) if rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), tt.want) { diff --git a/internal/api/tenants.go b/internal/api/tenants.go index b43d4f2..4dfe347 100644 --- a/internal/api/tenants.go +++ b/internal/api/tenants.go @@ -17,9 +17,9 @@ import ( // tenantRoutes are the routes of the tenants. // // Seeing a tenant takes a right on it (a role; for a key, the scope tenants:read too). Any person creates a tenant for themselves: -// they own it, it has the smallest plan, and the number of tenants a person owns is limited (MAX_TENANTS_PER_USER). Changing the -// name of a tenant and deleting it is for its admins, the owner among them. Its plan is not a thing the API changes: an -// administrator of the platform does it on request, where the platform is run. A key never creates, changes or deletes a tenant. +// they own it, and the number of tenants a person owns is limited (MAX_TENANTS_PER_USER). Changing the +// name of a tenant and deleting it is for its admins, the owner among them. Every tenant has the same limits (internal/quota), +// whatever its plan, which is deprecated and kept as it is read until the console stops using it. A key never creates, changes or deletes a tenant. type tenantRoutes struct { base store tenants.Store @@ -125,14 +125,14 @@ func (t *tenantRoutes) create(w http.ResponseWriter, r *http.Request) { } id, _ := auth.FromContext(r.Context()) req.CreatedBy = id.Subject - // A person creates a tenant for themselves: the owner is the caller, and the plan the smallest. A request that says otherwise + // A person creates a tenant for themselves: the owner is the caller, and the plan the default one, which limits nothing. A request that says otherwise // is refused, not changed in silence. if req.Owner != "" && !strings.EqualFold(req.Owner, id.Email) { httperr.Write(w, http.StatusForbidden, "forbidden", "you can only create a tenant for yourself") return } if req.Plan != "" && req.Plan != tenants.Small { - httperr.Write(w, http.StatusForbidden, "forbidden", "a new tenant has the small plan: ask the platform administrators for another one") + httperr.Write(w, http.StatusForbidden, "forbidden", "there is no choice of plan any more: every tenant has the same limits, leave plan out") return } req.Owner, req.Plan = id.Email, tenants.Small @@ -185,10 +185,10 @@ func (t *tenantRoutes) patch(w http.ResponseWriter, r *http.Request) { t.storeError(w, err, "tenant") return } - // The plan is what a tenant is allowed to hold: its admins rename it, and the platform administrators change the plan on request, - // where the platform is run. + // Every tenant has the same limits: the plan is deprecated, kept until the console stops reading it, and it changes nothing. Its + // admins rename a tenant, and a request that gives a plan is still refused, as it always was. if req.Plan != nil { - httperr.Write(w, http.StatusForbidden, "forbidden", "the plan of a tenant is changed by the platform administrators: ask them") + httperr.Write(w, http.StatusForbidden, "forbidden", "there is no choice of plan any more: every tenant has the same limits") return } tn, err := t.store.Patch(r.Context(), r.PathValue("t"), req) diff --git a/internal/api/tenants_test.go b/internal/api/tenants_test.go index 6076cf4..af10e29 100644 --- a/internal/api/tenants_test.go +++ b/internal/api/tenants_test.go @@ -406,7 +406,7 @@ func TestGetShowsThePhase(t *testing.T) { if ready.Phase != tenants.Ready || ready.Namespace != "t-demo" || ready.Owner != "alice@example.org" || ready.Plan != tenants.Large { t.Errorf("ready: %+v", ready) } - if failed.Phase != tenants.Failed || failed.Problems != "This tenant has reached a limit of its plan." { + if failed.Phase != tenants.Failed || failed.Problems != "This tenant has reached one of its limits." { t.Errorf("failed: %+v, the problem is told in words once it has lasted", failed) } } diff --git a/internal/config/config.go b/internal/config/config.go index fa045ff..22bcd4a 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -46,8 +46,6 @@ type Config struct { // RateLimitPerMinute is how many requests that create, change or delete one caller may send a minute, in bursts of // RateLimitBurst. 0 limits nothing. MaxImagesPerTenant is how many images a tenant may hold, 0 is no limit. RateLimitPerMinute, RateLimitBurst, MaxImagesPerTenant int - // MaxProfilesPerTenant is how many profiles the users of a tenant may make, 0 is no limit. - MaxProfilesPerTenant int // MaxTenantsPerUser is how many tenants a person may own, 0 is no limit. Any person signed in with Authentik creates their own. MaxTenantsPerUser int @@ -69,23 +67,22 @@ type Config struct { // Environment variables. const ( - EnvListenAddr = "LISTEN_ADDR" - EnvIssuer = "OIDC_ISSUER" - EnvAudience = "OIDC_AUDIENCE" - EnvOpenFGAURL = "OPENFGA_URL" - EnvOpenFGAAPIKey = "OPENFGA_API_KEY" //nolint:gosec // the name of a variable, not a credential - EnvOpenFGAStoreID = "OPENFGA_STORE_ID" - EnvOpenFGAModelID = "OPENFGA_MODEL_ID" - EnvCAFile = "CA_FILE" - EnvKubeContext = "KUBE_CONTEXT" - EnvInstanceBootGrace = "INSTANCE_BOOT_GRACE" - EnvInstanceStuckAfter = "INSTANCE_STUCK_AFTER" - EnvMaxTenantsPerUser = "MAX_TENANTS_PER_USER" - EnvRateLimitPerMinute = "RATE_LIMIT_WRITES_PER_MINUTE" - EnvRateLimitBurst = "RATE_LIMIT_BURST" - EnvMaxImagesPerTenant = "MAX_IMAGES_PER_TENANT" - EnvMaxProfilesPerTenant = "MAX_PROFILES_PER_TENANT" - EnvAPIKeyMaxLifetime = "API_KEY_MAX_LIFETIME" //nolint:gosec // the name of a variable, not a credential + EnvListenAddr = "LISTEN_ADDR" + EnvIssuer = "OIDC_ISSUER" + EnvAudience = "OIDC_AUDIENCE" + EnvOpenFGAURL = "OPENFGA_URL" + EnvOpenFGAAPIKey = "OPENFGA_API_KEY" //nolint:gosec // the name of a variable, not a credential + EnvOpenFGAStoreID = "OPENFGA_STORE_ID" + EnvOpenFGAModelID = "OPENFGA_MODEL_ID" + EnvCAFile = "CA_FILE" + EnvKubeContext = "KUBE_CONTEXT" + EnvInstanceBootGrace = "INSTANCE_BOOT_GRACE" + EnvInstanceStuckAfter = "INSTANCE_STUCK_AFTER" + EnvMaxTenantsPerUser = "MAX_TENANTS_PER_USER" + EnvRateLimitPerMinute = "RATE_LIMIT_WRITES_PER_MINUTE" + EnvRateLimitBurst = "RATE_LIMIT_BURST" + EnvMaxImagesPerTenant = "MAX_IMAGES_PER_TENANT" + EnvAPIKeyMaxLifetime = "API_KEY_MAX_LIFETIME" //nolint:gosec // the name of a variable, not a credential EnvIncusURL = "INCUS_URL" EnvIncusClientID = "INCUS_CLIENT_ID" //nolint:gosec // the name of a variable, not a credential @@ -205,7 +202,6 @@ func Load(lookup func(string) (string, bool)) (Config, error) { integer(EnvRateLimitPerMinute, 0, &c.RateLimitPerMinute) integer(EnvRateLimitBurst, 1, &c.RateLimitBurst) integer(EnvMaxImagesPerTenant, 0, &c.MaxImagesPerTenant) - integer(EnvMaxProfilesPerTenant, 0, &c.MaxProfilesPerTenant) integer(EnvMaxTenantsPerUser, 0, &c.MaxTenantsPerUser) duration(EnvInstanceBootGrace, 0, &c.InstanceBootGrace) duration(EnvInstanceStuckAfter, time.Second, &c.InstanceStuckAfter) @@ -253,7 +249,6 @@ func (c Config) LogValue() slog.Value { slog.Int("rate_limit_writes_per_minute", c.RateLimitPerMinute), slog.Int("rate_limit_burst", c.RateLimitBurst), slog.Int("max_images_per_tenant", c.MaxImagesPerTenant), - slog.Int("max_profiles_per_tenant", c.MaxProfilesPerTenant), slog.Duration("instance_boot_grace", c.InstanceBootGrace), slog.Duration("instance_stuck_after", c.InstanceStuckAfter), slog.Duration("api_key_max_lifetime", c.APIKeyMaxLifetime), diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 853aad9..35b0228 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -20,14 +20,13 @@ func valid() map[string]string { EnvOpenFGAStoreID: "01M50R0P12MY8JHNKP3ATYSJC2", EnvOpenFGAModelID: "01M6XYT8C5Q4R8GB5QY5DYH87B", // What decides how the API behaves has no default: a deployment writes it. - EnvInstanceBootGrace: "5m", - EnvInstanceStuckAfter: "10m", - EnvAPIKeyMaxLifetime: "8784h", - EnvMaxTenantsPerUser: "3", - EnvRateLimitPerMinute: "60", - EnvRateLimitBurst: "10", - EnvMaxImagesPerTenant: "20", - EnvMaxProfilesPerTenant: "20", + EnvInstanceBootGrace: "5m", + EnvInstanceStuckAfter: "10m", + EnvAPIKeyMaxLifetime: "8784h", + EnvMaxTenantsPerUser: "3", + EnvRateLimitPerMinute: "60", + EnvRateLimitBurst: "10", + EnvMaxImagesPerTenant: "20", // The terminal: Incus, the exchange at Authentik, and the limits of a session. EnvIncusURL: "https://incus.example.org", EnvIncusClientID: "incus-client", @@ -173,7 +172,7 @@ func TestTheDurationsAreChecked(t *testing.T) { } func TestTheRateLimitAndTheImageCapAreRequiredWholeNumbers(t *testing.T) { - for _, key := range []string{EnvRateLimitPerMinute, EnvRateLimitBurst, EnvMaxImagesPerTenant, EnvMaxProfilesPerTenant} { + for _, key := range []string{EnvRateLimitPerMinute, EnvRateLimitBurst, EnvMaxImagesPerTenant} { m := valid() delete(m, key) if _, err := Load(env(m)); err == nil || !strings.Contains(err.Error(), key+" is required") { diff --git a/internal/openapi/openapi.yaml b/internal/openapi/openapi.yaml index 993f06a..82931f3 100644 --- a/internal/openapi/openapi.yaml +++ b/internal/openapi/openapi.yaml @@ -68,7 +68,7 @@ paths: summary: What the API enforces on a request description: | The bounds of an instance (CPU, memory, disk) with the value each takes when a request leaves it out, and the longest - names. The plan of a tenant is a limit of its own and is not here. + names. What a tenant may hold is the same for every tenant and is in `GET /v1/tenants/{t}/quota`. security: - bearerAuth: [] responses: @@ -108,8 +108,9 @@ paths: summary: Create a tenant description: | Any person creates a tenant for themselves (`canCreateTenants` of `GET /v1/whoami`): they own it, `owner` is left - out or is their own email, and the plan is `small` (another one is `403`: the platform administrators change a - plan on request, where the platform is run). A person owns a limited number of tenants: + out or is their own email. Every tenant has the same limits (2 VMs, 2 vCPU, 4 GiB of memory, 128 GiB of disk, 2 networks + and 2 profiles), so there is no plan to choose: leave `plan` out. It is deprecated and kept until the console stops + reading it: a `plan` other than `small` is `403`, and none changes a limit. A person owns a limited number of tenants: past it the answer is `409` with the code `quota_exceeded`. A key never creates a tenant. The answer is `202`: the tenant exists but Crossplane takes about a minute to make its namespace, its Incus @@ -178,8 +179,8 @@ paths: operationId: updateTenant summary: Change the display name description: | - The admins of the tenant, the owner among them, change its display name. The plan is not changed through the API - (`403`): a person who needs another one asks the platform administrators. The name and the owner cannot change: to hand a tenant over, give the new person the + The admins of the tenant, the owner among them, change its display name. The `plan` is deprecated and changes + no limit, since every tenant has the same ones: a body that gives it is `403`. The name and the owner cannot change: to hand a tenant over, give the new person the `admin` role with a membership. security: - bearerAuth: [] @@ -191,7 +192,7 @@ paths: $ref: "#/components/schemas/TenantPatch" responses: "200": - description: The tenant. The new plan is applied by Crossplane within a minute. + description: The tenant. content: application/json: schema: @@ -397,7 +398,7 @@ paths: An OVN network of the tenant, NATed: its instances reach the Internet and are not reachable from it. The user may choose its range with `ipv4`; without one Incus chooses it. A range the platform uses, or that a network of any tenant already has, is refused with `409` (`range_reserved`, `range_in_use`). The answer is `202`: poll the `Location` until `phase` is `Ready`. The number of networks is - limited by the plan of the tenant: the next one never becomes ready, and `problems` says that a limit is reached. + limited (2 for every tenant): a third is refused with `409` and the code `quota_exceeded`, and a message that says which limit. security: - bearerAuth: [] requestBody: @@ -541,11 +542,12 @@ paths: tags: - Tenants operationId: getQuota - summary: What the plan of a tenant allows and what it holds + summary: What a tenant may hold and what it holds description: | - The limits of the plan of the tenant (instances, vCPU, memory, disk, networks) and what the tenant holds. A stopped - instance counts, as it does for Incus. A request that would pass a limit is refused with `409` and the code - `quota_exceeded`, and a message that says which. + The limits of the tenant (instances, vCPU, memory, disk, networks, profiles), the same for every tenant, and what the + tenant holds. A stopped instance counts, as it does for Incus. The profiles are the ones its users made: `s`, `m` and + `l` are not counted. The `plan` is deprecated, it limits nothing and goes when the console stops reading it. A request that + would pass a limit is refused with `409` and the code `quota_exceeded`, and a message that says which. security: - bearerAuth: [] responses: @@ -574,8 +576,8 @@ paths: description: | Every tenant has the profiles `s` (1 vCPU, 2 GiB, 64 GiB), `m` (2, 4, 128) and `l` (4, 8, 256), created with it and marked `builtin`, then the profiles its users made. An instance takes one of them (`profile`) or its own `cpu`, - `memoryMiB` and `diskGiB`. The plan of the tenant limits the total: a profile whose disk is above the plan's is - refused by Incus when an instance asks for it. + `memoryMiB` and `diskGiB`. The limits of the tenant hold the total: a profile whose disk is above them is + refused when an instance asks for it. A tenant holds at most 2 profiles of its own; `s`, `m` and `l` are not counted. security: - bearerAuth: [] responses: @@ -600,10 +602,10 @@ paths: summary: Make a profile in a tenant description: | A size of the user's own: CPU, memory and a root disk, all three given. The name is 1 to 32 characters, and `s`, `m`, `l` - and `default` are taken. A tenant holds a limited number of them (`quota_exceeded` past it). It may also say two settings + and `default` are taken. A tenant holds at most 2 of them (a third is `409`, `quota_exceeded`, delete one first); `s`, `m` and `l` are not counted. It may also say two settings of an instance, `secureBoot` and `sshPublicKeys`, which an instance takes unless it says its own; there is no nesting and no network on a profile (`400`, an unknown field). The answer is `202`: poll the `Location` until `phase` is - `Ready`. A profile that is bigger than the plan is a definition: it is the instance that Incus refuses. + `Ready`. A profile that is bigger than the limits of the tenant is a definition: it is the instance that is refused. security: - bearerAuth: [] requestBody: @@ -727,7 +729,7 @@ paths: The image has to be an image of the same tenant, and `Ready`. The answer is `202`: it takes about a minute. Poll the `Location` until `phase` is `Ready`. - A request that would pass a limit of the tenant's plan is refused here, before Incus is asked: `409` with the code + A request that would pass a limit of the tenant is refused here, before Incus is asked: `409` with the code `quota_exceeded` and a message that says which limit (`GET /v1/tenants/{t}/quota` says what is left). Stopped VMs count. Incus stays the authority: a `PATCH` that grows an instance is only checked by Incus, and its refusal comes back as `problems` of the instance, in words. @@ -1445,7 +1447,7 @@ components: problems: type: string description: | - What is wrong, in a sentence made for the user: a limit of the plan that is reached, an image that does not + What is wrong, in a sentence made for the user: a limit that is reached, an image that does not boot, or that the platform could not complete a step yet. Never a Crossplane condition or a provider error. Absent when all is well. createdAt: @@ -1489,6 +1491,7 @@ components: - memoryMiB - diskGiB - networks + - profiles properties: instances: type: integer @@ -1500,6 +1503,9 @@ components: type: integer networks: type: integer + profiles: + type: integer + description: The profiles the users of the tenant made (as `limits`, how many they may make). `s`, `m` and `l` are not counted. Quota: type: object required: @@ -1677,7 +1683,8 @@ components: type: integer maxPerTenant: type: integer - description: How many profiles the users of a tenant may make. `0` is no limit. + description: | + How many profiles the users of a tenant may make: 2, the same for every tenant (`s`, `m` and `l` are not counted). image: type: object required: @@ -1722,7 +1729,7 @@ components: problems: type: string description: | - What is wrong, in a sentence made for the user: a limit of the plan that is reached, or that the platform could + What is wrong, in a sentence made for the user: a limit that is reached, or that the platform could not complete a step yet. Never a Crossplane condition or a provider error. Absent when all is well. createdAt: type: string @@ -2228,9 +2235,11 @@ components: maxLength: 100 Plan: type: string + deprecated: true description: | - The quota of the tenant, enforced by Incus. The CPU, the memory and the disk of each plan hold two instances of the - size of its own profile. `small`: 2 VMs, 2 vCPU, 4 GiB, 128 GiB of disk, 1 network. `medium`: 4, 4, 8, 256, 2. `large`: 6, 8, 16, 512, 3. + Deprecated: every tenant has the same limits (2 VMs, 2 vCPU, 4 GiB, 128 GiB of disk, 2 networks, 2 profiles), whatever + its plan, which is kept as it is read until the console stops using it and then removed. A new tenant is `small`; + another plan is `403` on creation and on change. enum: - small - medium diff --git a/internal/quota/quota.go b/internal/quota/quota.go index fb1e897..9387569 100644 --- a/internal/quota/quota.go +++ b/internal/quota/quota.go @@ -1,43 +1,39 @@ -// Package quota is what a tenant may hold, and what it holds. The plan of a tenant is enforced by Incus as limits of its project; -// this package knows the same numbers so that the API can say "the limit is reached" before it asks, in words and with a stable -// code, and so that a client can draw what is left. Incus stays the authority: a request that passes here can still be refused -// there, and its refusal is told in words by internal/status. +// Package quota is what a tenant may hold, and what it holds. Every tenant has the same limits: Incus enforces most of them as limits +// of the tenant's project; this package knows the same numbers so that the API can say "the limit is reached" before it asks, in +// words and with a stable code, and so that a client can draw what is left. Incus stays the authority: a request that passes here +// can still be refused there, and its refusal is told in words by internal/status. The count of profiles is the API's own, Incus +// has no limit for it. package quota import ( "fmt" "github.com/phorge-fr/phorge-api/internal/compute" - "github.com/phorge-fr/phorge-api/internal/tenants" ) -// Limits are the limits of a plan. They are the ones of the Tenant composition in Hangar (composition-tenant.yml): the two lists -// are the same. The CPU, the memory and the disk of each plan hold two instances of the size of its profile (small two s, medium two m, large two l); the count of instances is 2, 4 and 6. +// Limits are what a tenant may hold, or what it holds. type Limits struct { Instances int `json:"instances"` VCPU int `json:"vcpu"` MemoryMiB int `json:"memoryMiB"` DiskGiB int `json:"diskGiB"` Networks int `json:"networks"` + // Profiles are the ones the users of the tenant make: the three every tenant has (s, m and l) are not counted. + Profiles int `json:"profiles"` } -// Plans are the quota plans of the Tenant XRD. -var Plans = map[tenants.Plan]Limits{ - tenants.Small: {Instances: 2, VCPU: 2, MemoryMiB: 4 * 1024, DiskGiB: 128, Networks: 1}, - tenants.Medium: {Instances: 4, VCPU: 4, MemoryMiB: 8 * 1024, DiskGiB: 256, Networks: 2}, - tenants.Large: {Instances: 6, VCPU: 8, MemoryMiB: 16 * 1024, DiskGiB: 512, Networks: 3}, -} - -// LimitsOf returns the limits of a plan. An unknown plan holds nothing: it is the plan of a tenant that the XRD would refuse. -func LimitsOf(p tenants.Plan) Limits { return Plans[p] } +// PerTenant are the limits of every tenant. Apart from the profiles they are the ones of the Tenant composition in Hangar +// (composition-tenant.yml): the two lists are the same. The CPU, the memory and the disk hold two instances of the size of the +// profile m. The disk is the one of the API (128 GiB): the project limit in Incus adds 512 MiB per VM for the state of a VM. +var PerTenant = Limits{Instances: 2, VCPU: 2, MemoryMiB: 4 * 1024, DiskGiB: 128, Networks: 2, Profiles: 2} // Used is what a tenant holds. A stopped instance counts: Incus counts it. type Used = Limits -// UsedBy adds up the instances and the networks of a tenant. An instance that has a profile counts what the profile comes to: the -// three every tenant has, or one of the profiles the user made (user). +// UsedBy adds up the instances, the networks and the profiles of a tenant. An instance that has a profile counts what the profile comes to: the +// three every tenant has, or one of the profiles the user made (user), which are the ones that count as profiles. func UsedBy(instances []compute.Instance, networks []compute.Network, user []compute.Profile) Used { - u := Used{Instances: len(instances), Networks: len(networks)} + u := Used{Instances: len(instances), Networks: len(networks), Profiles: len(user)} for _, in := range instances { cpu, mem, disk := SizeOf(in, user) u.VCPU += cpu @@ -66,7 +62,7 @@ func SizeAsked(r compute.CreateInstance, user []compute.Profile) (cpu, memMiB, d // Error says which limit a request would pass, and by how much. It is a refusal of the API, not of Incus. type Error struct { - // Limit is the name of the limit: instances, vcpu, memoryMiB, diskGiB, networks, images, tenants. + // Limit is the name of the limit: instances, vcpu, memoryMiB, diskGiB, networks, profiles, images, tenants. Limit string // Message is the sentence for the user. Message string @@ -74,32 +70,41 @@ type Error struct { func (e *Error) Error() string { return e.Message } -// CheckInstance returns an *Error when an instance of that size would pass a limit of the plan. The count comes first, then the +// CheckInstance returns an *Error when an instance of that size would pass a limit of the tenant. The count comes first, then the // CPU, the memory and the disk, so that the answer is the first thing the user can do something about. -func CheckInstance(plan tenants.Plan, used Used, cpu, memMiB, diskGiB int) *Error { - l := LimitsOf(plan) +func CheckInstance(used Used, cpu, memMiB, diskGiB int) *Error { + l := PerTenant switch { case used.Instances+1 > l.Instances: - return &Error{"instances", fmt.Sprintf("this tenant has %d %s out of %d allowed by its plan %s: delete one first", used.Instances, plural(used.Instances, "instance", "instances"), l.Instances, plan)} + return &Error{"instances", fmt.Sprintf("this tenant has %d %s out of %d allowed: delete one first", used.Instances, plural(used.Instances, "instance", "instances"), l.Instances)} case used.VCPU+cpu > l.VCPU: - return &Error{"vcpu", fmt.Sprintf("this instance needs %d vCPU and the tenant has %d out of %d allowed by its plan %s", cpu, used.VCPU, l.VCPU, plan)} + return &Error{"vcpu", fmt.Sprintf("this instance needs %d vCPU and the tenant has %d out of %d allowed", cpu, used.VCPU, l.VCPU)} case used.MemoryMiB+memMiB > l.MemoryMiB: - return &Error{"memoryMiB", fmt.Sprintf("this instance needs %s of memory and the tenant has %s out of %s allowed by its plan %s", gib(memMiB), gib(used.MemoryMiB), gib(l.MemoryMiB), plan)} + return &Error{"memoryMiB", fmt.Sprintf("this instance needs %s of memory and the tenant has %s out of %s allowed", gib(memMiB), gib(used.MemoryMiB), gib(l.MemoryMiB))} case used.DiskGiB+diskGiB > l.DiskGiB: - return &Error{"diskGiB", fmt.Sprintf("this instance needs %d GiB of disk and the tenant has %d out of %d GiB allowed by its plan %s", diskGiB, used.DiskGiB, l.DiskGiB, plan)} + return &Error{"diskGiB", fmt.Sprintf("this instance needs %d GiB of disk and the tenant has %d out of %d GiB allowed", diskGiB, used.DiskGiB, l.DiskGiB)} + } + return nil +} + +// CheckNetwork returns an *Error when one more network would pass the limit of the tenant. +func CheckNetwork(used Used) *Error { + if l := PerTenant; used.Networks+1 > l.Networks { + return &Error{"networks", fmt.Sprintf("this tenant has %d %s out of %d allowed: delete one first", used.Networks, plural(used.Networks, "network", "networks"), l.Networks)} } return nil } -// CheckNetwork returns an *Error when one more network would pass the limit of the plan. -func CheckNetwork(plan tenants.Plan, used Used) *Error { - if l := LimitsOf(plan); used.Networks+1 > l.Networks { - return &Error{"networks", fmt.Sprintf("this tenant has %d %s out of %d allowed by its plan %s: delete one first", used.Networks, plural(used.Networks, "network", "networks"), l.Networks, plan)} +// CheckProfile returns an *Error when one more profile made by a user would pass the limit of the tenant. The three profiles every +// tenant has are not counted. +func CheckProfile(used Used) *Error { + if l := PerTenant; used.Profiles+1 > l.Profiles { + return &Error{"profiles", fmt.Sprintf("this tenant has %d %s out of %d allowed (s, m and l do not count): delete one first", used.Profiles, plural(used.Profiles, "profile", "profiles"), l.Profiles)} } return nil } -// CheckCount returns an *Error when one more of something would pass a limit that is not the plan's: images of a tenant, tenants of a +// CheckCount returns an *Error when one more of something would pass a limit that is not the tenant's: images of a tenant, tenants of a // person. A limit of 0 is no limit. func CheckCount(limit string, have, max int, what string) *Error { if max > 0 && have+1 > max { diff --git a/internal/quota/quota_test.go b/internal/quota/quota_test.go index 08d4f1b..9a35cc5 100644 --- a/internal/quota/quota_test.go +++ b/internal/quota/quota_test.go @@ -5,68 +5,52 @@ import ( "testing" "github.com/phorge-fr/phorge-api/internal/compute" - "github.com/phorge-fr/phorge-api/internal/tenants" ) -// The plans are written twice, here and in the Tenant composition of Hangar: this is the table the composition says. -func TestThePlansAreTheOnesOfTheTenantComposition(t *testing.T) { - want := map[tenants.Plan]Limits{ - tenants.Small: {2, 2, 4096, 128, 1}, - tenants.Medium: {4, 4, 8192, 256, 2}, - tenants.Large: {6, 8, 16384, 512, 3}, - } - for plan, w := range want { - if got := LimitsOf(plan); got != w { - t.Errorf("%s = %+v, want %+v", plan, got, w) - } +// The limits are written twice, here and in the Tenant composition of Hangar (composition-tenant.yml): this is what the composition +// says. Its project limit for the disk is the 128 GiB plus 512 MiB for the state of each of the 2 VMs, 132096 MiB. The profiles are +// the API's own: Incus has no limit for them. +func TestTheLimitsAreTheOnesOfTheTenantComposition(t *testing.T) { + want := Limits{Instances: 2, VCPU: 2, MemoryMiB: 4096, DiskGiB: 128, Networks: 2, Profiles: 2} + if PerTenant != want { + t.Errorf("PerTenant = %+v, want %+v", PerTenant, want) } - if (LimitsOf("xl") != Limits{}) { - t.Error("an unknown plan holds something") + if project := PerTenant.DiskGiB*1024 + 512*PerTenant.Instances; project != 132096 { + t.Errorf("the project limit for the disk would be %d MiB, the composition has 132096", project) } } -// The CPU, the memory and the disk of a plan hold two instances of the size of its own profile, and nothing that is bigger: this is -// what the alignment says. The count of instances is the plan's own, 2, 4 and 6. -func TestEachPlanHoldsTwoOfItsOwnProfile(t *testing.T) { - counts := map[tenants.Plan]int{tenants.Small: 2, tenants.Medium: 4, tenants.Large: 6} - for plan, name := range map[tenants.Plan]string{tenants.Small: "s", tenants.Medium: "m", tenants.Large: "l"} { - p, ok := compute.ProfileNamed(name) - if !ok { - t.Fatalf("no profile %s", name) - } - l := LimitsOf(plan) - if l.Instances != counts[plan] { - t.Errorf("plan %s allows %d instances, want %d", plan, l.Instances, counts[plan]) - } - if l.VCPU != 2*p.CPU || l.MemoryMiB < 2*p.MemoryMiB || l.DiskGiB < 2*p.DiskGiB { - t.Errorf("plan %s %+v does not hold two %s (%+v)", plan, l, name, p) - } - var used Used - for i := 0; i < 2; i++ { - if e := CheckInstance(plan, used, p.CPU, p.MemoryMiB, p.DiskGiB); e != nil { - t.Errorf("plan %s refuses instance %d of its own profile %s: %v", plan, i+1, name, e) - } - used.Instances++ - used.VCPU += p.CPU - used.MemoryMiB += p.MemoryMiB - used.DiskGiB += p.DiskGiB - } - // a third of the same size passes the CPU, the memory or the disk, whichever gives out first - if e := CheckInstance(plan, used, p.CPU, p.MemoryMiB, p.DiskGiB); e == nil { - t.Errorf("plan %s accepts a third instance of its own profile", plan) +// The CPU, the memory and the disk hold two instances of the size of the profile s (or one of m), and nothing that is bigger. +func TestTheLimitsHoldTwoOfTheProfileS(t *testing.T) { + m, ok := compute.ProfileNamed("s") + if !ok { + t.Fatal("no profile s") + } + l := PerTenant + if l.VCPU != 2*m.CPU || l.MemoryMiB != 2*m.MemoryMiB || l.DiskGiB != 2*m.DiskGiB { + t.Errorf("%+v does not hold two s (%+v)", l, m) + } + var used Used + for i := 0; i < 2; i++ { + if e := CheckInstance(used, m.CPU, m.MemoryMiB, m.DiskGiB); e != nil { + t.Errorf("instance %d of the profile s is refused: %v", i+1, e) } + used.Instances++ + used.VCPU += m.CPU + used.MemoryMiB += m.MemoryMiB + used.DiskGiB += m.DiskGiB } - // a profile bigger than the plan is refused - l, small := compute.BuiltinProfiles[2], tenants.Small - if e := CheckInstance(small, Used{}, l.CPU, l.MemoryMiB, l.DiskGiB); e == nil { - t.Error("a l on a small plan is accepted") + if e := CheckInstance(used, m.CPU, m.MemoryMiB, m.DiskGiB); e == nil { + t.Error("a third instance of the profile s is accepted") } - // the count is reached only by instances smaller than the profile - if e := CheckInstance(tenants.Medium, Used{Instances: 4}, 1, 256, 1); e == nil || e.Limit != "instances" { - t.Errorf("a fifth instance on a medium plan: %v", e) + // one m is all the CPU, the memory and the disk there is + if mm, _ := compute.ProfileNamed("m"); mm.CPU != PerTenant.VCPU || mm.MemoryMiB != PerTenant.MemoryMiB || mm.DiskGiB != PerTenant.DiskGiB { + t.Errorf("one m (%+v) is not the whole of %+v", mm, PerTenant) } - if e := CheckInstance(tenants.Large, Used{Instances: 5}, 1, 256, 1); e != nil { - t.Errorf("a sixth instance on a large plan: %v", e) + // a profile bigger than the limits is refused + big := compute.BuiltinProfiles[2] + if e := CheckInstance(Used{}, big.CPU, big.MemoryMiB, big.DiskGiB); e == nil { + t.Error("a l is accepted") } } @@ -78,9 +62,9 @@ func TestUsedByCountsStoppedInstancesAndProfiles(t *testing.T) { {Name: "c", CPU: 1, MemoryMiB: 1024, DiskGiB: 10, Running: false}, }, []compute.Network{{Name: "n"}}, - nil, + []compute.Profile{{Name: "web", CPU: 1, MemoryMiB: 1024, DiskGiB: 10}}, ) - want := Used{Instances: 3, VCPU: 5, MemoryMiB: 2048 + 4096 + 1024, DiskGiB: 158, Networks: 1} + want := Used{Instances: 3, VCPU: 5, MemoryMiB: 2048 + 4096 + 1024, DiskGiB: 158, Networks: 1, Profiles: 1} if got != want { t.Errorf("UsedBy = %+v, want %+v", got, want) } @@ -88,21 +72,19 @@ func TestUsedByCountsStoppedInstancesAndProfiles(t *testing.T) { func TestCheckInstanceSaysWhichLimitIsPassed(t *testing.T) { for name, tt := range map[string]struct { - plan tenants.Plan used Used cpu, mem, disk int limit, mentioned string }{ - "nothing is passed": {tenants.Medium, Used{Instances: 1, VCPU: 1, MemoryMiB: 1024, DiskGiB: 10}, 1, 1024, 10, "", ""}, - "exactly the plan": {tenants.Small, Used{}, 2, 4096, 128, "", ""}, - "the count": {tenants.Small, Used{Instances: 2}, 1, 1024, 10, "instances", "2 instances out of 2"}, - "the count on medium": {tenants.Medium, Used{Instances: 4}, 1, 1024, 10, "instances", "4 instances out of 4"}, - "the CPU": {tenants.Medium, Used{Instances: 1, VCPU: 3}, 2, 1024, 10, "vcpu", "needs 2 vCPU and the tenant has 3 out of 4"}, - "the memory": {tenants.Medium, Used{Instances: 1, MemoryMiB: 7168}, 1, 2048, 10, "memoryMiB", "2 GiB of memory and the tenant has 7 GiB out of 8 GiB"}, - "the disk": {tenants.Small, Used{}, 1, 1024, 200, "diskGiB", "200 GiB of disk and the tenant has 0 out of 128 GiB"}, - "the count comes first": {tenants.Small, Used{Instances: 2, VCPU: 2}, 16, 65536, 500, "instances", ""}, + "nothing is passed": {Used{Instances: 1, VCPU: 1, MemoryMiB: 1024, DiskGiB: 10}, 1, 1024, 10, "", ""}, + "exactly the limits": {Used{}, 2, 4096, 128, "", ""}, + "the count": {Used{Instances: 2}, 1, 1024, 10, "instances", "2 instances out of 2 allowed: delete one first"}, + "the CPU": {Used{Instances: 1, VCPU: 1}, 2, 1024, 10, "vcpu", "needs 2 vCPU and the tenant has 1 out of 2"}, + "the memory": {Used{Instances: 1, MemoryMiB: 3072}, 2, 2048, 10, "memoryMiB", "2 GiB of memory and the tenant has 3 GiB out of 4 GiB"}, + "the disk": {Used{}, 1, 1024, 200, "diskGiB", "200 GiB of disk and the tenant has 0 out of 128 GiB"}, + "the count comes first": {Used{Instances: 2, VCPU: 2}, 16, 65536, 500, "instances", ""}, } { - e := CheckInstance(tt.plan, tt.used, tt.cpu, tt.mem, tt.disk) + e := CheckInstance(tt.used, tt.cpu, tt.mem, tt.disk) switch { case tt.limit == "" && e != nil: t.Errorf("%s: refused: %v", name, e) @@ -116,12 +98,18 @@ func TestCheckInstanceSaysWhichLimitIsPassed(t *testing.T) { } } -func TestCheckNetworkAndCount(t *testing.T) { - if e := CheckNetwork(tenants.Small, Used{Networks: 1}); e == nil || e.Limit != "networks" || !strings.Contains(e.Message, "1 network out of 1") { - t.Errorf("a second network on a small plan: %v", e) +func TestCheckNetworkProfileAndCount(t *testing.T) { + if e := CheckNetwork(Used{Networks: 2}); e == nil || e.Limit != "networks" || !strings.Contains(e.Message, "2 networks out of 2 allowed: delete one first") { + t.Errorf("a third network: %v", e) + } + if e := CheckNetwork(Used{Networks: 1}); e != nil { + t.Errorf("a second network: %v", e) + } + if e := CheckProfile(Used{Profiles: 2}); e == nil || e.Limit != "profiles" || !strings.Contains(e.Message, "2 profiles out of 2 allowed") || !strings.Contains(e.Message, "delete one first") { + t.Errorf("a third profile: %v", e) } - if e := CheckNetwork(tenants.Large, Used{Networks: 2}); e != nil { - t.Errorf("a third network on a large plan: %v", e) + if e := CheckProfile(Used{Profiles: 1}); e != nil { + t.Errorf("a second profile: %v", e) } if e := CheckCount("images", 20, 20, "this tenant holds too many images"); e == nil || e.Limit != "images" || !strings.Contains(e.Message, "20 out of 20") { t.Errorf("the 21st image: %v", e) @@ -154,7 +142,7 @@ func TestSizeAskedTakesTheProfileOrTheDefaults(t *testing.T) { func TestAProfileTheUserMadeCountsWhatItComesTo(t *testing.T) { mine := []compute.Profile{{Name: "web", CPU: 3, MemoryMiB: 3072, DiskGiB: 30}} got := UsedBy([]compute.Instance{{Name: "a", Profile: "web"}, {Name: "b", Profile: "s"}}, nil, mine) - if want := (Used{Instances: 2, VCPU: 4, MemoryMiB: 3072 + 2048, DiskGiB: 94}); got != want { + if want := (Used{Instances: 2, VCPU: 4, MemoryMiB: 3072 + 2048, DiskGiB: 94, Profiles: 1}); got != want { t.Errorf("UsedBy = %+v, want %+v", got, want) } if cpu, mem, disk := SizeAsked(compute.CreateInstance{Profile: "web"}, mine); cpu != 3 || mem != 3072 || disk != 30 { diff --git a/internal/status/message.go b/internal/status/message.go index 2004b22..44c1081 100644 --- a/internal/status/message.go +++ b/internal/status/message.go @@ -20,14 +20,14 @@ var actionable = []struct { re *regexp.Regexp say string }{ - {regexp.MustCompile(`Reached maximum number of instances`), "This tenant has reached the maximum number of instances of its plan."}, + {regexp.MustCompile(`Reached maximum number of instances`), "This tenant has reached the maximum number of instances it is allowed."}, // Incus says it either way: "Reached maximum number of networks" for a count, "Networks limit has been reached for project" for a // network (verified on the cluster, 2026-11-08). - {regexp.MustCompile(`Reached maximum number of networks|Networks limit has been reached`), "This tenant has reached the maximum number of networks of its plan."}, - {regexp.MustCompile(`Reached maximum aggregate value .*limits\.disk`), "This tenant has reached the disk limit of its plan."}, - {regexp.MustCompile(`Reached maximum aggregate value .*limits\.memory`), "This tenant has reached the memory limit of its plan."}, - {regexp.MustCompile(`Reached maximum aggregate value .*limits\.cpu`), "This tenant has reached the CPU limit of its plan."}, - {regexp.MustCompile(`Reached maximum`), "This tenant has reached a limit of its plan."}, + {regexp.MustCompile(`Reached maximum number of networks|Networks limit has been reached`), "This tenant has reached the maximum number of networks it is allowed."}, + {regexp.MustCompile(`Reached maximum aggregate value .*limits\.disk`), "This tenant has reached its disk limit."}, + {regexp.MustCompile(`Reached maximum aggregate value .*limits\.memory`), "This tenant has reached its memory limit."}, + {regexp.MustCompile(`Reached maximum aggregate value .*limits\.cpu`), "This tenant has reached its CPU limit."}, + {regexp.MustCompile(`Reached maximum`), "This tenant has reached one of its limits."}, {regexp.MustCompile(`incompatible with secureboot`), "This image cannot start with secure boot: create the instance with secureBoot set to false."}, {regexp.MustCompile(`in-use by`), "This image is used by an instance: delete the instance first."}, {regexp.MustCompile(`prevent_destroy`), "This instance cannot be changed in place: delete it and create it again."}, diff --git a/internal/tenants/tenants.go b/internal/tenants/tenants.go index 28323db..c5d7697 100644 --- a/internal/tenants/tenants.go +++ b/internal/tenants/tenants.go @@ -13,7 +13,8 @@ import ( "github.com/phorge-fr/phorge-api/internal/status" ) -// Plan is the quota plan of a tenant, which Incus enforces as project limits. +// Plan is the quota plan of a tenant. It is deprecated: every tenant has the same limits, whatever its plan, and it is kept only +// until the console stops reading it. type Plan string // The plans of the Tenant XRD.