Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/reference/images-and-instances.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Both live in the namespace `t-<tenant>` 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 SSH keys of a new instance have three cases**, and the API tells them apart on `POST`. `sshPublicKeys` absent (or `null`): the field is left out of the object and the instance takes the keys of its profile, if that has some. `sshPublicKeys: []`: the empty list is written, the instance has no key and its profile's do not apply. A list of keys: they are written and replace the profile's, they do not add to them. A client that always sends `[]` therefore overrides the keys of every profile: it must send the field only when the person typed keys. `PATCH` writes what it is given in the same way, so `[]` clears the keys of an instance and its profile's do not come back.
- **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 `- <key>` 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 `<type> <base64>` 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.
Expand Down
29 changes: 29 additions & 0 deletions internal/api/compute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,35 @@ func TestCreateInstance(t *testing.T) {
}
}

// The three ways to say the SSH keys of a new instance reach the store as three different values: nothing (the profile's keys
// apply), an empty list (no key, the profile's do not apply) and the keys. The body of the answer is a list in every case.
func TestCreateInstanceTellsAbsentKeysFromNone(t *testing.T) {
for name, tt := range map[string]struct {
field string
nil bool
keys int
}{
"absent": {"", true, 0},
"null": {`,"sshPublicKeys":null`, true, 0},
"empty list": {`,"sshPublicKeys":[]`, false, 0},
"keys": {`,"sshPublicKeys":["` + sshKey + `"]`, false, 1},
} {
e := newEnv(t)
e.images.put("demo", readyImage("debian"))
rec := e.do(t, "POST", "/v1/tenants/demo/instances", "user", `{"name":"web","image":"debian","cpu":1,"memoryMiB":1024,"diskGiB":10`+tt.field+`}`)
if rec.Code != http.StatusAccepted || len(e.instances.created) != 1 {
t.Fatalf("%s: status %d, created %d: %s", name, rec.Code, len(e.instances.created), rec.Body.String())
}
got := e.instances.created[0].SSHPublicKeys
if (got == nil) != tt.nil || len(got) != tt.keys {
t.Errorf("%s: the store got %#v, want nil %v and %d keys", name, got, tt.nil, tt.keys)
}
if !strings.Contains(rec.Body.String(), `"sshPublicKeys":[`) {
t.Errorf("%s: the body has no list of keys: %s", name, rec.Body.String())
}
}
}

func TestCreateInstanceNeedsAnImageOfTheTenantThatIsReady(t *testing.T) {
e := newEnv(t)
e.images.put("other", readyImage("elsewhere"))
Expand Down
21 changes: 12 additions & 9 deletions internal/compute/compute.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,15 +250,18 @@ type CreateInstance struct {
Image string `json:"image"`
// Networks are the networks of the tenant the instance joins, one NIC each in this order. Network is the deprecated way to give
// one. With neither, the route picks the only network of the tenant.
Networks []string `json:"networks"`
Network string `json:"network"`
Profile string `json:"profile"`
CPU *int `json:"cpu"`
MemoryMiB *int `json:"memoryMiB"`
DiskGiB *int `json:"diskGiB"`
Running *bool `json:"running"`
Nesting *bool `json:"nesting"`
SecureBoot *bool `json:"secureBoot"`
Networks []string `json:"networks"`
Network string `json:"network"`
Profile string `json:"profile"`
CPU *int `json:"cpu"`
MemoryMiB *int `json:"memoryMiB"`
DiskGiB *int `json:"diskGiB"`
Running *bool `json:"running"`
Nesting *bool `json:"nesting"`
SecureBoot *bool `json:"secureBoot"`

// SSHPublicKeys tells three things apart: nil (absent or null) leaves the field out of the object and the instance takes the keys
// of its profile; an empty, non-nil list is "no key" and the profile's do not apply; a list is the instance's own keys.
SSHPublicKeys []string `json:"sshPublicKeys"`

// CreatedBy is the subject of the caller, recorded on the object. Not part of the request body.
Expand Down
5 changes: 4 additions & 1 deletion internal/kube/compute.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,10 @@ func (s *Instances) Create(ctx context.Context, tenant string, req compute.Creat
setBool("running", req.Running)
setBool("nesting", req.Nesting)
setBool("secureBoot", req.SecureBoot)
if len(req.SSHPublicKeys) > 0 {
// Absent (nil) is left out of the spec: the instance takes its profile's keys. An empty list is written as it is: it is "no key",
// and the platform then does not apply the profile's. A decoded `"sshPublicKeys": []` is a non-nil empty slice, an absent
// field or a null is nil.
if req.SSHPublicKeys != nil {
spec["sshPublicKeys"] = toAny(req.SSHPublicKeys)
}
obj, err := r.Create(ctx, &unstructured.Unstructured{Object: map[string]any{
Expand Down
52 changes: 52 additions & 0 deletions internal/kube/compute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,58 @@ func TestInstanceCreateSendsOnlyWhatWasAsked(t *testing.T) {
}
}

// An instance that does not say its SSH keys takes its profile's; one that says an empty list has none. The object must carry the
// difference: absent is left out of the spec, an empty list is written as such, and the answer is read from the spec first so an empty
// list is "no key" and does not fall through to the status.
func TestInstanceCreateTellsAbsentKeysFromNone(t *testing.T) {
for name, tt := range map[string]struct {
keys []string
written bool
want int
}{
"absent": {nil, false, 0},
"empty list": {[]string{}, true, 0},
"keys": {[]string{key}, true, 1},
} {
client := newClient()
s := NewInstances(Static(client))
got, err := s.Create(t.Context(), "demo", compute.CreateInstance{Name: "web", Image: "debian", SSHPublicKeys: tt.keys})
if err != nil {
t.Fatal(err)
}
if len(got.SSHPublicKeys) != tt.want {
t.Errorf("%s: the answer has %v, want %d keys", name, got.SSHPublicKeys, tt.want)
}
obj, err := client.Resource(instancesGVR).Namespace("t-demo").Get(t.Context(), "web", metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
v, found, err := unstructured.NestedStringSlice(obj.Object, "spec", "sshPublicKeys")
if err != nil || found != tt.written || len(v) != tt.want {
t.Errorf("%s: spec.sshPublicKeys = %v, found %v, err %v; want written %v with %d keys", name, v, found, err, tt.written, tt.want)
}
}
}

// What the platform says it has in force does not replace an empty list the instance wrote.
func TestInstanceCreatedWithNoKeyKeepsNoKeyWhenTheStatusHasSome(t *testing.T) {
client := newClient()
s := NewInstances(Static(client))
if _, err := s.Create(t.Context(), "demo", compute.CreateInstance{Name: "web", Image: "debian", SSHPublicKeys: []string{}}); err != nil {
t.Fatal(err)
}
obj, err := client.Resource(instancesGVR).Namespace("t-demo").Get(t.Context(), "web", metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
if err := unstructured.SetNestedStringSlice(obj.Object, []string{key}, "status", "sshPublicKeys"); err != nil {
t.Fatal(err)
}
if got := instanceOf(obj); len(got.SSHPublicKeys) != 0 {
t.Errorf("keys = %v, the spec says none", got.SSHPublicKeys)
}
}

func TestInstancePatchChangesOnlyWhatWasGiven(t *testing.T) {
s := NewInstances(Static(newClient()))
if _, err := s.Create(t.Context(), "demo", compute.CreateInstance{Name: "web", Image: "debian", CPU: ptr(2), MemoryMiB: ptr(2048), SSHPublicKeys: []string{key}}); err != nil {
Expand Down
8 changes: 6 additions & 2 deletions internal/openapi/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1969,8 +1969,10 @@ components:
type: array
maxItems: 20
description: |
Injected with cloud-init, so the image must be a `cloud` variant. Left out, the instance takes the keys of its profile
when that has some; keys given here replace the profile's. Each key is one line: its type
Injected with cloud-init, so the image must be a `cloud` variant. Left out (or `null`), the instance takes the keys
of its profile when that has some. An empty list, `[]`, is "no key": the instance has none, and the profile's do
not apply. A list of keys replaces the profile's, it does not add to them. Send the field only when the person
gave keys: a client that always sends `[]` overrides the keys of every profile. Each key is one line: its type
(`ssh-ed25519`, `ssh-rsa`, `ecdsa-sha2-nistp256`/`384`/`521`, `sk-ssh-ed25519@openssh.com`,
`sk-ecdsa-sha2-nistp256@openssh.com`), the key in base64 and, at most, a comment of one word made of letters,
digits and `@._+=/-`. Nothing else is accepted, on purpose.
Expand Down Expand Up @@ -2016,6 +2018,8 @@ components:
sshPublicKeys:
type: array
maxItems: 20
description: |
Replaces the keys of the instance. An empty list, `[]`, leaves it with no key, and its profile's do not apply.
items:
type: string
Role:
Expand Down
Loading