diff --git a/aws/cur/errors.go b/aws/cur/errors.go index f7ed086..8816e78 100644 --- a/aws/cur/errors.go +++ b/aws/cur/errors.go @@ -66,7 +66,7 @@ func faultError(f fault.Fault) *apiError { case "rateLimitExceeded": code, status = "ThrottlingException", http.StatusBadRequest } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } type errorJSON struct { diff --git a/aws/ec2/errors.go b/aws/ec2/errors.go index 5187153..06313e3 100644 --- a/aws/ec2/errors.go +++ b/aws/ec2/errors.go @@ -52,7 +52,7 @@ func faultError(f fault.Fault) *apiError { case "rateLimitExceeded": code = "RequestLimitExceeded" } - return &apiError{status, code, fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{status, code, f.ErrorMessage()} } type errorResponse struct { diff --git a/aws/route53/errors.go b/aws/route53/errors.go index 325399d..ec24401 100644 --- a/aws/route53/errors.go +++ b/aws/route53/errors.go @@ -66,7 +66,7 @@ func faultError(f fault.Fault) *apiError { case "rateLimitExceeded": code, status = "Throttling", http.StatusBadRequest } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } type errorResponse struct { diff --git a/aws/s3/errors.go b/aws/s3/errors.go index 7c4dc3f..ad91ee5 100644 --- a/aws/s3/errors.go +++ b/aws/s3/errors.go @@ -65,7 +65,7 @@ func faultError(f fault.Fault) *apiError { case "rateLimitExceeded": code, status = "SlowDown", http.StatusServiceUnavailable } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } type errorXML struct { diff --git a/azure/arm/blob.go b/azure/arm/blob.go index 54330aa..a062d21 100644 --- a/azure/arm/blob.go +++ b/azure/arm/blob.go @@ -285,7 +285,7 @@ func blobFaultError(f fault.Fault) *apiError { case "rateLimitExceeded": code, status = "ServerBusy", http.StatusServiceUnavailable } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } // storageHeaders sets the headers every Blob service answer carries. diff --git a/azure/arm/datadisks.go b/azure/arm/datadisks.go new file mode 100644 index 0000000..c233a90 --- /dev/null +++ b/azure/arm/datadisks.go @@ -0,0 +1,194 @@ +package arm + +import ( + "encoding/json" + "fmt" + "maps" + "strings" +) + +const maxDataDiskLun = 63 + +var dataDiskMembers = []string{ + "caching", "createOption", "deleteOption", "detachOption", "diskIOPSReadWrite", "diskMBpsReadWrite", "diskSizeGB", + "image", "lun", "managedDisk", "name", "sourceResource", "toBeDetached", "vhd", "writeAcceleratorEnabled", +} + +// dataDisk is a data disk a VM's storage profile names. +type dataDisk struct { + body map[string]any + id string + // disk is the managed disk, when the server holds it. + disk *resource + detach bool +} + +// dataDiskPlan is the data disks a write gives a VM: set ones replace what +// it has, and otherwise kept are what it had. +type dataDiskPlan struct { + set bool + disks []dataDisk + kept []any +} + +// planDataDisks parses the data disks props, the properties a write sends, +// ask the VM id to hold, and checks that each can be attached. existing is +// the VM as it was, or nil for a new one. The caller holds s.mu. +func (s *Server) planDataDisks(existing *resource, id string, props map[string]any) (*dataDiskPlan, *apiError) { + sp, err := object(props, "storageProfile") + if err != nil { + return nil, err + } + plan := &dataDiskPlan{} + if _, plan.set = sp["dataDisks"]; !plan.set { + if existing == nil { + plan.set = true + } else { + plan.kept = recordedDataDisks(existing) + } + return plan, nil + } + raw, err := objects(sp, "dataDisks") + if err != nil { + return nil, err + } + luns := map[int64]bool{} + for i, d := range raw { + path := fmt.Sprintf("properties.storageProfile.dataDisks[%d]", i) + if err := checkMembers(d, "DataDisk", path, dataDiskMembers...); err != nil { + return nil, err + } + for _, k := range []string{"image", "sourceResource", "vhd"} { + if d[k] != nil { + return nil, unsupported("%s.%s is not supported", path, k) + } + } + switch option := str(d, "createOption"); { + case option == "": + return nil, requiredParameter(path + ".createOption") + case !strings.EqualFold(option, "Attach"): + return nil, unsupported("createOption %s is not supported for a data disk; only Attach is", option) + } + if d["lun"] == nil { + return nil, requiredParameter(path + ".lun") + } + n, _ := d["lun"].(json.Number) + lun, convErr := n.Int64() + if convErr != nil || lun < 0 || lun > maxDataDiskLun { + return nil, invalidParameter(path+".lun", "The value '%v' of %s.lun is not valid.", d["lun"], path) + } + if luns[lun] { + return nil, invalidParameter("dataDisks", "A disk at LUN %d already exists.", lun) + } + luns[lun] = true + dd := dataDisk{body: maps.Clone(d), id: refID(d, "managedDisk")} + if dd.id == "" { + return nil, requiredParameter(path + ".managedDisk.id") + } + delete(dd.body, "diskIOPSReadWrite") + delete(dd.body, "diskMBpsReadWrite") + dd.detach, _ = boolean(d, "toBeDetached") + if res := s.settled(dd.id); res != nil && res.disk != nil { + dd.disk = res + } + if dd.disk != nil && !dd.detach && dd.disk.disk.vm != "" && key(dd.disk.disk.vm) != key(id) { + return nil, diskAttached(dd.disk.name, dd.disk.disk.vm) + } + plan.disks = append(plan.disks, dd) + } + return plan, nil +} + +// recordedDataDisks returns the data disks the VM vm holds, as it shows them. +func recordedDataDisks(vm *resource) []any { + sp, _ := vm.props["storageProfile"].(map[string]any) + disks, _ := sp["dataDisks"].([]any) + return disks +} + +// applyDataDisks gives the VM vm the data disks plan names, attaching the +// ones it did not hold and releasing the ones it no longer does. The caller +// holds s.mu. +func (s *Server) applyDataDisks(vm *resource, plan *dataDiskPlan) { + listed := plan.kept + if plan.set { + listed = []any{} + held := map[string]bool{} + for _, d := range plan.disks { + if d.detach { + continue + } + body := d.body + body["toBeDetached"] = false + if str(body, "deleteOption") == "" { + body["deleteOption"] = "Detach" + } + name := d.id[strings.LastIndex(d.id, "/")+1:] + if d.disk != nil { + md, _ := body["managedDisk"].(map[string]any) + md = maps.Clone(md) + md["id"] = d.disk.id + body["managedDisk"] = md + name = d.disk.name + if size, ok := d.disk.props["diskSizeGB"]; ok { + body["diskSizeGB"] = size + } + if key(d.disk.disk.vm) != key(vm.id) { + d.disk.disk.vm, d.disk.disk.owned = vm.id, s.now() + } + held[key(d.disk.id)] = true + } + if str(body, "name") == "" { + body["name"] = name + } + listed = append(listed, body) + } + os := key(refID(osDiskOf(vm), "managedDisk")) + for _, res := range s.resources { + if res.disk != nil && key(res.disk.vm) == key(vm.id) && !held[key(res.id)] && key(res.id) != os { + res.disk.vm, res.disk.owned = "", s.now() + } + } + } + sp, _ := vm.props["storageProfile"].(map[string]any) + sp = maps.Clone(sp) + if sp == nil { + sp = map[string]any{} + } + if listed == nil { + delete(sp, "dataDisks") + } else { + sp["dataDisks"] = listed + } + vm.props["storageProfile"] = sp +} + +// releaseDataDisks detaches the VM vm, which is being deleted, from its data +// disks, deleting those whose deleteOption is Delete. The caller holds s.mu. +func (s *Server) releaseDataDisks(vm *resource) { + deleting := map[string]bool{} + for _, d := range recordedDataDisks(vm) { + body, _ := d.(map[string]any) + deleting[key(refID(body, "managedDisk"))] = strings.EqualFold(str(body, "deleteOption"), "Delete") + } + for _, res := range s.resources { + if res.disk == nil || key(res.disk.vm) != key(vm.id) { + continue + } + res.disk.vm, res.disk.owned = "", s.now() + if deleting[key(res.id)] { + s.remove(res) + } + } +} + +// dateDataDisks dates the data disks of the VM vm, which was just deallocated +// or started, as its OS disk is dated. The caller holds s.mu. +func (s *Server) dateDataDisks(vm *resource) { + os := key(refID(osDiskOf(vm), "managedDisk")) + for _, res := range s.resources { + if res.disk != nil && key(res.disk.vm) == key(vm.id) && key(res.id) != os { + res.disk.owned = s.now() + } + } +} diff --git a/azure/arm/disks.go b/azure/arm/disks.go index e8be504..8756763 100644 --- a/azure/arm/disks.go +++ b/azure/arm/disks.go @@ -441,6 +441,7 @@ func (s *Server) powerChanged(vm *resource) { if d != nil && d.disk != nil && key(d.disk.vm) == key(vm.id) { d.disk.owned = s.now() } + s.dateDataDisks(vm) } // releaseOSDisk detaches the VM vm, which is being deleted, from its OS disk, diff --git a/azure/arm/errors.go b/azure/arm/errors.go index 32a7d47..06ca2f7 100644 --- a/azure/arm/errors.go +++ b/azure/arm/errors.go @@ -125,7 +125,7 @@ func faultError(f fault.Fault) *apiError { case "rateLimitExceeded": code = "SubscriptionRequestsThrottled" } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } type errorBody struct { diff --git a/azure/arm/galleries.go b/azure/arm/galleries.go index 5b4feac..cb533e8 100644 --- a/azure/arm/galleries.go +++ b/azure/arm/galleries.go @@ -104,6 +104,78 @@ func (s *Server) registerGalleryRoutes() { s.add("GET", l.path, l.kind.action("read"), false, s.getGallery(l)) s.add("DELETE", l.path, l.kind.action("delete"), true, s.deleteCompute(l.kind, l.id, capsOps)) } + s.add("PATCH", galleryVersion, galleryVersionKind.action("write"), true, s.patchGalleryVersion) +} + +// patchGalleryVersion updates an image version's tags, publishingProfile or +// safetyProfile, merging each profile's members into the ones it has. +func (s *Server) patchGalleryVersion(c *call) (*reply, *apiError) { + body, err := readObject(c.r) + if err != nil { + return nil, err + } + if err := checkMembers(body, "GalleryImageVersionUpdate", "", "id", "name", "type", "tags", "properties"); err != nil { + return nil, err + } + props, err := object(body, "properties") + if err != nil { + return nil, err + } + if err := checkMembers(props, "GalleryImageVersionProperties", "properties", slices.Concat(galleryVersionKind.props, galleryVersionKind.readOnly)...); err != nil { + return nil, err + } + for _, k := range []string{"restore", "securityProfile", "storageProfile"} { + if props[k] != nil { + return nil, unsupported("updating %s with PATCH is not supported; use PUT", k) + } + } + _, hasTags := body["tags"] + tags, err := tagsOf(body) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := s.writableGroup(c); err != nil { + return nil, err + } + res, err := s.claim(galleryVersionID(c), "") + if err != nil { + return nil, err + } + if res == nil || res.kind != galleryVersionKind { + return nil, resourceNotFound(galleryKind.typ, galleryName(galleryVersionID(c)), c.val("rg")) + } + p := &parsed{location: res.loc, tags: res.tags, top: res.top, props: maps.Clone(res.props)} + if hasTags { + p.tags = tags + } + for _, k := range []string{"publishingProfile", "safetyProfile"} { + patch, err := object(props, k) + if err != nil { + return nil, err + } + if patch == nil { + continue + } + merged, _ := p.props[k].(map[string]any) + merged = maps.Clone(merged) + if merged == nil { + merged = map[string]any{} + } + maps.Copy(merged, patch) + p.props[k] = merged + } + render := func() []byte { return encode(renderGallery(res, false)) } + paths := capsOps(c, res.loc) + if c.opFault != nil { + op := s.begin(c, paths, 0, nil) + op.target, op.state = res.id, stateUpdating + return accepted(c, op, http.StatusOK, http.StatusOK, false, func() []byte { return withState(res, stateUpdating, render) }), nil + } + s.update(res, p) + op := s.change(c, res, paths, 0, stateUpdating, nil) + return accepted(c, op, http.StatusOK, http.StatusOK, false, render), nil } // prepareGalleryImage validates p as the new body of the image definition diff --git a/azure/arm/openai.go b/azure/arm/openai.go new file mode 100644 index 0000000..bda8659 --- /dev/null +++ b/azure/arm/openai.go @@ -0,0 +1,246 @@ +package arm + +import ( + "cmp" + "maps" + "net" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + + "github.com/parallelworks/squall/fault" + "github.com/parallelworks/squall/internal/stub" +) + +// OpenAI returns the Azure OpenAI data plane of the server's Cognitive +// Services accounts, an [http.Handler] to serve with [net/http/httptest]. It +// takes the account's custom subdomain from a host name such as +// {subdomain}.openai.azure.com or {subdomain}.cognitiveservices.azure.com, +// or else from the first path segment, so a client reaches the account at +// {server URL}/{subdomain}/. +func (s *Server) OpenAI() http.Handler { return http.HandlerFunc(s.serveOpenAI) } + +// ingestionJob is an Azure OpenAI On Your Data ingestion job. +type ingestionJob struct { + body map[string]any + status string + err *apiError + // wait is how many more reads see the job running. + wait int +} + +const ( + jobRunning = "running" + jobSucceeded = "succeeded" + jobFailed = "failed" +) + +type openAICall struct { + r *http.Request + subdomain string + job string + account *resource + // opFault, when set, is the error the job must end in. + opFault *apiError +} + +type openAIOp struct { + // name is the operation's ID in the REST API's specification, which fault rules match. + name string + h func(s *Server, c *openAICall) (*reply, *apiError) +} + +var ( + createJobOp = &openAIOp{"IngestionJobs_Create", (*Server).putIngestionJob} + getJobOp = &openAIOp{"IngestionJobs_Get", (*Server).getIngestionJob} +) + +// openAIKinds are the account kinds that serve the Azure OpenAI data plane. +var openAIKinds = []string{"AIServices", "OpenAI"} + +func parseOpenAIRequest(r *http.Request) (*openAICall, *openAIOp) { + c := &openAICall{r: r} + path := strings.TrimPrefix(r.URL.EscapedPath(), "/") + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + host = r.Host + } + if labels := strings.Split(host, "."); len(labels) > 3 && (strings.EqualFold(labels[1], "openai") || strings.EqualFold(labels[1], "cognitiveservices")) { + c.subdomain = labels[0] + } else { + c.subdomain, path, _ = strings.Cut(path, "/") + } + job, ok := strings.CutPrefix(path, "openai/ingestion/jobs/") + if !ok || job == "" || strings.Contains(job, "/") { + return c, nil + } + c.job, _ = url.PathUnescape(job) + switch r.Method { + case http.MethodPut: + return c, createJobOp + case http.MethodGet: + return c, getJobOp + } + return c, nil +} + +func (s *Server) serveOpenAI(w http.ResponseWriter, r *http.Request) { + c, op := parseOpenAIRequest(r) + if op == nil || r.URL.Query().Get("api-version") == "" { + writeOpenAIError(w, newError(http.StatusNotFound, "404", "Resource not found")) + return + } + if err := s.admitOpenAI(c); err != nil { + writeOpenAIError(w, err) + return + } + f, _ := s.faults.Decide(fault.Call{Method: op.name, Resource: strings.ToLower(c.subdomain) + "/ingestion/jobs/" + c.job}) + reject := f.Mode == fault.ModeReject || f.Mode == fault.ModeFailOperation && op != createJobOp + if f.Mode == fault.ModeFailOperation && !reject { + c.opFault = openAIFaultError(f) + } + stub.Serve(w, r, f, reject, "application/json", func() { writeOpenAIError(w, openAIFaultError(f)) }, func() (func(), bool) { + s.mu.Lock() + rep, err := op.h(s, c) + s.mu.Unlock() + if err != nil { + return func() { writeOpenAIError(w, err) }, false + } + return func() { writeJSON(w, rep.status, nil, rep.body) }, true + }) +} + +// admitOpenAI finds the account c names and checks its key. +func (s *Server) admitOpenAI(c *openAICall) *apiError { + s.mu.Lock() + defer s.mu.Unlock() + acct := s.subdomainHolder(c.subdomain) + if acct == nil || s.resources[key(acct.id)] != acct || !slices.Contains(openAIKinds, str(acct.top, "kind")) { + return newError(http.StatusNotFound, "404", "Resource not found") + } + key := c.r.Header.Get("api-key") + switch { + case key == "" && strings.HasPrefix(c.r.Header.Get("Authorization"), "Bearer "): + return unsupported("Microsoft Entra ID tokens are not supported; send an account key in api-key") + case key == "": + return newError(http.StatusUnauthorized, "401", + "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API.") + case key != accessKey(acct, "key1", 84) && key != accessKey(acct, "key2", 84): + return newError(http.StatusUnauthorized, "401", + "Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.") + } + c.account = acct + return nil +} + +// openAIFaultError is the error a fault answers with. The fault package's +// generic reasons become the HTTP status, as Azure OpenAI writes its codes. +func openAIFaultError(f fault.Fault) *apiError { + status := cmp.Or(f.Status, http.StatusServiceUnavailable) + code := f.Reason + switch code { + case "", "backendError": + code = strconv.Itoa(status) + case "rateLimitExceeded": + code, status = "429", http.StatusTooManyRequests + } + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} +} + +func writeOpenAIError(w http.ResponseWriter, e *apiError) { + writeJSON(w, e.Status, e.Header, encode(map[string]any{"error": map[string]any{"code": e.Code, "message": e.Message}})) +} + +// jobMembers are the members an ingestion job takes; status, error, warnings +// and progress are read-only and dropped. +var jobMembers = []string{ + "completionAction", "compute", "dataRefreshIntervalInHours", "datasource", "jobId", "kind", "searchServiceConnection", "target", "workspaceId", +} + +var jobReadOnly = []string{"error", "progress", "status", "warnings"} + +// putIngestionJob creates the job, or replaces and restarts it, running +// until the reads [WithSettleAfter] sets are spent. +func (s *Server) putIngestionJob(c *openAICall) (*reply, *apiError) { + body, err := readObject(c.r) + if err != nil { + return nil, newError(http.StatusBadRequest, "BadRequest", "%s", err.Message) + } + for _, k := range slices.Sorted(maps.Keys(body)) { + switch { + case slices.Contains(jobReadOnly, k): + delete(body, k) + case !slices.Contains(jobMembers, k): + return nil, newError(http.StatusBadRequest, "BadRequest", "The ingestion job has an unknown member '%s'.", k) + } + } + if id := str(body, "jobId"); id != "" && id != c.job { + return nil, newError(http.StatusBadRequest, "BadRequest", "The jobId '%s' in the body does not match the jobId '%s' in the URL.", id, c.job) + } + var required []string + switch str(body, "kind") { + case "SystemCompute": + required = []string{"searchServiceConnection", "datasource"} + case "UserCompute": + required = []string{"workspaceId", "compute", "target", "datasource"} + default: + return nil, newError(http.StatusBadRequest, "BadRequest", "The ingestion job's kind must be SystemCompute or UserCompute.") + } + for _, k := range required { + if body[k] == nil { + return nil, newError(http.StatusBadRequest, "BadRequest", "A %s ingestion job needs %s.", str(body, "kind"), k) + } + } + if a := str(body, "completionAction"); a != "" && a != "cleanUpAssets" && a != "keepAllAssets" { + return nil, newError(http.StatusBadRequest, "BadRequest", "The completionAction must be cleanUpAssets or keepAllAssets.") + } + body["jobId"] = c.job + if c.account.jobs == nil { + c.account.jobs = map[string]*ingestionJob{} + } + job := &ingestionJob{body: body, status: jobRunning, wait: max(s.settleAfter, 0)} + c.account.jobs[c.job] = job + switch { + case c.opFault != nil: + job.status, job.err = jobFailed, c.opFault + case s.settleAfter == 0: + job.status = jobSucceeded + } + return ok200(job.render()), nil +} + +// getIngestionJob answers the job, counting the read toward its run. +func (s *Server) getIngestionJob(c *openAICall) (*reply, *apiError) { + job := c.account.jobs[c.job] + if job == nil { + return nil, newError(http.StatusNotFound, "NotFound", "The ingestion job '%s' was not found.", c.job) + } + if job.status == jobRunning && s.settleAfter >= 0 { + if job.wait == 0 { + job.status = jobSucceeded + } else { + job.wait-- + } + } + return ok200(job.render()), nil +} + +func (job *ingestionJob) render() map[string]any { + m := maps.Clone(job.body) + m["status"], m["warnings"] = job.status, []any{} + if job.err != nil { + m["error"] = map[string]any{"code": job.err.Code, "message": job.err.Message} + } + return m +} + +// settleJobs ends the ingestion jobs of res that are running. The caller holds s.mu. +func settleJobs(res *resource) { + for _, job := range res.jobs { + if job.status == jobRunning { + job.status = jobSucceeded + } + } +} diff --git a/azure/arm/operations.go b/azure/arm/operations.go index cf391c4..90e0b3e 100644 --- a/azure/arm/operations.go +++ b/azure/arm/operations.go @@ -182,7 +182,8 @@ func (s *Server) observer() func(*operation) { // Settle finishes every operation in progress, with the effects finishing // has, such as a VM reaching running or a deleted resource group going away, -// and takes one step of each snapshot copy that was already running. +// ends the search indexer executions and ingestion jobs that are running, and +// takes one step of each snapshot copy that was already running. func (s *Server) Settle() { s.mu.Lock() defer s.mu.Unlock() @@ -195,6 +196,12 @@ func (s *Server) Settle() { for op := range s.pending { s.finish(op) } + for _, res := range s.resources { + if res.searchData != nil { + s.settleSearch(res.searchData) + } + settleJobs(res) + } for _, res := range copies { if copying(res) { s.stepCopy(res) diff --git a/azure/arm/resources.go b/azure/arm/resources.go index 051cb83..587defe 100644 --- a/azure/arm/resources.go +++ b/azure/arm/resources.go @@ -86,6 +86,10 @@ type resource struct { restoring bool // shareSnapshots are a file share's snapshots, oldest first. shareSnapshots []*shareSnapshot + // searchData is a search service's indexes, data sources and indexers. + searchData *searchState + // jobs are a Cognitive Services account's ingestion jobs, by ID. + jobs map[string]*ingestionJob } // inGroup reports whether r is in the group with key gk. @@ -341,6 +345,25 @@ func systemData(res *resource) map[string]any { } } +// FailProvisioning leaves the resource with the ID id Failed, as Azure leaves +// a resource whose create or update failed once it was accepted, for gets, +// lists and later writes to see. A fault that fails an operation leaves no +// trace of the call, so use it to set up such a resource. It fails for a +// resource the server does not hold or that has a change in progress. +func (s *Server) FailProvisioning(id string) error { + s.mu.Lock() + defer s.mu.Unlock() + res := s.resources[key(id)] + switch { + case res == nil: + return fmt.Errorf("squall: no resource has the ID %s", id) + case res.pending != nil && res.pending.complete != nil: + return fmt.Errorf("squall: %s has a change in progress", id) + } + res.state = stateFailed + return nil +} + // change starts an operation on res that shows it in state until it // finishes, then Succeeded; done, when set, applies the rest of the effect. // The caller holds s.mu. @@ -402,6 +425,7 @@ func (s *Server) remove(res *resource) { case res.vm != nil: s.detachNICs(res, true) s.releaseOSDisk(res) + s.releaseDataDisks(res) s.removeExtensions(res) case res.snap != nil: s.failCopiesOf(res) diff --git a/azure/arm/scalesets.go b/azure/arm/scalesets.go index c17a9a9..4103e76 100644 --- a/azure/arm/scalesets.go +++ b/azure/arm/scalesets.go @@ -880,10 +880,6 @@ func (s *Server) getInstancePublicIP(c *call) (*reply, *apiError) { }), nil } -func (s *Server) listSKUs(c *call) (*reply, *apiError) { - return ok(encode(map[string]any{"value": []any{}})), nil -} - // ScaleSet is a snapshot of a scale set. type ScaleSet struct { ID string diff --git a/azure/arm/search.go b/azure/arm/search.go index 4f13cbe..d1d8e3b 100644 --- a/azure/arm/search.go +++ b/azure/arm/search.go @@ -86,13 +86,17 @@ func (s *Server) listAdminKeys(c *call) (*reply, *apiError) { } // renderSearch shows the service's endpoint, and its state in lower case as -// Search writes it: provisioning, then succeeded and running. +// Search writes it: provisioning, then succeeded and running, or failed and +// error. func renderSearch(res *resource) map[string]any { m, props := envelope(res) props["endpoint"] = "https://" + res.name + ".search.windows.net" props["provisioningState"], props["status"], props["statusDetails"] = "provisioning", "provisioning", "" - if res.state == stateSucceeded { + switch res.state { + case stateSucceeded: props["provisioningState"], props["status"] = "succeeded", "running" + case stateFailed: + props["provisioningState"], props["status"] = "failed", "error" } return m } diff --git a/azure/arm/searchdata.go b/azure/arm/searchdata.go new file mode 100644 index 0000000..b08e6e5 --- /dev/null +++ b/azure/arm/searchdata.go @@ -0,0 +1,864 @@ +package arm + +import ( + "bytes" + "cmp" + "encoding/json" + "fmt" + "maps" + "net" + "net/http" + "net/url" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "github.com/parallelworks/squall/fault" + "github.com/parallelworks/squall/internal/stub" +) + +// Search returns the data plane of the server's search services, an +// [http.Handler] to serve with [net/http/httptest]. It takes the service from +// a host name such as {service}.search.windows.net, or else from the first +// path segment, so a client reaches the service at {server URL}/{service}. +func (s *Server) Search() http.Handler { return http.HandlerFunc(s.serveSearch) } + +// searchState is what a search service's data plane holds. +type searchState struct { + indexes map[string]*searchIndex + dataSources map[string]*searchObject + indexers map[string]*indexer +} + +// searchObject is an index, data source or indexer definition. +type searchObject struct { + body map[string]any + etag string +} + +type searchIndex struct { + searchObject + key string + fields map[string]map[string]any + docs map[string]map[string]any +} + +type indexer struct { + searchObject + // runs are the indexer's executions, newest first. + runs []*indexerRun +} + +// indexerRun is one execution of an indexer. +type indexerRun struct { + status string + err string + start, end time.Time + // wait is how many more status reads see the run in progress. + wait int +} + +const ( + runInProgress = "inProgress" + runSuccess = "success" + runFailure = "transientFailure" + maxRuns = 50 + maxIndexBatch = 1000 +) + +type searchCall struct { + r *http.Request + query url.Values + service string + // base is the URL the service is addressed at, for @odata.context. + base string + collection string + name string + rest string + op *searchOp + svc *resource + // opFault, when set, is the error a run must end in. + opFault *apiError +} + +func (c *searchCall) resource() string { + return strings.ToLower(c.service) + "/" + c.collection + "/" + c.name +} + +type searchOp struct { + // name is the operation's ID in the REST API's specification, such as Indexes_CreateOrUpdate, which fault rules match. + name string + h func(s *Server, c *searchCall, st *searchState) (*searchReply, *apiError) +} + +type searchReply struct { + status int + etag string + body map[string]any +} + +var ( + putIndexOp = &searchOp{"Indexes_CreateOrUpdate", (*Server).putSearchIndex} + getIndexOp = &searchOp{"Indexes_Get", (*Server).getSearchIndex} + deleteIndexOp = &searchOp{"Indexes_Delete", (*Server).deleteSearchIndex} + putDataSourceOp = &searchOp{"DataSources_CreateOrUpdate", (*Server).putDataSource} + getDataSourceOp = &searchOp{"DataSources_Get", (*Server).getDataSource} + deleteDataSourceO = &searchOp{"DataSources_Delete", (*Server).deleteDataSource} + putIndexerOp = &searchOp{"Indexers_CreateOrUpdate", (*Server).putIndexer} + getIndexerOp = &searchOp{"Indexers_Get", (*Server).getIndexer} + deleteIndexerOp = &searchOp{"Indexers_Delete", (*Server).deleteIndexer} + runIndexerOp = &searchOp{"Indexers_Run", (*Server).runIndexer} + indexerStatusOp = &searchOp{"Indexers_GetStatus", (*Server).indexerStatus} + indexDocumentsOp = &searchOp{"Documents_Index", (*Server).indexDocuments} + searchDocumentsOp = &searchOp{"Documents_SearchGet", (*Server).searchDocuments} +) + +// searchOperation returns the operation c asks for, or nil if it is not served. +func searchOperation(c *searchCall) *searchOp { + m := c.r.Method + switch c.collection + " " + c.rest { + case "indexes ": + return pick(m, putIndexOp, getIndexOp, deleteIndexOp) + case "datasources ": + return pick(m, putDataSourceOp, getDataSourceOp, deleteDataSourceO) + case "indexers ": + return pick(m, putIndexerOp, getIndexerOp, deleteIndexerOp) + case "indexers search.run": + if m == http.MethodPost { + return runIndexerOp + } + case "indexers search.status": + if m == http.MethodGet { + return indexerStatusOp + } + case "indexes docs/index", "indexes docs/search.index": + if m == http.MethodPost { + return indexDocumentsOp + } + case "indexes docs": + if m == http.MethodGet { + return searchDocumentsOp + } + } + return nil +} + +func pick(method string, put, get, del *searchOp) *searchOp { + switch method { + case http.MethodPut: + return put + case http.MethodGet: + return get + case http.MethodDelete: + return del + } + return nil +} + +// odataKey addresses an object by its key, as in indexers('name'). +var odataKey = regexp.MustCompile(`^(indexes|datasources|indexers)\('([^']*)'\)$`) + +// parseSearchRequest finds the service, collection, object and rest of the path r names. +func parseSearchRequest(r *http.Request) *searchCall { + c := &searchCall{r: r, query: r.URL.Query()} + scheme := "http" + if r.TLS != nil { + scheme = "https" + } + path := strings.TrimPrefix(r.URL.EscapedPath(), "/") + host, _, err := net.SplitHostPort(r.Host) + if err != nil { + host = r.Host + } + if labels := strings.Split(host, "."); len(labels) > 3 && strings.EqualFold(labels[1], "search") { + c.service, c.base = labels[0], scheme+"://"+r.Host + } else { + c.service, path, _ = strings.Cut(path, "/") + c.base = scheme + "://" + r.Host + "/" + c.service + } + segments := strings.Split(path, "/") + if m := odataKey.FindStringSubmatch(segments[0]); m != nil { + c.collection, c.name = m[1], m[2] + segments = segments[1:] + } else if len(segments) > 1 && slices.Contains([]string{"indexes", "datasources", "indexers"}, segments[0]) { + c.collection, c.name = segments[0], segments[1] + segments = segments[2:] + } + c.name, _ = url.PathUnescape(c.name) + c.rest = strings.Join(segments, "/") + return c +} + +func (s *Server) serveSearch(w http.ResponseWriter, r *http.Request) { + c := parseSearchRequest(r) + if c.collection != "" && c.name != "" { + c.op = searchOperation(c) + } + if c.op == nil { + s.writeSearchError(w, newError(http.StatusNotFound, "", "squall: %s %s is not served", r.Method, r.URL.RequestURI())) + return + } + if c.query.Get("api-version") == "" { + s.writeSearchError(w, newError(http.StatusBadRequest, "", "Invalid or missing api-version query string parameter.")) + return + } + if err := s.admitSearch(c); err != nil { + s.writeSearchError(w, err) + return + } + f, _ := s.faults.Decide(fault.Call{Method: c.op.name, Resource: c.resource()}) + reject := f.Mode == fault.ModeReject || f.Mode == fault.ModeFailOperation && c.op != runIndexerOp + if f.Mode == fault.ModeFailOperation && !reject { + c.opFault = searchFaultError(f) + } + stub.Serve(w, r, f, reject, "application/json", func() { s.writeSearchError(w, searchFaultError(f)) }, func() (func(), bool) { + s.mu.Lock() + rep, err := c.op.h(s, c, s.searchStateOf(c.svc)) + s.mu.Unlock() + if err != nil { + return func() { s.writeSearchError(w, err) }, false + } + return func() { s.writeSearchReply(w, rep) }, true + }) +} + +// admitSearch finds the service c names and checks its admin key. +func (s *Server) admitSearch(c *searchCall) *apiError { + s.mu.Lock() + defer s.mu.Unlock() + c.svc = s.searchServiceNamed(c.service) + if c.svc == nil { + return newError(http.StatusNotFound, "ResourceNotFound", "squall: no search service is named %s", c.service) + } + key := c.r.Header.Get("api-key") + if key == "" && strings.HasPrefix(c.r.Header.Get("Authorization"), "Bearer ") { + return unsupported("Microsoft Entra ID tokens are not supported; send an admin key in api-key") + } + if key != accessKey(c.svc, "primary", 52) && key != accessKey(c.svc, "secondary", 52) { + return newError(http.StatusForbidden, "", "Authorization failed. The api-key is missing or invalid.") + } + return nil +} + +// searchServiceNamed returns the search service named name, the one whose ID +// sorts first when several share it. The caller holds s.mu. +func (s *Server) searchServiceNamed(name string) *resource { + var found *resource + for _, res := range s.resources { + if res.kind == searchKind && strings.EqualFold(res.name, name) && (found == nil || key(res.id) < key(found.id)) { + found = res + } + } + return found +} + +// searchStateOf returns the data plane state of the service res. The caller holds s.mu. +func (s *Server) searchStateOf(res *resource) *searchState { + if res.searchData == nil { + res.searchData = &searchState{indexes: map[string]*searchIndex{}, dataSources: map[string]*searchObject{}, indexers: map[string]*indexer{}} + } + return res.searchData +} + +// searchFaultError is the error a fault answers with. Search leaves the code +// of most errors empty, as the fault package's generic reasons become. +func searchFaultError(f fault.Fault) *apiError { + status := cmp.Or(f.Status, http.StatusServiceUnavailable) + code := f.Reason + switch code { + case "", "backendError": + code = "" + case "rateLimitExceeded": + code, status = "", http.StatusServiceUnavailable + } + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} +} + +func (s *Server) searchHeaders(h http.Header) { + h.Set("request-id", fmt.Sprintf("%08x-0000-4000-8000-%012x", 0, s.requests.Add(1))) + h.Set("OData-Version", "4.0") +} + +func (s *Server) writeSearchError(w http.ResponseWriter, e *apiError) { + s.searchHeaders(w.Header()) + writeJSON(w, e.Status, e.Header, encode(map[string]any{"error": map[string]any{"code": e.Code, "message": e.Message}})) +} + +func (s *Server) writeSearchReply(w http.ResponseWriter, rep *searchReply) { + h := w.Header() + s.searchHeaders(h) + if rep.etag != "" { + h.Set("ETag", rep.etag) + } + if rep.body == nil { + w.WriteHeader(rep.status) + return + } + var buf bytes.Buffer + if err := json.NewEncoder(&buf).Encode(rep.body); err != nil { + panic(fmt.Sprintf("squall: encoding a response: %v", err)) + } + h.Set("Content-Type", "application/json; odata.metadata=minimal; odata.streaming=true") + w.WriteHeader(rep.status) + _, _ = w.Write(buf.Bytes()) +} + +// searchETag returns a new ETag in the form Search gives them. The caller holds s.mu. +func (s *Server) searchETag() string { + s.seq++ + return fmt.Sprintf(`"0x8D%013X"`, s.seq) +} + +func (o *searchObject) render(c *searchCall, collection string) map[string]any { + m := maps.Clone(o.body) + m["@odata.context"] = c.base + "/$metadata#" + collection + "/$entity" + m["@odata.etag"] = o.etag + return m +} + +// readSearchObject reads a definition from the request body, rejecting +// members not in known, and checks that the name it gives, if any, is the +// one in the URL. +func readSearchObject(c *searchCall, typeName string, known ...string) (map[string]any, *apiError) { + body, err := readObject(c.r) + if err != nil { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: %s", err.Message) + } + for _, k := range slices.Sorted(maps.Keys(body)) { + if strings.HasPrefix(k, "@odata.") { + delete(body, k) + continue + } + if k != "name" && !slices.Contains(known, k) { + return nil, newError(http.StatusBadRequest, "", + "The request is invalid. Details: The property '%s' does not exist on type '%s'. Make sure to only use property names that are defined by the type.", k, typeName) + } + } + if name, ok := body["name"].(string); ok && name != c.name { + return nil, newError(http.StatusBadRequest, "", "The %s name '%s' in the request body does not match the name '%s' in the URL.", typeName, name, c.name) + } + body["name"] = c.name + return body, nil +} + +// searchPrecondition applies If-Match and If-None-Match to a change of existing, which may be nil. +func searchPrecondition(r *http.Request, existing *searchObject) *apiError { + m, none := r.Header.Get("If-Match"), r.Header.Get("If-None-Match") + if m != "" && (existing == nil || m != "*" && m != existing.etag) || none == "*" && existing != nil { + return newError(http.StatusPreconditionFailed, "", + "The precondition given in one of the request headers evaluated to false. No change was made to the resource from this request.") + } + return nil +} + +// putAnswer answers a create with 201 and an update with 200, or 204 when +// the caller prefers return=minimal. +func putAnswer(c *searchCall, created bool, o *searchObject, collection string) *searchReply { + status := http.StatusOK + if created { + status = http.StatusCreated + } + if strings.Contains(c.r.Header.Get("Prefer"), "return=minimal") { + return &searchReply{status: http.StatusNoContent, etag: o.etag} + } + return &searchReply{status: status, etag: o.etag, body: o.render(c, collection)} +} + +func searchNotFound(what, name, service string) *apiError { + return newError(http.StatusNotFound, "", "No %s with the name '%s' was found in a service named '%s'.", what, name, service) +} + +var ( + indexNames = regexp.MustCompile(`^[a-z0-9](?:-?[a-z0-9])*$`) + objectNames = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9_]|-[A-Za-z0-9_])*$`) +) + +func checkSearchName(what, name string, pattern *regexp.Regexp) *apiError { + if len(name) > 128 || !pattern.MatchString(name) { + return newError(http.StatusBadRequest, "", "The %s name '%s' is invalid.", what, name) + } + return nil +} + +func (s *Server) putSearchIndex(c *searchCall, st *searchState) (*searchReply, *apiError) { + if err := checkSearchName("index", c.name, indexNames); err != nil { + return nil, err + } + body, err := readSearchObject(c, "Index", + "analyzers", "charFilters", "corsOptions", "defaultScoringProfile", "description", "encryptionKey", "fields", "normalizers", + "scoringProfiles", "semantic", "similarity", "suggesters", "tokenFilters", "tokenizers", "vectorSearch") + if err != nil { + return nil, err + } + existing := st.indexes[c.name] + var prior *searchObject + if existing != nil { + prior = &existing.searchObject + } + if err := searchPrecondition(c.r, prior); err != nil { + return nil, err + } + fields, keyField, err := indexFields(body) + if err != nil { + return nil, err + } + if existing != nil { + for name, old := range existing.fields { + now := fields[name] + if now == nil || str(now, "type") != str(old, "type") || name == existing.key && name != keyField { + return nil, newError(http.StatusBadRequest, "", "Existing field '%s' cannot be removed or have its type or key changed.", name) + } + } + } + idx := existing + if idx == nil { + idx = &searchIndex{docs: map[string]map[string]any{}} + st.indexes[c.name] = idx + } + idx.body, idx.etag, idx.key, idx.fields = body, s.searchETag(), keyField, fields + return putAnswer(c, existing == nil, &idx.searchObject, "indexes"), nil +} + +// indexFields reads an index's fields, by name, and the name of its key, +// which must be the one key field and of type Edm.String. +func indexFields(body map[string]any) (map[string]map[string]any, string, *apiError) { + list, err := objects(body, "fields") + if err != nil { + return nil, "", newError(http.StatusBadRequest, "", "The request is invalid. Details: %s", err.Message) + } + fields := map[string]map[string]any{} + keyField := "" + for _, f := range list { + name, typ := str(f, "name"), str(f, "type") + if name == "" || typ == "" { + return nil, "", newError(http.StatusBadRequest, "", "The request is invalid. Details: every field needs a name and a type.") + } + if fields[name] != nil { + return nil, "", newError(http.StatusBadRequest, "", "The request is invalid. Details: the field name '%s' is used more than once.", name) + } + fields[name] = f + if isKey, _ := boolean(f, "key"); isKey { + if keyField != "" || typ != "Edm.String" { + keyField = "" + break + } + keyField = name + } + } + if keyField == "" { + return nil, "", newError(http.StatusBadRequest, "", "The request is invalid. Details: the index must have exactly one key field, of type Edm.String.") + } + return fields, keyField, nil +} + +func (s *Server) getSearchIndex(c *searchCall, st *searchState) (*searchReply, *apiError) { + idx := st.indexes[c.name] + if idx == nil { + return nil, searchNotFound("index", c.name, c.svc.name) + } + return &searchReply{status: http.StatusOK, etag: idx.etag, body: idx.render(c, "indexes")}, nil +} + +// deleteSearchIndex deletes the index and its documents, answering 404 for +// one that does not exist, as Search does. +func (s *Server) deleteSearchIndex(c *searchCall, st *searchState) (*searchReply, *apiError) { + idx := st.indexes[c.name] + if idx == nil { + return nil, searchNotFound("index", c.name, c.svc.name) + } + if err := searchPrecondition(c.r, &idx.searchObject); err != nil { + return nil, err + } + delete(st.indexes, c.name) + return &searchReply{status: http.StatusNoContent}, nil +} + +var dataSourceTypes = []string{"adlsgen2", "azureblob", "azuresql", "azuretable", "cosmosdb", "mysql", "onelake"} + +// unchangedSecret stands for a data source's connection string, which GET +// leaves out, in an update that keeps it. +var unchangedSecret = []string{"", ""} + +func (s *Server) putDataSource(c *searchCall, st *searchState) (*searchReply, *apiError) { + if err := checkSearchName("data source", c.name, objectNames); err != nil { + return nil, err + } + body, err := readSearchObject(c, "DataSource", + "container", "credentials", "dataChangeDetectionPolicy", "dataDeletionDetectionPolicy", "description", "encryptionKey", "identity", + "indexerPermissionOptions", "type") + if err != nil { + return nil, err + } + existing := st.dataSources[c.name] + if err := searchPrecondition(c.r, existing); err != nil { + return nil, err + } + if !slices.Contains(dataSourceTypes, str(body, "type")) { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: dataSource.type must be one of %s.", strings.Join(dataSourceTypes, ", ")) + } + creds, _ := body["credentials"].(map[string]any) + conn := str(creds, "connectionString") + if slices.Contains(unchangedSecret, conn) && existing != nil { + conn = str(existing.body["credentials"].(map[string]any), "connectionString") + } + container, _ := body["container"].(map[string]any) + if conn == "" || slices.Contains(unchangedSecret, conn) || str(container, "name") == "" { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: a data source needs credentials.connectionString and container.name.") + } + creds = maps.Clone(creds) + creds["connectionString"] = conn + body["credentials"] = creds + ds := existing + if ds == nil { + ds = &searchObject{} + st.dataSources[c.name] = ds + } + ds.body, ds.etag = body, s.searchETag() + view := dataSourceView{ds}.object() + return putAnswer(c, existing == nil, &view, "datasources"), nil +} + +// dataSourceView shows a data source without its connection string, as +// Search leaves it out of what it returns. +type dataSourceView struct{ *searchObject } + +func (v dataSourceView) object() searchObject { + body := maps.Clone(v.body) + creds := maps.Clone(body["credentials"].(map[string]any)) + creds["connectionString"] = nil + body["credentials"] = creds + return searchObject{body: body, etag: v.etag} +} + +func (s *Server) getDataSource(c *searchCall, st *searchState) (*searchReply, *apiError) { + ds := st.dataSources[c.name] + if ds == nil { + return nil, searchNotFound("data source", c.name, c.svc.name) + } + view := dataSourceView{ds}.object() + return &searchReply{status: http.StatusOK, etag: ds.etag, body: view.render(c, "datasources")}, nil +} + +func (s *Server) deleteDataSource(c *searchCall, st *searchState) (*searchReply, *apiError) { + ds := st.dataSources[c.name] + if ds == nil { + return nil, searchNotFound("data source", c.name, c.svc.name) + } + if err := searchPrecondition(c.r, ds); err != nil { + return nil, err + } + delete(st.dataSources, c.name) + return &searchReply{status: http.StatusNoContent}, nil +} + +func (s *Server) putIndexer(c *searchCall, st *searchState) (*searchReply, *apiError) { + if err := checkSearchName("indexer", c.name, objectNames); err != nil { + return nil, err + } + body, err := readSearchObject(c, "Indexer", + "cache", "dataSourceName", "description", "disabled", "encryptionKey", "fieldMappings", "outputFieldMappings", "parameters", "schedule", + "skillsetName", "targetIndexName") + if err != nil { + return nil, err + } + existing := st.indexers[c.name] + var prior *searchObject + if existing != nil { + prior = &existing.searchObject + } + if err := searchPrecondition(c.r, prior); err != nil { + return nil, err + } + if str(body, "skillsetName") != "" { + return nil, unsupported("skillsets are not supported") + } + source, target := str(body, "dataSourceName"), str(body, "targetIndexName") + if source == "" || target == "" { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: an indexer needs dataSourceName and targetIndexName.") + } + if st.dataSources[source] == nil { + return nil, newError(http.StatusBadRequest, "", "This indexer refers to a data source '%s' that doesn't exist.", source) + } + if st.indexes[target] == nil { + return nil, newError(http.StatusBadRequest, "", "This indexer refers to a target index '%s' that doesn't exist.", target) + } + ix := existing + if ix == nil { + ix = &indexer{} + st.indexers[c.name] = ix + } + ix.body, ix.etag = body, s.searchETag() + if disabled, _ := boolean(body, "disabled"); !disabled && existing == nil { + s.startRun(ix, nil) + } + return putAnswer(c, existing == nil, &ix.searchObject, "indexers"), nil +} + +func (s *Server) indexerNamed(c *searchCall, st *searchState) (*indexer, *apiError) { + ix := st.indexers[c.name] + if ix == nil { + return nil, searchNotFound("indexer", c.name, c.svc.name) + } + return ix, nil +} + +func (s *Server) getIndexer(c *searchCall, st *searchState) (*searchReply, *apiError) { + ix, err := s.indexerNamed(c, st) + if err != nil { + return nil, err + } + return &searchReply{status: http.StatusOK, etag: ix.etag, body: ix.render(c, "indexers")}, nil +} + +func (s *Server) deleteIndexer(c *searchCall, st *searchState) (*searchReply, *apiError) { + ix, err := s.indexerNamed(c, st) + if err != nil { + return nil, err + } + if err := searchPrecondition(c.r, &ix.searchObject); err != nil { + return nil, err + } + delete(st.indexers, c.name) + return &searchReply{status: http.StatusNoContent}, nil +} + +func (ix *indexer) running() bool { return len(ix.runs) > 0 && ix.runs[0].status == runInProgress } + +// startRun starts an execution of ix, which ends in failure when set, at +// once or after the reads [WithSettleAfter] sets. The caller holds s.mu. +func (s *Server) startRun(ix *indexer, failure *apiError) { + run := &indexerRun{status: runInProgress, start: s.now(), wait: max(s.settleAfter, 0)} + ix.runs = append([]*indexerRun{run}, ix.runs[:min(len(ix.runs), maxRuns-1)]...) + switch { + case failure != nil: + run.status, run.err, run.end = runFailure, failure.Message, s.now() + case s.settleAfter == 0: + s.finishRun(run) + } +} + +// finishRun ends run, if it is in progress, in success. The caller holds s.mu. +func (s *Server) finishRun(run *indexerRun) { + if run.status == runInProgress { + run.status, run.end = runSuccess, s.now() + } +} + +// runIndexer starts an execution of the indexer, which fails with 409 while +// one is in progress, as Search answers. +func (s *Server) runIndexer(c *searchCall, st *searchState) (*searchReply, *apiError) { + ix, err := s.indexerNamed(c, st) + if err != nil { + return nil, err + } + if ix.running() { + return nil, newError(http.StatusConflict, "", "Another indexer invocation is currently in progress; concurrent invocations are not allowed.") + } + s.startRun(ix, c.opFault) + return &searchReply{status: http.StatusAccepted}, nil +} + +// indexerStatus answers the indexer's executions, counting the read toward +// the one in progress. +func (s *Server) indexerStatus(c *searchCall, st *searchState) (*searchReply, *apiError) { + ix, err := s.indexerNamed(c, st) + if err != nil { + return nil, err + } + if ix.running() && s.settleAfter >= 0 { + if run := ix.runs[0]; run.wait == 0 { + s.finishRun(run) + } else { + run.wait-- + } + } + history := make([]any, 0, len(ix.runs)) + for _, run := range ix.runs { + history = append(history, run.render()) + } + var last any + if len(history) > 0 { + last = history[0] + } + return &searchReply{status: http.StatusOK, body: map[string]any{ + "@odata.context": c.base + "/$metadata#Microsoft.Azure.Search.V2024_07_01.IndexerExecutionInfo", + "name": c.name, "status": "running", "lastResult": last, "executionHistory": history, + "limits": map[string]any{"maxRunTime": "PT2H", "maxDocumentExtractionSize": 134217728, "maxDocumentContentCharactersToExtract": 4194304}, + }}, nil +} + +func (run *indexerRun) render() map[string]any { + m := map[string]any{ + "status": run.status, "statusDetail": nil, "errorMessage": nil, "startTime": timestamp(run.start), "endTime": nil, + "itemsProcessed": 0, "itemsFailed": 0, "initialTrackingState": nil, "finalTrackingState": nil, "errors": []any{}, "warnings": []any{}, + } + if run.err != "" { + m["errorMessage"] = run.err + } + if !run.end.IsZero() { + m["endTime"] = timestamp(run.end) + } + return m +} + +// settleSearch ends the indexer executions in progress. The caller holds s.mu. +func (s *Server) settleSearch(st *searchState) { + for _, ix := range st.indexers { + if ix.running() { + s.finishRun(ix.runs[0]) + } + } +} + +func (s *Server) indexOf(c *searchCall, st *searchState) (*searchIndex, *apiError) { + idx := st.indexes[c.name] + if idx == nil { + return nil, searchNotFound("index", c.name, c.svc.name) + } + return idx, nil +} + +// indexDocuments applies a batch of upload, merge, mergeOrUpload and delete +// actions, answering 207 when any of them fails. +func (s *Server) indexDocuments(c *searchCall, st *searchState) (*searchReply, *apiError) { + idx, err := s.indexOf(c, st) + if err != nil { + return nil, err + } + body, err := readObject(c.r) + if err != nil { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: %s", err.Message) + } + actions, err := objects(body, "value") + if err != nil { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: %s", err.Message) + } + if len(actions) > maxIndexBatch { + return nil, newError(http.StatusRequestEntityTooLarge, "", "The request is too large. A batch can hold at most %d actions.", maxIndexBatch) + } + for i, a := range actions { + for k := range a { + if k != "@search.action" && idx.fields[k] == nil { + return nil, newError(http.StatusBadRequest, "", + "The request is invalid. Details: The property '%s' does not exist on type 'search.documentFields'. Make sure to only use property names that are defined by the type.", k) + } + } + if key, _ := a[idx.key].(string); key == "" { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: actions : %d: Document key cannot be missing or empty.", i) + } + if !slices.Contains([]string{"", "upload", "merge", "mergeOrUpload", "delete"}, str(a, "@search.action")) { + return nil, newError(http.StatusBadRequest, "", "The request is invalid. Details: actions : %d: unknown @search.action '%s'.", i, str(a, "@search.action")) + } + } + status := http.StatusOK + results := make([]any, 0, len(actions)) + for _, a := range actions { + key := a[idx.key].(string) + doc := maps.Clone(a) + delete(doc, "@search.action") + code, msg := http.StatusOK, "" + existing := idx.docs[key] + switch cmp.Or(str(a, "@search.action"), "upload") { + case "upload": + if existing == nil { + code = http.StatusCreated + } + idx.docs[key] = doc + case "merge", "mergeOrUpload": + switch { + case existing != nil: + maps.Copy(existing, doc) + case str(a, "@search.action") == "merge": + code, msg = http.StatusNotFound, "Document not found." + default: + code, idx.docs[key] = http.StatusCreated, doc + } + case "delete": + delete(idx.docs, key) + } + result := map[string]any{"key": key, "status": code < 300, "errorMessage": nil, "statusCode": code} + if msg != "" { + result["errorMessage"], status = msg, http.StatusMultiStatus + } + results = append(results, result) + } + return &searchReply{status: status, body: map[string]any{"value": results}}, nil +} + +// searchParams are the query parameters a document search takes. +var searchParams = []string{"api-version", "search", "$select", "$top", "$skip", "$count"} + +// searchDocuments lists the index's documents, in key order, for a search +// of * or none. +func (s *Server) searchDocuments(c *searchCall, st *searchState) (*searchReply, *apiError) { + idx, err := s.indexOf(c, st) + if err != nil { + return nil, err + } + for k := range c.query { + if !slices.Contains(searchParams, k) { + return nil, unsupported("the search parameter %s is not supported", k) + } + } + if q := c.query.Get("search"); q != "" && q != "*" { + return nil, unsupported("full-text search is not supported; search for * or leave search out") + } + top, err := searchInt(c, "$top", 50) + if err != nil { + return nil, err + } + skip, err := searchInt(c, "$skip", 0) + if err != nil { + return nil, err + } + var selected []string + if sel := c.query.Get("$select"); sel != "" && sel != "*" { + for f := range strings.SplitSeq(sel, ",") { + f = strings.TrimSpace(f) + if idx.fields[f] == nil { + return nil, newError(http.StatusBadRequest, "", "Invalid expression: Could not find a property named '%s' on type 'search.document'.\r\nParameter name: $select", f) + } + selected = append(selected, f) + } + } + keys := slices.Sorted(maps.Keys(idx.docs)) + body := map[string]any{"@odata.context": c.base + "/indexes('" + c.name + "')/$metadata#docs(*)"} + if c.query.Get("$count") == "true" { + body["@odata.count"] = len(keys) + } + keys = keys[min(skip, len(keys)):] + keys = keys[:min(top, len(keys))] + value := make([]any, 0, len(keys)) + for _, k := range keys { + doc := idx.docs[k] + hit := map[string]any{"@search.score": 1.0} + for name, field := range idx.fields { + if retrievable, set := boolean(field, "retrievable"); set && !retrievable { + continue + } + if selected != nil && !slices.Contains(selected, name) { + continue + } + if v, ok := doc[name]; ok { + hit[name] = v + } + } + value = append(value, hit) + } + body["value"] = value + return &searchReply{status: http.StatusOK, body: body}, nil +} + +func searchInt(c *searchCall, name string, def int) (int, *apiError) { + v := c.query.Get(name) + if v == "" { + return def, nil + } + n, err := strconv.Atoi(v) + if err != nil || n < 0 { + return 0, newError(http.StatusBadRequest, "", "Invalid expression: %s must be a non-negative integer.", name) + } + return n, nil +} diff --git a/azure/arm/server.go b/azure/arm/server.go index 2396873..277217e 100644 --- a/azure/arm/server.go +++ b/azure/arm/server.go @@ -25,18 +25,19 @@ // global location (create or update, get; another location fails with // MissingRegistrationForLocation), and A record sets (create or update, // get, delete); -// - Microsoft.Compute virtual machines: create or update, get, list in a -// group, instance view, deallocate, start and delete, and their -// extensions (create or update, get, list on a VM and delete); +// - Microsoft.Compute virtual machines: create or update, update, get, +// list in a group, instance view, deallocate, power off, start and +// delete, their data disks, and their extensions (create or update, get, +// list on a VM and delete); // - Microsoft.Compute scale sets in the Uniform orchestration mode: create // or update, update, get, list in a group, delete and delete instances, // and their VMs (list, get); -// - Microsoft.Compute resource SKUs: list, which lists none; +// - Microsoft.Compute resource SKUs: list, as [WithResourceSKUs] sets them; // - Microsoft.Compute managed disks and snapshots: create or update, get, // list in a group and delete, and a snapshot's access (grant and revoke); // - Microsoft.Compute galleries, their image definitions and image // versions: create or update, get, list in their group, gallery or image -// definition, and delete; +// definition, and delete, and image versions also update; // - Microsoft.Storage: storage accounts (create, get, list in a group or // subscription, list keys and delete), name availability checks, the // blob, file, queue and table services' properties (set and get), blob @@ -61,8 +62,13 @@ // and delete), their deployments (create or update, get, list and // delete), deleted accounts (get and purge) and model capacities (list, // as [WithModelCapacities] sets them); +// - the Azure OpenAI data plane of Cognitive Services accounts, which +// [Server.OpenAI] serves: ingestion jobs (create and get); // - Microsoft.Search: search services (create or update, get and delete) // and their admin keys (list); +// - the Azure AI Search data plane, which [Server.Search] serves: indexes, +// data sources and indexers (create or update, get and delete), indexer +// runs and status, and documents (index, and search for all); // - Microsoft.KeyVault: vaults (create or update, get and list in a group); // - Microsoft.Insights: Application Insights components (create or update, // get and list in a group); @@ -133,6 +139,9 @@ // with 400. // - Listing groups or a group's resources with $top returns at most that // many, with no nextLink; Azure may page them instead. +// - A fault that fails an operation leaves no trace of the call, where +// Azure may leave the resource Failed; [Server.FailProvisioning] sets up +// a resource in that state. // - Resource names, subscription IDs and locations are not validated, and // names match without regard to case. Tags are not validated. Fields the // server only records keep the JSON the caller sent; fields it does not @@ -243,6 +252,23 @@ // disk ID, with the group's name upper-cased as Azure writes it. Deleting // it deletes the interfaces whose deleteOption is Delete and detaches the // rest. +// - An update that changes a VM's osProfile.customData or its Linux SSH +// public keys fails with 409 PropertyChangeNotAllowed, "Changing property +// 'customData' is not allowed." or naming +// linuxConfiguration.ssh.publicKeys, as Azure refuses both; one that +// leaves either out keeps it, as a GET leaves out customData. +// - A VM create whose operation [fault.ModeFailOperation] fails leaves the +// VM Failed, as Azure leaves a VM whose provisioning failed, such as with +// AllocationFailed: it has its interfaces and OS disk, no power state, and +// an instance view whose one status is +// ProvisioningState/failed/{code} at level Error with the error's +// message. A PUT over it provisions it again, as a retry does in Azure; +// deleting it deletes it. A failed update leaves the VM as it was. +// - Powering a VM off (powerOff, with or without skipShutdown) stops it, +// showing PowerState/stopping while in progress and then +// PowerState/stopped, VM stopped; it keeps its OS disk Attached and its +// LastOwnershipUpdateTime, as a stopped VM keeps its resources allocated. +// Start runs it again. // - A VM made from an image makes its OS disk a managed disk, Attached and // managed by the VM, and Reserved while the VM is deallocated, as Azure // documents those states. Its SKU is the OS disk's storageAccountType and @@ -256,8 +282,34 @@ // OperationNotAllowed, naming the VM. A disk's LastOwnershipUpdateTime, // capitalized as Azure writes it, is when a VM last attached or released // it, or was last deallocated or started while holding it, and is absent -// until then. Data disks, and the OS disks of scale set VMs, are not -// modeled. +// until then. The disks of scale set VMs are not modeled. +// - A VM's PATCH takes tags and storageProfile.dataDisks. The OS disk and +// image reference it sends back are kept as they were, except that +// renaming the OS disk fails with PropertyChangeNotAllowed; other +// properties, identity, plan and zones fail with 400 as not supported, +// so change them with a PUT. It answers 200, with an +// Azure-AsyncOperation URL while it is in progress. +// - A VM's data disks attach managed disks that exist (createOption +// Attach), each at its own lun from 0 to 63. A lun outside that range, +// which Azure narrows by VM size, or one two disks share ("A disk at LUN +// 0 already exists.") fails with InvalidParameter, which is inferred. +// Other createOptions, image, vhd and sourceResource fail with 400 as +// not supported. A PUT or PATCH that lists dataDisks replaces them: a +// disk it leaves out, or marks toBeDetached, is detached and dropped from +// the list, as Microsoft documents detaching a data disk. One that leaves +// out dataDisks keeps them, which for a PUT is inferred, as one that +// leaves out osProfile keeps it. Attaching a disk another VM holds fails +// with 409 OperationNotAllowed, as for an OS disk; a disk the server does +// not hold is recorded, not checked, and the location of one it holds is +// not checked. A data disk shows its disk's name and diskSizeGB, +// toBeDetached false, and deleteOption Detach unless set, the default +// Microsoft documents. Its disk shows managedBy and diskState as an OS +// disk does, and its LastOwnershipUpdateTime moves as an OS disk's does. +// Deleting the VM detaches its data disks, deleting those whose +// deleteOption is Delete, and deleting a group that holds a disk a VM +// elsewhere has attached fails with ResourceGroupDeletionBlocked, as an +// attached disk cannot be deleted. caching, writeAcceleratorEnabled and +// detachOption are recorded, not modeled. // - A VM extension create answers 201, and an update 200, with an // Azure-AsyncOperation URL under // Microsoft.Compute/locations/{location}/operations; a delete in progress @@ -355,6 +407,15 @@ // shows display names such as West US. Replication between regions, // sharing, soft deletion, checking a version's source against its image // definition, and VMs made from a version are not modeled. +// - An image version update (PATCH) takes tags and the publishingProfile +// and safetyProfile properties, merging the members it gives into the +// ones the version has, as an ARM PATCH does; storageProfile, +// securityProfile and restore fail with 400, as the server rejects input it +// does not model. It answers 200 with an Azure-AsyncOperation URL under +// capsOperations while in progress, the version showing Updating, as a +// PUT does. safetyProfile.blockDeletionBeforeEndOfLife is recorded: a +// blocked version can still be deleted, where Azure refuses it before its +// end-of-life date. // - A scale set's VMs are numbered from 0 and never reuse a number. Raising // sku.capacity creates VMs, each with the network interfaces and public // IP addresses its profile describes; lowering it deletes the newest, @@ -372,8 +433,15 @@ // with PropertyChangeNotAllowed. A PATCH takes sku and tags only. // Deleting instances that do not exist fails with InvalidParameter and // deletes nothing. Scale set VMs are always running. -// - Resource SKUs list none: a caller that checks availability sees no -// restrictions. +// - Resource SKUs list those [WithResourceSKUs] sets, none by default, each +// in one location, as Azure lists them. The list takes the one $filter +// Azure supports, location eq '{location}', matching locations without +// regard to case or spaces; any other filter fails with 400. Every SKU is +// in the one page, with no nextLink, and includeExtendedLocations adds +// nothing, as no SKU has extended locations. A restriction with zones is a +// Zone restriction and one without a Location restriction, whose values +// and restrictionInfo name the SKU's location. The SKUs a subscription is +// offered are not checked when a VM or scale set is created. // - A storage account create that finishes at once answers 200, as Azure // Storage does, and one in progress answers 202 with an empty body and // only a Location URL, under Microsoft.Storage/operations, which answers @@ -737,7 +805,10 @@ // 00000000-0000-0000-0000-000000000000, as the server does not read // the caller's token. // An update answers 200 and shows Updating, where Azure answers 201 and -// shows Creating. A subnet check answers 200 for any subnet. +// shows Creating. A subnet check answers 200 for any subnet, unless +// [Server.FailSubnetCheck] fails it: then it answers 400 with the error +// the API defines for it, {"filesystemSubnet": {"status": "Invalid", +// "message": ...}}, and no x-ms-error-code header. // - A Cognitive Services account change in progress answers with an // Azure-AsyncOperation URL under // Microsoft.CognitiveServices/locations/{location}/operationResults, whose @@ -761,8 +832,8 @@ // and the SDK reads the resource until its provisioningState ends, so // [fault.ModeFailOperation] fails their writes as [fault.ModeReject] // does. A deployment being created shows Accepted. A search service shows -// provisioningState and status provisioning, then succeeded and running, -// in lower case as Search writes them, and the endpoint +// provisioningState and status provisioning, then succeeded and running +// (or failed and error), in lower case as Search writes them, and the endpoint // https://{name}.search.windows.net. Deleting a deployment or a search // service answers 200 at once. Search service names are not unique across // the server, where Azure makes them unique across Azure. Admin keys are @@ -828,6 +899,72 @@ // has not replicated yet never fails with PrincipalNotFound, and names // need not be GUIDs or unique across scopes. Deleting the group deletes // the assignments at its scope. +// - The Search data plane takes the service from a host name such as +// {service}.search.windows.net, or else from the first path segment, and +// addresses an index, data source or indexer as indexes/{name} or, as +// the REST API also accepts, indexes('{name}'). Services in different +// groups may share a name; the one whose ID sorts first is served. Each +// call needs an api-version, which may be any value, and one of the +// service's admin keys in api-key: a missing or wrong key fails with 403, +// as Search answers a wrong one, and a Microsoft Entra ID token with 400 +// as not supported. Query keys are not modeled. Errors are +// {"error": {"code", "message"}} with an empty code, as Search writes +// most of them; the messages other than those for a missing api-version, +// a concurrent indexer run, an unknown document property and a failed +// precondition are inferred. A create answers 201 and an update 200 with +// the definition, its @odata.etag and an ETag header, or 204 with Prefer: +// return=minimal, and If-Match and If-None-Match apply to writes and +// deletes. A get or delete of something that does not exist answers 404, +// as Search does. Names follow Microsoft's naming rules: up to 128 +// characters, an index's lower-case letters, digits and dashes, and a +// data source's or indexer's also upper-case letters and underscores. +// Definitions keep the JSON the caller sent, @odata annotations aside, +// and members Search does not define fail with 400. Deleting a search +// service, or its group, deletes what its data plane holds. +// - An index needs one key field, of type Edm.String, and each field a name +// and a type; an update may add fields but not remove one or change its +// type or which is the key, which fails with 400 (inferred). Deleting an +// index deletes its documents. Index Documents takes upload, merge, +// mergeOrUpload and delete actions, up to 1,000 a batch, and answers each +// action's statusCode (201 for a new document, 200 otherwise, 404 for a +// merge of a missing one), with 207 when one fails, as Microsoft +// documents; values are not checked against their fields' types. Search +// Documents (GET) takes a search of * or none, $select, $top (50 unless +// set), $skip and $count, and lists the documents in key order, each with +// an @search.score of 1 and without fields that are not retrievable; +// other parameters, full-text search included, fail with 400. +// - A data source needs a type the API lists, credentials.connectionString +// and container.name. It shows its connection string as null, and an +// update that sends or keeps it, as Microsoft +// documents. An indexer needs dataSourceName and targetIndexName, which +// must exist (400, inferred); skillsets are not modeled, so one that names +// a skillset fails with 400. An indexer runs when it is created, unless +// disabled, and when run, which answers 202, as Microsoft documents; a run +// while another is in progress fails with 409. Indexers read nothing and +// index nothing: a run processes no items and leaves the index's +// documents as they were. A run is inProgress until the reads of the +// indexer's status [WithSettleAfter] sets, or [Server.Settle], then +// success. The status shows the indexer running, its last result and up +// to 50 executions, newest first, and a Standard service's limits, which +// are inferred. Schedules, resets, change tracking and listing are not +// served. +// - The Azure OpenAI data plane takes the account's custom subdomain from a +// host name such as {subdomain}.openai.azure.com, or else from the first +// path segment, and serves accounts of kind OpenAI or AIServices; other +// accounts, and calls without an api-version, answer 404 Resource not +// found, which for a missing api-version is inferred. Each call needs one +// of the account's keys in api-key: a missing or wrong one fails with 401 +// and the message Azure OpenAI answers, and a Microsoft Entra ID token +// with 400 as not supported. An ingestion job needs kind SystemCompute, +// with searchServiceConnection and datasource, or UserCompute, with +// workspaceId, compute, target and datasource. Its connections and data +// source are recorded, not checked or read, and it creates nothing in the +// search service. A create answers 200 with the job, and one with the ID +// of an existing job replaces and restarts it, which is inferred. A job +// is running until the reads of it [WithSettleAfter] sets, or +// [Server.Settle], then succeeded. A get of a job that does not exist +// answers 404, whose code and message are inferred. Listing jobs and +// their runs are not served. // - Every namespace is Registered in every subscription unless // [WithUnregisteredProviders] names it; Azure registers only some by // default, such as Microsoft.Resources and Microsoft.CostManagement but @@ -869,7 +1006,19 @@ // DeleteContainer, whose resource is {account}/{container}/{blob}. Blob // service faults fail as [fault.ModeReject] does for ModeFailOperation, and // the generic reasons become InternalError, or ServerBusy for 503 and rate -// limits. Other fault method names are the operation's Azure RBAC action, such as +// limits. Search data plane faults are named for the operation's ID in the +// REST API's specification, such as Indexes_CreateOrUpdate, Indexes_Delete, +// DataSources_Delete, Indexers_Run, Indexers_GetStatus, Documents_Index or +// Documents_SearchGet, whose resource is {service}/{collection}/{name} with +// the service in lower case, such as find/indexers/nightly; ModeFailOperation makes Indexers_Run start a run +// that ends in transientFailure with the fault's message, and other calls +// fail as ModeReject does. The generic reasons become an empty code, and a +// rate limit 503. Azure OpenAI faults are named IngestionJobs_Create and +// IngestionJobs_Get, whose resource is {subdomain}/ingestion/jobs/{jobId} +// with the subdomain in lower case; +// ModeFailOperation makes IngestionJobs_Create answer a job that has failed +// with the fault's error, and the generic reasons become the HTTP status, +// such as "503" or "429", as Azure OpenAI writes its codes. Other fault method names are the operation's Azure RBAC action, such as // "Microsoft.Compute/virtualMachines/write", // "Microsoft.Compute/virtualMachines/deallocate/action" or // "Microsoft.Resources/subscriptions/resourceGroups/delete". A call's @@ -940,7 +1089,9 @@ // "*" does not grant them, where a grant of "*" here does. Legal holds and // policies need containers/setLegalHold/action, // containers/clearLegalHold/action, containers/immutabilityPolicies/write and -// containers/immutabilityPolicies/lock/action. Actions are not +// containers/immutabilityPolicies/lock/action. The Search and Azure OpenAI +// data planes authenticate with keys, which Azure RBAC does not apply to, so +// the policy does not check them. Actions are not // checked against the scope they act on: a grant covers every subscription. // // A lost response aborts the handler with [http.ErrAbortHandler] after @@ -1008,6 +1159,9 @@ type Server struct { public *pool deleted map[string]*softDeleted capacities []ModelCapacity + skus []ResourceSKU + // subnetChecks are the messages subnet checks fail with, by the subnet's ID's key. + subnetChecks map[string]string // unregistered are the namespaces that start NotRegistered, by their lower-case names. unregistered map[string]string providers map[string]*provider @@ -1061,6 +1215,7 @@ func New(opts ...Option) *Server { unregistered: map[string]string{}, providers: map[string]*provider{}, exports: map[string]*export{}, + subnetChecks: map[string]string{}, logWorkspacesDeleted: map[string]*softDeleted{}, // Neither range is routable on the internet, so a test cannot reach a real host by mistake. @@ -1169,10 +1324,12 @@ func (s *Server) registerRoutes() { vm := compute + "/virtualMachines/{name}" s.add("GET", compute+"/virtualMachines", vmKind.action("read"), false, s.listVMs) s.add("PUT", vm, vmKind.action("write"), true, s.putVM) + s.add("PATCH", vm, vmKind.action("write"), true, s.patchVM) s.add("GET", vm, vmKind.action("read"), false, s.getVM) s.add("GET", vm+"/instanceView", vmKind.action("instanceView/read"), false, s.vmInstanceView) s.add("POST", vm+"/deallocate", vmKind.action("deallocate/action"), true, s.powerVM(powerDeallocated)) s.add("POST", vm+"/start", vmKind.action("start/action"), true, s.powerVM(powerRunning)) + s.add("POST", vm+"/powerOff", vmKind.action("powerOff/action"), true, s.powerVM(powerStopped)) s.add("DELETE", vm, vmKind.action("delete"), true, s.deleteVM) s.registerExtensionRoutes() diff --git a/azure/arm/skus.go b/azure/arm/skus.go new file mode 100644 index 0000000..41b1ef0 --- /dev/null +++ b/azure/arm/skus.go @@ -0,0 +1,105 @@ +package arm + +import ( + "cmp" + "maps" + "slices" + "strings" +) + +// ResourceSKU is a SKU a subscription is offered in one location, as +// Microsoft.Compute lists resource SKUs, such as the VM size Standard_D2s_v3 +// in eastus. +type ResourceSKU struct { + // ResourceType is the type the SKU is a size of, virtualMachines unless set. + ResourceType string + Name string + Tier string + Size string + Family string + Location string + // Zones are the availability zones of Location that offer the SKU. + Zones []string + // Capabilities are the SKU's capabilities by name, such as vCPUs or + // AcceleratedNetworkingEnabled, with values as Azure writes them, such as + // "2" or "True". + Capabilities map[string]string + Restrictions []SKURestriction +} + +// SKURestriction keeps the subscription from using a SKU in its location, or +// in some of the location's zones. +type SKURestriction struct { + // Zones, when set, are the zones the restriction applies to, making it a + // Zone restriction; without them it is a Location restriction. + Zones []string + // ReasonCode is why, QuotaId or NotAvailableForSubscription. + ReasonCode string +} + +// WithResourceSKUs sets the resource SKUs the server lists, in the order +// given. The default lists none. +func WithResourceSKUs(skus ...ResourceSKU) Option { + return func(s *Server) { s.skus = slices.Clone(skus) } +} + +// listSKUs lists the SKUs [WithResourceSKUs] sets, in one location when +// $filter names it, as the only filter Azure takes. +func (s *Server) listSKUs(c *call) (*reply, *apiError) { + location := "" + if f := c.query("$filter"); strings.TrimSpace(f) != "" { + v, rest, err := filterClause(f, "location") + if err != nil || strings.TrimSpace(rest) != "" { + return nil, unsupported("the $filter '%s' is not supported; use location eq 'location'", f) + } + location = normalizeLocation(v) + } + if v := c.query("includeExtendedLocations"); v != "" && v != "true" && v != "false" { + return nil, invalidParameter("includeExtendedLocations", "The value '%s' of parameter 'includeExtendedLocations' is not valid.", v) + } + var items []ResourceSKU + for _, sku := range s.skus { + if location == "" || normalizeLocation(sku.Location) == location { + items = append(items, sku) + } + } + return ok(listBody(items, renderResourceSKU)), nil +} + +func renderResourceSKU(sku ResourceSKU) any { + loc := normalizeLocation(sku.Location) + info := map[string]any{"location": loc} + if len(sku.Zones) > 0 { + info["zones"] = sku.Zones + } + m := map[string]any{ + "resourceType": cmp.Or(sku.ResourceType, "virtualMachines"), + "name": sku.Name, + "locations": []string{loc}, + "locationInfo": []any{info}, + "capabilities": []any{}, + "restrictions": []any{}, + } + for k, v := range map[string]string{"tier": sku.Tier, "size": sku.Size, "family": sku.Family} { + if v != "" { + m[k] = v + } + } + capabilities := make([]any, 0, len(sku.Capabilities)) + for _, name := range slices.Sorted(maps.Keys(sku.Capabilities)) { + capabilities = append(capabilities, map[string]any{"name": name, "value": sku.Capabilities[name]}) + } + m["capabilities"] = capabilities + restrictions := make([]any, 0, len(sku.Restrictions)) + for _, r := range sku.Restrictions { + typ, info := "Location", map[string]any{"locations": []string{loc}} + if len(r.Zones) > 0 { + typ, info["zones"] = "Zone", r.Zones + } + restrictions = append(restrictions, map[string]any{ + "type": typ, "values": []string{loc}, "restrictionInfo": info, "reasonCode": r.ReasonCode, + }) + } + m["restrictions"] = restrictions + return m +} diff --git a/azure/arm/storagecache.go b/azure/arm/storagecache.go index 6d45eb7..5d7f228 100644 --- a/azure/arm/storagecache.go +++ b/azure/arm/storagecache.go @@ -53,7 +53,21 @@ func (s *Server) prepareAmlfs(res *resource, p *parsed) (func(), *apiError) { return s.holdAddress(res, p, subnet, "filesystemSubnet") } -// checkAmlfsSubnets answers that any subnet will do, as subnets are not modeled. +// FailSubnetCheck makes Managed Lustre subnet checks of subnet, a subnet's +// resource ID, fail with message, as Azure answers a subnet it finds unfit +// for a file system. An empty message lets checks of it pass again. +func (s *Server) FailSubnetCheck(subnet, message string) { + s.mu.Lock() + defer s.mu.Unlock() + if message == "" { + delete(s.subnetChecks, key(subnet)) + return + } + s.subnetChecks[key(subnet)] = message +} + +// checkAmlfsSubnets answers that a subnet will do, unless [Server.FailSubnetCheck] +// says otherwise, as subnets' fitness is not modeled. func (s *Server) checkAmlfsSubnets(c *call) (*reply, *apiError) { body, err := readObject(c.r) if err != nil { @@ -62,9 +76,17 @@ func (s *Server) checkAmlfsSubnets(c *call) (*reply, *apiError) { if err := checkMembers(body, "AmlFilesystemSubnetInfo", "", "filesystemSubnet", "location", "sku", "storageCapacityTiB"); err != nil { return nil, err } - if str(body, "filesystemSubnet") == "" { + subnet := str(body, "filesystemSubnet") + if subnet == "" { return nil, unsupported("a subnet check needs filesystemSubnet") } + s.mu.Lock() + defer s.mu.Unlock() + if message, ok := s.subnetChecks[key(subnet)]; ok { + return &reply{status: http.StatusBadRequest, body: encode(map[string]any{ + "filesystemSubnet": map[string]any{"status": "Invalid", "message": message}, + })}, nil + } return &reply{status: http.StatusOK}, nil } diff --git a/azure/arm/vm_update.go b/azure/arm/vm_update.go new file mode 100644 index 0000000..53dbd7d --- /dev/null +++ b/azure/arm/vm_update.go @@ -0,0 +1,91 @@ +package arm + +import ( + "maps" + "net/http" + "slices" + "strings" +) + +var storageProfileMembers = []string{"alignRegionalDisksToVMZone", "dataDisks", "diskControllerType", "imageReference", "osDisk"} + +func (s *Server) patchVM(c *call) (*reply, *apiError) { + body, err := readObject(c.r) + if err != nil { + return nil, err + } + if err := checkMembers(body, "VirtualMachineUpdate", "", "identity", "plan", "properties", "tags", "zones"); err != nil { + return nil, err + } + for _, k := range []string{"identity", "plan", "zones"} { + if body[k] != nil { + return nil, unsupported("updating %s with PATCH is not supported; use PUT", k) + } + } + props, err := object(body, "properties") + if err != nil { + return nil, err + } + if err := checkMembers(props, "VirtualMachineProperties", "properties", slices.Concat(vmKind.props, vmKind.readOnly)...); err != nil { + return nil, err + } + for _, k := range slices.Sorted(maps.Keys(props)) { + if props[k] != nil && k != "storageProfile" && !slices.Contains(vmKind.readOnly, k) { + return nil, unsupported("updating properties.%s with PATCH is not supported; use PUT", k) + } + } + sp, err := object(props, "storageProfile") + if err != nil { + return nil, err + } + if err := checkMembers(sp, "StorageProfile", "properties.storageProfile", storageProfileMembers...); err != nil { + return nil, err + } + osDisk, err := object(sp, "osDisk") + if err != nil { + return nil, err + } + _, hasTags := body["tags"] + tags, err := tagsOf(body) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if err := s.writableGroup(c); err != nil { + return nil, err + } + res, err := s.claim(vmID(c), "Update VM") + if err != nil { + return nil, err + } + if res == nil { + return nil, resourceNotFound(vmKind.typ, c.val("name"), c.val("rg")) + } + if err := checkPrecondition(c.r, res); err != nil { + return nil, err + } + if name := str(osDisk, "name"); name != "" && !strings.EqualFold(name, str(osDiskOf(res), "name")) { + return nil, changeNotAllowed("osDisk.name") + } + plan := &dataDiskPlan{kept: recordedDataDisks(res)} + if _, ok := sp["dataDisks"]; ok { + if plan, err = s.planDataDisks(res, res.id, props); err != nil { + return nil, err + } + } + render := func() []byte { return encode(s.renderVM(res, "")) } + paths := computeOps(c, res.loc) + if c.opFault != nil { + op := s.begin(c, paths, 0, nil) + return accepted(c, op, http.StatusOK, http.StatusOK, false, func() []byte { return withState(res, stateUpdating, render) }), nil + } + if hasTags { + res.tags = tags + } + s.applyDataDisks(res, plan) + s.touch(res) + res.modified = s.now() + op := s.change(c, res, paths, 0, stateUpdating, nil) + return accepted(c, op, http.StatusOK, http.StatusOK, false, render), nil +} diff --git a/azure/arm/vms.go b/azure/arm/vms.go index 6c4d301..efa053d 100644 --- a/azure/arm/vms.go +++ b/azure/arm/vms.go @@ -1,6 +1,7 @@ package arm import ( + "bytes" "cmp" "maps" "net/http" @@ -30,13 +31,18 @@ const ( powerDeallocated = "deallocated" powerStarting = "starting" powerDeallocating = "deallocating" + powerStopped = "stopped" + powerStopping = "stopping" ) type vmState struct { - power string - userData any - nics []vmNIC - changed time.Time + power string + userData any + customData string + nics []vmNIC + changed time.Time + // failure is the error the VM's creation ended in, if it failed. + failure *apiError } type vmNIC struct { @@ -60,6 +66,9 @@ type vmBody struct { osDisk map[string]any osName string userData any + // customData is the osProfile's customData, which a GET leaves out, when the body sets it. + customData string + hasCustomData bool } func parseVM(c *call) (*vmBody, *apiError) { @@ -144,6 +153,7 @@ func parseVM(c *call) (*vmBody, *apiError) { return nil, err } if os != nil { + b.customData, b.hasCustomData = os["customData"].(string) delete(os, "adminPassword") delete(os, "customData") } @@ -217,17 +227,28 @@ func (s *Server) putVM(c *call) (*reply, *apiError) { return nil, diskAttached(d.name, d.disk.vm) } } + disks, err := s.planDataDisks(existing, id, b.props) + if err != nil { + return nil, err + } render := func() []byte { return encode(s.renderVM(res, "")) } paths := computeOps(c, b.location) if c.opFault != nil { op := s.begin(c, paths, 0, nil) - if status == http.StatusCreated { - s.fillVM(res, b) + if status != http.StatusCreated { + return accepted(c, op, status, status, false, func() []byte { return withState(res, putState(status), render) }), nil } - return accepted(c, op, status, status, false, func() []byte { return withState(res, putState(status), render) }), nil + s.applyVM(res, b) + s.resources[key(id)] = res + res.state, res.vm.power, res.vm.failure, res.vm.changed = stateFailed, "", op.err, s.now() + return accepted(c, op, status, status, false, func() []byte { return withState(res, stateCreating, render) }), nil } s.applyVM(res, b) + s.applyDataDisks(res, disks) s.resources[key(id)] = res + if res.vm.failure != nil { + res.vm.power, res.vm.failure = powerStarting, nil + } op := s.change(c, res, paths, 0, putState(status), func() { if res.vm.power == powerStarting { res.vm.power, res.vm.changed = powerRunning, s.now() @@ -252,9 +273,25 @@ func (s *Server) checkVMUpdate(res *resource, b *vmBody) *apiError { if name := str(newOS, "computerName"); name != "" && oldOS != nil && !strings.EqualFold(name, str(oldOS, "computerName")) { return changeNotAllowed("computerName") } + if b.hasCustomData && b.customData != res.vm.customData { + return changeNotAllowed("customData") + } + if keys, ok := sshKeys(newOS); ok { + if old, _ := sshKeys(oldOS); !bytes.Equal(encode(keys), encode(old)) { + return changeNotAllowed("linuxConfiguration.ssh.publicKeys") + } + } return nil } +// sshKeys returns the SSH public keys of a Linux osProfile, and whether it sets them. +func sshKeys(os map[string]any) (any, bool) { + linux, _ := os["linuxConfiguration"].(map[string]any) + ssh, _ := linux["ssh"].(map[string]any) + keys, ok := ssh["publicKeys"] + return keys, ok && keys != nil +} + // fillVM completes b with what Azure assigns a new VM: the OS disk's name, ID // and type, and the computer name. The caller holds s.mu. func (s *Server) fillVM(res *resource, b *vmBody) { @@ -333,6 +370,9 @@ func (s *Server) applyVM(res *resource, b *vmBody) { } s.detachNICs(res, false) res.vm.nics, res.vm.userData = b.nics, b.userData + if b.hasCustomData { + res.vm.customData = b.customData + } for _, n := range b.nics { s.resources[key(n.id)].nic.vm = res.id } @@ -403,6 +443,12 @@ func statuses(state, power string, at time.Time) []any { } func (s *Server) instanceView(res *resource) map[string]any { + if f := res.vm.failure; f != nil && res.state == stateFailed { + return map[string]any{"statuses": []any{map[string]any{ + "code": "ProvisioningState/failed/" + f.Code, "level": "Error", + "displayStatus": "Provisioning failed", "message": f.Message, "time": timestamp(res.vm.changed), + }}} + } view := map[string]any{"statuses": statuses(res.state, res.vm.power, res.vm.changed)} if os, _ := object(res.props, "osProfile"); os != nil { view["computerName"] = str(os, "computerName") @@ -474,16 +520,22 @@ func (s *Server) listVMs(c *call) (*reply, *apiError) { return ok(listBody(s.listed(c, vmKind), func(res *resource) any { return s.renderVM(res, expand) })), nil } -// powerVM deallocates or starts a VM. +// powerVM deallocates, powers off or starts a VM. func (s *Server) powerVM(target string) handler { transition, verb := powerStarting, "start" - if target == powerDeallocated { + switch target { + case powerDeallocated: transition, verb = powerDeallocating, "deallocate" + case powerStopped: + transition, verb = powerStopping, "powerOff" } return func(c *call) (*reply, *apiError) { if c.query("hibernate") == "true" { return nil, unsupported("hibernation is not supported") } + if v := c.query("skipShutdown"); v != "" && v != "true" && v != "false" { + return nil, invalidParameter("skipShutdown", "The value '%s' of parameter 'skipShutdown' is not valid.", v) + } s.mu.Lock() defer s.mu.Unlock() if err := s.writableGroup(c); err != nil { @@ -498,7 +550,9 @@ func (s *Server) powerVM(target string) handler { } op := s.change(c, res, computeOps(c, res.loc), http.StatusNoContent, stateUpdating, func() { res.vm.power, res.vm.changed = target, s.now() - s.powerChanged(res) + if target != powerStopped { + s.powerChanged(res) + } }) if op.status == opInProgress { res.vm.power, res.vm.changed = transition, s.now() diff --git a/azure/graph/server.go b/azure/graph/server.go index 8105df4..b4c501c 100644 --- a/azure/graph/server.go +++ b/azure/graph/server.go @@ -49,7 +49,10 @@ // Microsoft Entra documents, whichever domain is the default; that it is // the first such domain [WithDomains] sets is inferred. // - The organization is the one [WithOrganization] describes, with the -// verified domains [WithDomains] sets. It shows the members Graph's +// verified domains [WithDomains] sets. A tenant lists exactly one +// organization, as Graph lists it. Its countryLetterCode and +// defaultUsageLocation may be null, as Graph allows, for a tenant set up +// without them; country, state and city are always null. It shows the members Graph's // example of the call shows, with empty plans and notification lists; // each verified domain's capabilities, "Email, OfficeCommunicationsOnline" // as in that example, and type Managed are inferred. @@ -131,6 +134,12 @@ type Organization struct { CountryLetterCode string // DefaultUsageLocation is the usage location new users get, such as US. DefaultUsageLocation string + // NoCountry leaves the tenant without a country, so countryLetterCode is + // null, as Graph shows a tenant that never set one. + NoCountry bool + // NoDefaultUsageLocation leaves the tenant without a default usage + // location, so defaultUsageLocation is null. + NoDefaultUsageLocation bool } // Server is a stand-in for Microsoft Graph. Create one with [New]. It is @@ -178,13 +187,15 @@ func WithDomains(domains ...Domain) Option { // WithOrganization sets the directory's organization. A field left empty // keeps its default: the tenant ID 00000000-0000-0000-0000-000000000001, the -// display name Squall, and US as the country and default usage location. +// display name Squall, and US as the country and default usage location; +// NoCountry and NoDefaultUsageLocation leave those out instead. func WithOrganization(org Organization) Option { return func(s *Server) { s.org = Organization{ ID: cmp.Or(org.ID, s.org.ID), DisplayName: cmp.Or(org.DisplayName, s.org.DisplayName), CountryLetterCode: cmp.Or(org.CountryLetterCode, s.org.CountryLetterCode), DefaultUsageLocation: cmp.Or(org.DefaultUsageLocation, s.org.DefaultUsageLocation), + NoCountry: org.NoCountry, NoDefaultUsageLocation: org.NoDefaultUsageLocation, } } } @@ -501,10 +512,17 @@ func (s *Server) listOrganization(c *call) (*reply, *apiError) { }) } } + var country, usageLocation any = s.org.CountryLetterCode, s.org.DefaultUsageLocation + if s.org.NoCountry { + country = nil + } + if s.org.NoDefaultUsageLocation { + usageLocation = nil + } org := map[string]any{ "id": s.org.ID, "deletedDateTime": nil, "businessPhones": []string{}, "city": nil, "country": nil, - "countryLetterCode": s.org.CountryLetterCode, "createdDateTime": s.created.UTC().Format(time.RFC3339), - "defaultUsageLocation": s.org.DefaultUsageLocation, "displayName": s.org.DisplayName, + "countryLetterCode": country, "createdDateTime": s.created.UTC().Format(time.RFC3339), + "defaultUsageLocation": usageLocation, "displayName": s.org.DisplayName, "isMultipleDataLocationsForServicesEnabled": nil, "marketingNotificationEmails": []string{}, "onPremisesLastSyncDateTime": nil, "onPremisesSyncEnabled": nil, "postalCode": nil, "preferredLanguage": "en", "securityComplianceNotificationMails": []string{}, "securityComplianceNotificationPhones": []string{}, "state": nil, "street": nil, "technicalNotificationMails": []string{}, @@ -588,7 +606,7 @@ func faultError(f fault.Fault) *apiError { if code == "" || code == "backendError" || code == "rateLimitExceeded" { code = cmp.Or(strings.ReplaceAll(http.StatusText(status), " ", ""), "InternalServerError") } - return &apiError{Status: status, Code: code, Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Code: code, Message: f.ErrorMessage()} } func writeError(w http.ResponseWriter, e *apiError) { diff --git a/fault/fault.go b/fault/fault.go index 91234c6..bea1174 100644 --- a/fault/fault.go +++ b/fault/fault.go @@ -70,10 +70,28 @@ type Fault struct { Status int // Reason is the machine-readable error reason, such as "backendError". Reason string + // Message, when set, is the error's human-readable message, so a fault can + // carry the wording of a specific failure that the caller tells apart. + Message string // Delay is how long the server waits before it handles the call. Delay time.Duration } +// WithMessage returns f with its error message set to message. +func (f Fault) WithMessage(message string) Fault { + f.Message = message + return f +} + +// ErrorMessage is the message of the error f answers with: its Message, or +// one that says the fault was injected. +func (f Fault) ErrorMessage() string { + if f.Message != "" { + return f.Message + } + return fmt.Sprintf("squall: injected fault (%s)", f) +} + func (f Fault) String() string { var b strings.Builder b.WriteString(f.Mode.String()) @@ -83,6 +101,9 @@ func (f Fault) String() string { if f.Reason != "" { fmt.Fprintf(&b, " %s", f.Reason) } + if f.Message != "" { + fmt.Fprintf(&b, " %q", f.Message) + } if f.Delay > 0 { fmt.Fprintf(&b, " after %s", f.Delay) } diff --git a/fault/fault_test.go b/fault/fault_test.go index 35184eb..6562f36 100644 --- a/fault/fault_test.go +++ b/fault/fault_test.go @@ -172,3 +172,15 @@ func TestFaultString(t *testing.T) { } } } + +func TestErrorMessage(t *testing.T) { + if got, want := fault.Unavailable().WithMessage("try later").ErrorMessage(), "try later"; got != want { + t.Fatalf("ErrorMessage = %q, want %q", got, want) + } + if got, want := fault.Unavailable().ErrorMessage(), "squall: injected fault (reject 503 backendError)"; got != want { + t.Fatalf("ErrorMessage = %q, want %q", got, want) + } + if got, want := fault.Reject(http.StatusConflict, "alreadyExists").WithMessage("taken").String(), `reject 409 alreadyExists "taken"`; got != want { + t.Fatalf("String = %q, want %q", got, want) + } +} diff --git a/gcp/bigquery/errors.go b/gcp/bigquery/errors.go index c54e049..c2f513c 100644 --- a/gcp/bigquery/errors.go +++ b/gcp/bigquery/errors.go @@ -66,7 +66,7 @@ func notEnabled(project string) *apiError { } func faultError(f fault.Fault) *apiError { - return &apiError{Status: cmp.Or(f.Status, http.StatusServiceUnavailable), Reason: cmp.Or(f.Reason, "backendError"), Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: cmp.Or(f.Status, http.StatusServiceUnavailable), Reason: cmp.Or(f.Reason, "backendError"), Message: f.ErrorMessage()} } // rpcNames follow Google's HTTP mapping of google.rpc.Code. diff --git a/gcp/compute/accelerators.go b/gcp/compute/accelerators.go new file mode 100644 index 0000000..7843ed2 --- /dev/null +++ b/gcp/compute/accelerators.go @@ -0,0 +1,117 @@ +package compute + +import ( + "net/http" + "slices" + "strconv" +) + +// AcceleratorType is an accelerator a zone offers, in the API's JSON shape. +type AcceleratorType struct { + Kind string `json:"kind"` + ID uint64 `json:"id,string"` + CreationTimestamp string `json:"creationTimestamp"` + Name string `json:"name"` + Description string `json:"description"` + Zone string `json:"zone"` + SelfLink string `json:"selfLink"` + MaximumCardsPerInstance int `json:"maximumCardsPerInstance"` +} + +// defaultAccelerators are what a zone offers unless [WithAcceleratorTypes] says otherwise. +var defaultAccelerators = []string{"nvidia-l4", "nvidia-tesla-t4"} + +var knownAccelerators = map[string]struct { + description string + maxCards int +}{ + "nvidia-a100-80gb": {"NVIDIA A100 80GB", 8}, + "nvidia-h100-80gb": {"NVIDIA H100 80GB", 8}, + "nvidia-l4": {"NVIDIA L4", 8}, + "nvidia-tesla-a100": {"NVIDIA A100 40GB", 16}, + "nvidia-tesla-p100": {"NVIDIA Tesla P100", 4}, + "nvidia-tesla-p4": {"NVIDIA Tesla P4", 4}, + "nvidia-tesla-t4": {"NVIDIA T4", 4}, + "nvidia-tesla-v100": {"NVIDIA V100", 8}, +} + +// WithAcceleratorTypes sets the accelerator types zone offers, such as +// "nvidia-tesla-t4", in place of the built-in ones, nvidia-l4 and +// nvidia-tesla-t4. With no names the zone offers none. +func WithAcceleratorTypes(zone string, names ...string) Option { + return func(s *Server) { s.accelerators[zone] = slices.Clone(names) } +} + +var acceleratorFields = fieldSet{names: []string{"name", "description", "id", "zone"}} + +func (a *AcceleratorType) filterValue(field string) string { + switch field { + case "name": + return a.Name + case "description": + return a.Description + case "id": + return strconv.FormatUint(a.ID, 10) + case "zone": + return a.Zone + } + return "" +} + +// acceleratorTypes returns the accelerator types zone offers, in project. +func (s *Server) acceleratorTypes(project, zone string) *collection[*AcceleratorType] { + names, ok := s.accelerators[zone] + if !ok { + names = defaultAccelerators + } + c := &collection[*AcceleratorType]{byName: map[string]*AcceleratorType{}} + zoneLink := selfLinkBase + "projects/" + project + "/zones/" + zone + for i, name := range names { + known, ok := knownAccelerators[name] + if !ok { + known.description, known.maxCards = name, 8 + } + c.put(name, &AcceleratorType{ + Kind: "compute#acceleratorType", + ID: s.zoneIDs[zone]*1000 + uint64(i) + 1, + CreationTimestamp: "1969-12-31T16:00:00.000-08:00", + Name: name, + Description: known.description, + Zone: zoneLink, + SelfLink: zoneLink + "/acceleratorTypes/" + name, + MaximumCardsPerInstance: known.maxCards, + }) + } + return c +} + +func (s *Server) listAcceleratorTypes(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, acceleratorFields) + if err != nil { + return nil, err + } + project, zone := r.PathValue("project"), r.PathValue("zone") + return listScope(s.acceleratorTypes(project, zone), q, "compute#acceleratorTypeList", scopeOf(r)+"/acceleratorTypes", nil), nil +} + +func (s *Server) aggregatedAcceleratorTypes(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, acceleratorFields) + if err != nil { + return nil, err + } + project := r.PathValue("project") + byZone := map[string]*collection[*AcceleratorType]{} + for zone := range s.zoneRegion { + byZone["projects/"+project+"/zones/"+zone] = s.acceleratorTypes(project, zone) + } + return listAggregated(byZone, project, q, "compute#acceleratorTypeAggregatedList", "acceleratorTypes", nil), nil +} + +func (s *Server) getAcceleratorType(r *http.Request, _ *apiError) (any, *apiError) { + project, zone, name := r.PathValue("project"), r.PathValue("zone"), r.PathValue("name") + a, ok := s.acceleratorTypes(project, zone).byName[name] + if !ok { + return nil, notFound(scopeOf(r) + "/acceleratorTypes/" + name) + } + return a, nil +} diff --git a/gcp/compute/disks.go b/gcp/compute/disks.go index 095e7b1..b60f729 100644 --- a/gcp/compute/disks.go +++ b/gcp/compute/disks.go @@ -13,6 +13,7 @@ const ( diskCreating = "CREATING" diskReady = "READY" diskDeleting = "DELETING" + diskFailed = "FAILED" ) // Disk is a zonal persistent disk, in the API's JSON shape. @@ -259,6 +260,34 @@ func (s *Server) LookupDisk(project, zone, name string) (Disk, bool) { return jsonClone(d), true } +// PutDisk stores d in project and zone as if it had been inserted, and +// returns it as stored. Its status is READY, or FAILED for a disk whose +// creation failed, which Compute Engine keeps until it is deleted: it cannot +// be attached or snapshotted. Use it to set up such state. It fills in what an +// insert does and fails as an insert would, for a name already taken too. +func (s *Server) PutDisk(project, zone string, d Disk) (Disk, error) { + status := cmp.Or(d.Status, diskReady) + if status != diskReady && status != diskFailed { + return Disk{}, invalid("Invalid value for field 'resource.status': '%s'. Must be READY or FAILED.", d.Status) + } + if _, ok := s.zoneRegion[zone]; !ok { + return Disk{}, invalid("Invalid value for field 'zone': '%s'. Unknown zone.", zone) + } + scope := "projects/" + project + "/zones/" + zone + s.mu.Lock() + defer s.mu.Unlock() + stored, err := s.newDisk(scope, "resource", d) + if err != nil { + return Disk{}, err + } + if _, ok := lookupIn(s.disks, scope, stored.Name); ok { + return Disk{}, alreadyExists(diskPath(scope, stored.Name)) + } + stored.Status = status + scoped(s.disks, scope).put(stored.Name, stored) + return jsonClone(stored), nil +} + // release takes user off d's users. The caller holds s.mu. func (d *Disk) release(user string, now string) { if i := slices.Index(d.Users, user); i >= 0 { diff --git a/gcp/compute/errors.go b/gcp/compute/errors.go index 2d3968f..7236ae4 100644 --- a/gcp/compute/errors.go +++ b/gcp/compute/errors.go @@ -16,7 +16,7 @@ type apiError struct { Reason string Message string // opErrors, when set, are the errors an operation that ends in this one lists. - opErrors []operationError + opErrors []OperationError } func (e *apiError) Error() string { return fmt.Sprintf("%d %s: %s", e.Status, e.Reason, e.Message) } @@ -48,7 +48,7 @@ func invalid(format string, args ...any) *apiError { func faultError(f fault.Fault) *apiError { status := cmp.Or(f.Status, http.StatusServiceUnavailable) - return &apiError{Status: status, Reason: cmp.Or(f.Reason, "backendError"), Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Reason: cmp.Or(f.Reason, "backendError"), Message: f.ErrorMessage()} } type errorBody struct { diff --git a/gcp/compute/groups.go b/gcp/compute/groups.go new file mode 100644 index 0000000..1181a2d --- /dev/null +++ b/gcp/compute/groups.go @@ -0,0 +1,739 @@ +package compute + +import ( + "cmp" + "encoding/json" + "fmt" + "hash/fnv" + "net/http" + "slices" + "strconv" + "strings" + + "github.com/parallelworks/squall/internal/reason" +) + +const ( + actionNone = "NONE" + actionCreating = "CREATING" + actionDeleting = "DELETING" + + maxGroupInstances = 1000 + maxBaseNameLength = 58 +) + +// InstanceGroupManager is a zonal managed instance group, in the API's JSON +// shape. Policies the server only records, such as instanceLifecyclePolicy, +// keep the JSON the caller sent. +type InstanceGroupManager struct { + Kind string `json:"kind"` + ID uint64 `json:"id,string"` + CreationTimestamp string `json:"creationTimestamp"` + Name string `json:"name"` + Description string `json:"description,omitzero"` + Zone string `json:"zone"` + InstanceTemplate string `json:"instanceTemplate"` + InstanceGroup string `json:"instanceGroup"` + BaseInstanceName string `json:"baseInstanceName"` + Fingerprint string `json:"fingerprint"` + CurrentActions CurrentActions `json:"currentActions"` + Status GroupStatus `json:"status"` + TargetSize int `json:"targetSize"` + ListManagedInstancesResults string `json:"listManagedInstancesResults"` + SelfLink string `json:"selfLink"` + InstanceLifecyclePolicy json.RawMessage `json:"instanceLifecyclePolicy,omitzero"` + ResourcePolicies json.RawMessage `json:"resourcePolicies,omitzero"` + UpdatePolicy json.RawMessage `json:"updatePolicy,omitzero"` + TargetSizePolicy json.RawMessage `json:"targetSizePolicy,omitzero"` + NamedPorts json.RawMessage `json:"namedPorts,omitzero"` + + zone string + members *collection[*member] + requests *collection[*ResizeRequest] + op *operation +} + +// CurrentActions counts a group's instances by what the group is doing to them. +type CurrentActions struct { + Abandoning int `json:"abandoning"` + Creating int `json:"creating"` + CreatingWithoutRetries int `json:"creatingWithoutRetries"` + Deleting int `json:"deleting"` + None int `json:"none"` + Recreating int `json:"recreating"` + Refreshing int `json:"refreshing"` + Restarting int `json:"restarting"` + Resuming int `json:"resuming"` + Starting int `json:"starting"` + Stopping int `json:"stopping"` + Suspending int `json:"suspending"` + Verifying int `json:"verifying"` +} + +// GroupStatus is a group's status. +type GroupStatus struct { + IsStable bool `json:"isStable"` +} + +// ManagedInstance is one of a group's instances, as listManagedInstances +// reports it. Instance and InstanceStatus are empty while the group cannot +// create the instance; LastAttempt then says why. +type ManagedInstance struct { + Name string `json:"name"` + Instance string `json:"instance,omitzero"` + ID uint64 `json:"id,string,omitzero"` + InstanceStatus string `json:"instanceStatus,omitzero"` + CurrentAction string `json:"currentAction"` + Version ManagedInstanceVersion `json:"version"` + LastAttempt *ManagedInstanceErrors `json:"lastAttempt,omitzero"` +} + +// ManagedInstanceVersion is the template a managed instance was created from. +type ManagedInstanceVersion struct { + InstanceTemplate string `json:"instanceTemplate"` +} + +// ManagedInstanceErrors are the errors of the group's last attempt at an instance. +type ManagedInstanceErrors struct { + Errors OperationErrors `json:"errors"` +} + +// member is one of a group's instances: the instance, once the group has +// created it, or the error that keeps it from doing so. +type member struct { + name string + template string + inst *Instance + failed *apiError + deleting bool +} + +func (m *member) filterValue(field string) string { + if field == "name" { + return m.name + } + return "" +} + +var groupFields = fieldSet{names: []string{"name", "description", "id"}} + +func (g *InstanceGroupManager) filterValue(field string) string { + switch field { + case "name": + return g.Name + case "description": + return g.Description + case "id": + return strconv.FormatUint(g.ID, 10) + } + return "" +} + +func groupPath(zone, name string) string { return zone + "/instanceGroupManagers/" + name } + +// templateLink resolves ref, a template's name or URL, to the selfLink of a +// template project holds. field names ref in errors. The caller holds s.mu. +func (s *Server) templateLink(project, field, ref string) (string, *apiError) { + path := ref + if !strings.Contains(ref, "/") { + path = "global/instanceTemplates/" + ref + } + global, name, ok := strings.Cut(relPath(path, project), "/instanceTemplates/") + if !ok || !strings.HasSuffix(global, "/global") || !validName(name) { + return "", invalid("Invalid value for field '%s': '%s'. The URL is malformed.", field, ref) + } + if _, ok := lookupIn(s.templates, global, name); !ok { + return "", missingRef(field, ref, "instanceTemplate") + } + return selfLinkBase + templatePath(global, name), nil +} + +// groupUsing returns the path of a group whose template is link, or "". The +// caller holds s.mu. +func (s *Server) groupUsing(link string) string { + var user string + each(s.groups, func(g *InstanceGroupManager) { + if user == "" && g.InstanceTemplate == link { + user = strings.TrimPrefix(g.SelfLink, selfLinkBase) + } + }) + return user +} + +// regionOf is the region path of zone, a path such as "projects/p/zones/z". +func (s *Server) regionOf(zone string) string { + return "projects/" + projectOf(zone) + "/regions/" + s.zoneRegion[zone[strings.LastIndexByte(zone, '/')+1:]] +} + +// buildMember builds the instance name in g's zone from g's template, with +// the disks and addresses it takes. The caller holds s.mu. +func (s *Server) buildMember(g *InstanceGroupManager, name string) (*Instance, []*Disk, []claim, *apiError) { + global, tmplName, _ := strings.Cut(strings.TrimPrefix(g.InstanceTemplate, selfLinkBase), "/instanceTemplates/") + t, ok := lookupIn(s.templates, global, tmplName) + if !ok { + return nil, nil, nil, missingRef("instanceTemplate", g.InstanceTemplate, "instanceTemplate") + } + var props Instance + if err := unmarshalStrict(t.Properties, &props); err != nil { + return nil, nil, nil, err + } + items := slices.Clone(props.Metadata.Items) + for _, item := range []MetadataItem{ + {"instance-template", strings.TrimPrefix(g.InstanceTemplate, selfLinkBase)}, + {"created-by", strings.TrimPrefix(g.SelfLink, selfLinkBase)}, + } { + if !slices.ContainsFunc(items, func(m MetadataItem) bool { return m.Key == item.Key }) { + items = append(items, item) + } + } + props.Metadata.Items = items + inst, disks, claims, err := s.newInstance(g.zone, s.regionOf(g.zone), name, "instanceTemplate.properties", props, true) + if err != nil { + return nil, nil, nil, err + } + if _, ok := lookupIn(s.instances, g.zone, name); ok { + return nil, nil, nil, alreadyExists(instancePath(g.zone, name)) + } + for _, d := range disks { + if _, ok := lookupIn(s.disks, g.zone, d.Name); ok { + return nil, nil, nil, alreadyExists(diskPath(g.zone, d.Name)) + } + } + return inst, disks, claims, nil +} + +// addMembers adds a member to g for each name and creates its instance. A +// name whose instance cannot be created stays a member whose last attempt +// failed, as the group keeps trying. The instances run once op, a change +// made in the background, finishes. The caller holds s.mu. +func (s *Server) addMembers(g *InstanceGroupManager, names []string) { + var insts []*Instance + var disks []*Disk + for _, name := range names { + m := &member{name: name, template: g.InstanceTemplate} + inst, d, c, err := s.buildMember(g, name) + if err != nil { + m.failed = err + } else { + s.storeInstance(g.zone, s.regionOf(g.zone), inst, d, c) + m.inst = inst + insts, disks = append(insts, inst), append(disks, d...) + } + g.members.put(name, m) + } + if len(insts) > 0 { + track(s.inBackground(s.provisioned(insts, disks)), insts, disks, true) + } +} + +// inBackground applies complete as a change the API makes after the call +// that asked for it is done, such as a group creating an instance: at once, +// or after the reads [WithSettleAfter] sets. The operation it returns is +// never listed. The caller holds s.mu. +func (s *Server) inBackground(complete func()) *operation { + op := &operation{} + if s.settleAfter == 0 { + complete() + return op + } + op.complete, op.wait = complete, max(s.settleAfter, 0) + s.pending[op] = struct{}{} + return op +} + +// holds reports whether inst, which may be nil, is still in zone. The caller holds s.mu. +func (s *Server) holds(zone string, inst *Instance) bool { + if inst == nil { + return false + } + cur, ok := lookupIn(s.instances, zone, inst.Name) + return ok && cur == inst +} + +// releaseMember deletes m's instance, and then m. The caller holds s.mu. +func (s *Server) releaseMember(g *InstanceGroupManager, m *member) { + if m.inst != nil { + s.finish(m.inst.op) + } + if !s.holds(g.zone, m.inst) { + g.members.remove(m.name) + return + } + m.deleting = true + inst := m.inst + inst.Status = statusStopping + track(s.inBackground(func() { + s.removeInstance(g.zone, inst) + if cur, ok := g.members.byName[m.name]; ok && cur == m { + g.members.remove(m.name) + } + }), []*Instance{inst}, nil, false) +} + +// refresh drops the members whose instance went away other than through g, +// and counts what g is doing. The caller holds s.mu. +func (s *Server) refresh(g *InstanceGroupManager) { + for _, name := range slices.Clone(g.members.names) { + if m := g.members.byName[name]; m.inst != nil && !s.holds(g.zone, m.inst) { + g.members.remove(name) + } + } + g.TargetSize = len(g.members.names) + g.CurrentActions = CurrentActions{} + for _, name := range g.members.names { + switch memberAction(g.members.byName[name]) { + case actionCreating: + g.CurrentActions.Creating++ + case actionDeleting: + g.CurrentActions.Deleting++ + default: + g.CurrentActions.None++ + } + } + g.Status.IsStable = g.CurrentActions.None == g.TargetSize && g.op == nil +} + +func memberAction(m *member) string { + switch { + case m.deleting: + return actionDeleting + case m.inst == nil, m.inst.op != nil && (m.inst.Status == statusProvisioning || m.inst.Status == statusStaging): + return actionCreating + } + return actionNone +} + +func (m *member) view() ManagedInstance { + v := ManagedInstance{Name: m.name, CurrentAction: memberAction(m), Version: ManagedInstanceVersion{m.template}} + if m.inst != nil { + v.Instance, v.ID, v.InstanceStatus = m.inst.SelfLink, m.inst.ID, m.inst.Status + } + if m.failed != nil { + v.LastAttempt = &ManagedInstanceErrors{OperationErrors{[]OperationError{{reason.UpperSnake(m.failed.Reason), m.failed.Message}}}} + } + return v +} + +// memberName returns a name for a new instance of g that no instance or +// member has: its base instance name and four characters. The caller holds s.mu. +func (s *Server) memberName(g *InstanceGroupManager, taken []string) string { + const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789" + for { + h := fnv.New32a() + fmt.Fprint(h, s.newID()) + n := h.Sum32() + suffix := make([]byte, 4) + for i := range suffix { + suffix[i], n = alphabet[n%uint32(len(alphabet))], n/uint32(len(alphabet)) + } + name := g.BaseInstanceName + "-" + string(suffix) + if !g.members.has(name) && !slices.Contains(taken, name) { + if _, ok := lookupIn(s.instances, g.zone, name); !ok { + return name + } + } + } +} + +// lookupGroup returns the group r names, by its path value key. The caller holds s.mu. +func (s *Server) lookupGroup(r *http.Request, key string) (*InstanceGroupManager, *apiError) { + zone, name := scopeOf(r), r.PathValue(key) + g, ok := lookupIn(s.groups, zone, name) + if !ok { + return nil, notFound(groupPath(zone, name)) + } + return g, nil +} + +func (s *Server) insertGroupManager(r *http.Request, opFault *apiError) (any, *apiError) { + var want InstanceGroupManager + if err := decodeStrict(r, &want); err != nil { + return nil, err + } + if !validName(want.Name) { + return nil, invalid("Invalid value for field 'resource.name': '%s'. Must be a match of regex '(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'", want.Name) + } + want.BaseInstanceName = cmp.Or(want.BaseInstanceName, want.Name) + if !validName(want.BaseInstanceName) || len(want.BaseInstanceName) > maxBaseNameLength { + return nil, invalid("Invalid value for field 'resource.baseInstanceName': '%s'. Must be a match of regex '[a-z](([-a-z0-9]{0,57})|([-a-z0-9]{0,51}[0-9]{0,6}))'", want.BaseInstanceName) + } + if want.TargetSize < 0 || want.TargetSize > maxGroupInstances { + return nil, invalid("Invalid value for field 'resource.targetSize': '%d'. Must be between 0 and %d.", want.TargetSize, maxGroupInstances) + } + mode := cmp.Or(want.ListManagedInstancesResults, "PAGELESS") + if mode != "PAGELESS" && mode != "PAGINATED" { + return nil, invalid("Invalid value for field 'resource.listManagedInstancesResults': '%s'.", mode) + } + if want.InstanceTemplate == "" { + return nil, invalid("Invalid value for field 'resource.instanceTemplate': ''. An instance template is required.") + } + reqID, err := requestID(r) + if err != nil { + return nil, err + } + zone := scopeOf(r) + path := groupPath(zone, want.Name) + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + template, err := s.templateLink(projectOf(zone), "resource.instanceTemplate", want.InstanceTemplate) + if err != nil { + return nil, err + } + if _, ok := lookupIn(s.groups, zone, want.Name); ok { + return nil, alreadyExists(path) + } + if opFault != nil { + return encoded(s.startOperation(r, reqID, "insert", path, 0, opFault, nil)), nil + } + g := &InstanceGroupManager{ + Kind: "compute#instanceGroupManager", ID: s.newID(), CreationTimestamp: timestamp(s.now()), + Name: want.Name, Description: want.Description, Zone: selfLinkBase + zone, InstanceTemplate: template, + InstanceGroup: selfLinkBase + zone + "/instanceGroups/" + want.Name, BaseInstanceName: want.BaseInstanceName, + ListManagedInstancesResults: mode, SelfLink: selfLinkBase + path, + InstanceLifecyclePolicy: want.InstanceLifecyclePolicy, ResourcePolicies: want.ResourcePolicies, + UpdatePolicy: want.UpdatePolicy, TargetSizePolicy: want.TargetSizePolicy, NamedPorts: want.NamedPorts, + zone: zone, + members: &collection[*member]{byName: map[string]*member{}}, + requests: &collection[*ResizeRequest]{byName: map[string]*ResizeRequest{}}, + } + g.Fingerprint = hash([]any{g.ID, g.InstanceTemplate}) + scoped(s.groups, zone).put(g.Name, g) + var names []string + for range want.TargetSize { + names = append(names, s.memberName(g, names)) + } + s.addMembers(g, names) + s.refresh(g) + return encoded(s.startOperation(r, reqID, "insert", path, g.ID, nil, nil)), nil +} + +func (s *Server) getGroupManager(r *http.Request, _ *apiError) (any, *apiError) { + s.mu.Lock() + defer s.mu.Unlock() + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + if s.observe(g.op); !s.groups[g.zone].has(g.Name) { + return nil, notFound(groupPath(g.zone, g.Name)) + } + s.refresh(g) + return encoded(g), nil +} + +func (s *Server) listGroupManagers(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, groupFields) + if err != nil { + return nil, err + } + zone := scopeOf(r) + s.mu.Lock() + defer s.mu.Unlock() + return listScope(s.groups[zone], q, "compute#instanceGroupManagerList", zone+"/instanceGroupManagers", s.groupSeen()), nil +} + +func (s *Server) aggregatedGroupManagers(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, groupFields) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + return listAggregated(s.groups, r.PathValue("project"), q, + "compute#instanceGroupManagerAggregatedList", "instanceGroupManagers", s.groupSeen()), nil +} + +// groupSeen observes each listed group's change in progress and brings its +// counts up to date. The caller holds s.mu. +func (s *Server) groupSeen() func(*InstanceGroupManager) { + seen := s.observer() + return func(g *InstanceGroupManager) { + seen(g.op) + if s.groups[g.zone].has(g.Name) { + s.refresh(g) + } + } +} + +func (s *Server) deleteGroupManager(r *http.Request, opFault *apiError) (any, *apiError) { + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + if g.op != nil { + s.finish(g.op) + if g, err = s.lookupGroup(r, "name"); err != nil { + return nil, err + } + } + path := groupPath(g.zone, g.Name) + if opFault != nil { + return encoded(s.startOperation(r, reqID, "delete", path, g.ID, opFault, nil)), nil + } + for _, name := range g.requests.names { + s.stopRequest(g.requests.byName[name]) + } + var insts []*Instance + for _, name := range slices.Clone(g.members.names) { + m := g.members.byName[name] + if m.inst != nil && m.inst.op != nil { + s.finish(m.inst.op) + } + if !s.holds(g.zone, m.inst) { + continue + } + m.deleting, m.inst.Status = true, statusStopping + insts = append(insts, m.inst) + } + op := s.startOperation(r, reqID, "delete", path, g.ID, nil, func() { + for _, inst := range insts { + s.removeInstance(g.zone, inst) + } + s.groups[g.zone].remove(g.Name) + g.op = nil + }) + if op.complete != nil { + g.op = op + track(op, insts, nil, false) + } + return encoded(op), nil +} + +// PerInstanceConfig names an instance a group or resize request creates. +type PerInstanceConfig struct { + Name string `json:"name"` +} + +// checkNewNames checks that names may be new instances of g: valid, distinct, +// and not taken by an instance or member. field names them in errors. A +// conflicting instance with a change in progress counts a read of it. The +// caller holds s.mu. +func (s *Server) checkNewNames(g *InstanceGroupManager, field string, names []string) (conflict string, err *apiError) { + if len(names) == 0 || len(names) > maxGroupInstances { + return "", invalid("Invalid value for field '%s': between 1 and %d instances are required.", field, maxGroupInstances) + } + for i, name := range names { + if !validName(name) { + return "", invalid("Invalid value for field '%s[%d].name': '%s'. Must be a match of regex '(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'", field, i, name) + } + if slices.Contains(names[:i], name) { + return "", invalid("Invalid value for field '%s[%d].name': '%s'. Instance names must be unique.", field, i, name) + } + } + for _, name := range names { + if inst, ok := lookupIn(s.instances, g.zone, name); ok { + s.observe(inst.op) + } + if _, ok := lookupIn(s.instances, g.zone, name); ok || g.members.has(name) { + return name, nil + } + } + return "", nil +} + +func (s *Server) createGroupInstances(r *http.Request, opFault *apiError) (any, *apiError) { + var in struct { + Instances []PerInstanceConfig `json:"instances"` + } + if err := decodeStrict(r, &in); err != nil { + return nil, err + } + names := make([]string, len(in.Instances)) + for i, c := range in.Instances { + names[i] = c.Name + } + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + s.refresh(g) + conflict, err := s.checkNewNames(g, "resource.instances", names) + if err != nil { + return nil, err + } + if conflict != "" { + return nil, alreadyExists(instancePath(g.zone, conflict)) + } + path := groupPath(g.zone, g.Name) + if opFault == nil { + s.addMembers(g, names) + } + return encoded(s.startOperation(r, reqID, "createInstances", path, g.ID, opFault, nil)), nil +} + +func (s *Server) deleteGroupInstances(r *http.Request, opFault *apiError) (any, *apiError) { + var in struct { + Instances []string `json:"instances"` + SkipInstancesOnValidationError bool `json:"skipInstancesOnValidationError"` + } + if err := decodeStrict(r, &in); err != nil { + return nil, err + } + refs := in.Instances + if len(refs) == 0 || len(refs) > maxGroupInstances { + return nil, invalid("Invalid value for field 'resource.instances': between 1 and %d instances are required.", maxGroupInstances) + } + byURL := slices.ContainsFunc(refs, func(ref string) bool { return strings.Contains(ref, "/") }) + if byURL && slices.ContainsFunc(refs, func(ref string) bool { return !strings.Contains(ref, "/") }) { + return nil, invalid("Invalid value for field 'resource.instances': instances must be named all by URL or all by name.") + } + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + s.refresh(g) + path := groupPath(g.zone, g.Name) + var release []*member + for i, ref := range refs { + name := ref + if byURL { + inZone, n, ok := strings.Cut(relPath(ref, projectOf(g.zone)), "/instances/") + if !ok || !validName(n) || inZone != g.zone { + opFault = cmp.Or(opFault, invalid("Invalid value for field 'resource.instances[%d]': '%s'. The instance must be in zone '%s'.", i, ref, g.zone)) + break + } + name = n + } + m, ok := g.members.byName[name] + if ok && !m.deleting && !slices.Contains(release, m) { + release = append(release, m) + continue + } + if !in.SkipInstancesOnValidationError { + opFault = cmp.Or(opFault, invalid("Invalid value for field 'resource.instances[%d]': '%s'. The instance is not a member of the group or is already being deleted.", i, ref)) + break + } + } + if opFault == nil { + for _, m := range release { + s.releaseMember(g, m) + } + } + return encoded(s.startOperation(r, reqID, "deleteInstances", path, g.ID, opFault, nil)), nil +} + +func (s *Server) setGroupTemplate(r *http.Request, opFault *apiError) (any, *apiError) { + var in struct { + InstanceTemplate string `json:"instanceTemplate"` + } + if err := decodeStrict(r, &in); err != nil { + return nil, err + } + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + link, err := s.templateLink(projectOf(g.zone), "instanceTemplate", in.InstanceTemplate) + if err != nil { + return nil, err + } + if opFault == nil { + g.InstanceTemplate = link + g.Fingerprint = hash([]any{g.ID, g.InstanceTemplate}) + } + return encoded(s.startOperation(r, reqID, "setInstanceTemplate", groupPath(g.zone, g.Name), g.ID, opFault, nil)), nil +} + +// managedInstanceList is a listManagedInstances response. +type managedInstanceList struct { + ManagedInstances []ManagedInstance `json:"managedInstances,omitzero"` + NextPageToken string `json:"nextPageToken,omitzero"` +} + +func (s *Server) listManagedInstances(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, fieldSet{names: []string{"name"}}) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + g, err := s.lookupGroup(r, "name") + if err != nil { + return nil, err + } + s.refresh(g) + start := 0 + if g.ListManagedInstancesResults == "PAGINATED" { + start = afterName(g.members.names, q.after) + } else { + q.limit = maxGroupInstances + } + var list managedInstanceList + for _, m := range scan(g.members, start, q.filter, nil) { + if len(list.ManagedInstances) == q.limit { + list.NextPageToken = list.ManagedInstances[len(list.ManagedInstances)-1].Name + break + } + list.ManagedInstances = append(list.ManagedInstances, m.view()) + } + return encoded(list), nil +} + +// InstanceGroupManagers returns every instance group manager the server +// holds, ordered by selfLink. +func (s *Server) InstanceGroupManagers() []InstanceGroupManager { + s.mu.Lock() + defer s.mu.Unlock() + var out []InstanceGroupManager + each(s.groups, func(g *InstanceGroupManager) { + s.refresh(g) + out = append(out, jsonClone(g)) + }) + return out +} + +// ManagedInstances returns the instances of the named group in project and +// zone, as listManagedInstances reports them, ordered by name. +func (s *Server) ManagedInstances(project, zone, group string) ([]ManagedInstance, bool) { + s.mu.Lock() + defer s.mu.Unlock() + g, ok := lookupIn(s.groups, "projects/"+project+"/zones/"+zone, group) + if !ok { + return nil, false + } + s.refresh(g) + out := []ManagedInstance{} + for _, name := range g.members.names { + out = append(out, g.members.byName[name].view()) + } + return out, true +} diff --git a/gcp/compute/instance_actions.go b/gcp/compute/instance_actions.go index 882da35..3a32dc0 100644 --- a/gcp/compute/instance_actions.go +++ b/gcp/compute/instance_actions.go @@ -169,6 +169,10 @@ func (s *Server) instanceVerb(verb string) handler { c = s.stopInstance(inst) case "start": c = s.startInstance(inst) + case "suspend": + c = s.suspendInstance(inst, path) + case "resume": + c = s.resumeInstance(inst, path) case "setLabels": c, err = setInstanceLabels(inst, labels) case "setMachineType": @@ -223,6 +227,40 @@ func (s *Server) startInstance(inst *Instance) change { } } +// suspendInstance suspends a running inst, unless it is already suspended. +// The caller holds s.mu. +func (s *Server) suspendInstance(inst *Instance, path string) change { + switch inst.Status { + case statusSuspended: + return change{} + case statusRunning: + default: + return change{fail: notReady(path)} + } + return change{ + now: func() { inst.Status = statusSuspending }, + later: func() { + inst.Status, inst.LastSuspendedTimestamp, inst.op = statusSuspended, timestamp(s.now()), nil + }, + } +} + +// resumeInstance resumes a suspended inst, unless it is already running. The +// caller holds s.mu. +func (s *Server) resumeInstance(inst *Instance, path string) change { + switch inst.Status { + case statusRunning: + return change{} + case statusSuspended: + default: + return change{fail: notReady(path)} + } + return change{ + now: func() { inst.Status = statusStaging }, + later: func() { inst.Status, inst.op = statusRunning, nil }, + } +} + func setInstanceLabels(inst *Instance, req setLabelsRequest) (change, *apiError) { if req.LabelFingerprint == "" { return change{}, invalid("Required field 'labelFingerprint' not specified") diff --git a/gcp/compute/instances.go b/gcp/compute/instances.go index 7fa5bcd..a661156 100644 --- a/gcp/compute/instances.go +++ b/gcp/compute/instances.go @@ -22,6 +22,8 @@ const ( statusRunning = "RUNNING" statusStopping = "STOPPING" statusTerminated = "TERMINATED" + statusSuspending = "SUSPENDING" + statusSuspended = "SUSPENDED" maxNetworkInterfaces = 8 maxBulkCount = 1000 @@ -53,6 +55,7 @@ type Instance struct { StartRestricted bool `json:"startRestricted"` LastStartTimestamp string `json:"lastStartTimestamp,omitzero"` LastStopTimestamp string `json:"lastStopTimestamp,omitzero"` + LastSuspendedTimestamp string `json:"lastSuspendedTimestamp,omitzero"` ResourcePolicies []string `json:"resourcePolicies,omitzero"` Hostname string `json:"hostname,omitzero"` MinCPUPlatform string `json:"minCpuPlatform,omitzero"` @@ -234,7 +237,7 @@ func (s *Server) newInstance(zone, region, name, field string, props Instance, b inst.CreationTimestamp = timestamp(s.now()) inst.Zone, inst.SelfLink = selfLinkBase+zone, selfLinkBase+path inst.Status, inst.StartRestricted = statusProvisioning, false - inst.LastStartTimestamp, inst.LastStopTimestamp, inst.op = "", "", nil + inst.LastStartTimestamp, inst.LastStopTimestamp, inst.LastSuspendedTimestamp, inst.op = "", "", "", nil inst.LabelFingerprint = fingerprint(inst.Labels) inst.Tags.Fingerprint = hash(inst.Tags.Items) inst.Metadata.Kind, inst.Metadata.Fingerprint = "compute#metadata", hash(inst.Metadata.Items) @@ -741,8 +744,9 @@ func decodeValue(b []byte) any { } // bulkNames are the names a bulkInsert creates: those it lists, in order, and -// then as many from its pattern as count asks for. The caller holds s.mu. -func (s *Server) bulkNames(zone string, in *bulkInsertInput) ([]string, *apiError) { +// then as many from its pattern as count asks for, numbered after the +// instances in zones. The caller holds s.mu. +func (s *Server) bulkNames(zones []string, in *bulkInsertInput) ([]string, *apiError) { names := slices.Sorted(maps.Keys(in.PerInstanceProperties)) for _, name := range names { if p := in.PerInstanceProperties[name]; p.Name != "" && p.Name != name { @@ -765,7 +769,11 @@ func (s *Server) bulkNames(zone string, in *bulkInsertInput) ([]string, *apiErro return nil, invalid("Invalid value for field 'resource.namePattern': '%s'. The pattern must hold one run of 1 to 18 '#' characters.", in.NamePattern) } next := uint64(0) - if c := s.instances[zone]; c != nil { + for _, zone := range zones { + c := s.instances[zone] + if c == nil { + continue + } for _, name := range c.names { digits, hasPrefix := strings.CutPrefix(name, prefix) if digits, ok := strings.CutSuffix(digits, suffix); hasPrefix && ok && len(digits) == width { @@ -788,6 +796,65 @@ func (s *Server) bulkNames(zone string, in *bulkInsertInput) ([]string, *apiErro return names, nil } +// locationPolicy is a regional bulkInsert's locationPolicy. +type locationPolicy struct { + Locations map[string]struct { + Preference string `json:"preference"` + Constraints json.RawMessage `json:"constraints"` + } `json:"locations"` + TargetShape string `json:"targetShape"` +} + +// placeBulk returns the zone, as a path, of each of n instances a regional +// bulkInsert creates in region, from the zones its policy allows: all in the +// first allowed zone in name order, or spread across the allowed zones in turn +// when the policy's targetShape is BALANCED. The caller holds s.mu. +func (s *Server) placeBulk(project, region string, raw json.RawMessage, n int) ([]string, *apiError) { + zones := slices.Sorted(slices.Values(s.regionZones[region])) + if len(zones) == 0 { + return nil, invalid("Invalid value for field 'region': '%s'. Unknown region.", region) + } + var policy locationPolicy + if len(raw) > 0 && string(raw) != "null" { + if err := unmarshalStrict(raw, &policy); err != nil { + return nil, err + } + } + denied := map[string]bool{} + for key, loc := range policy.Locations { + zone, ok := strings.CutPrefix(key, "zones/") + if !ok || !slices.Contains(zones, zone) { + return nil, invalid("Invalid value for field 'resource.locationPolicy.locations': '%s'. The location must be a zone of region '%s'.", key, region) + } + switch loc.Preference { + case "", "PREFERENCE_UNSPECIFIED", "ALLOW": + case "DENY": + denied[zone] = true + default: + return nil, invalid("Invalid value for field 'resource.locationPolicy.locations[%s].preference': '%s'.", key, loc.Preference) + } + } + allowed := slices.DeleteFunc(zones, func(z string) bool { return denied[z] }) + if len(allowed) == 0 { + return nil, invalid("Invalid value for field 'resource.locationPolicy': every zone of region '%s' is denied.", region) + } + switch policy.TargetShape { + case "", "ANY", "ANY_SINGLE_ZONE": + allowed = allowed[:1] + case "BALANCED": + default: + return nil, invalid("Invalid value for field 'resource.locationPolicy.targetShape': '%s'.", policy.TargetShape) + } + placed := make([]string, n) + for i := range placed { + placed[i] = "projects/" + project + "/zones/" + allowed[i%len(allowed)] + } + return placed, nil +} + +// bulkInsertInstances answers a bulkInsert, zonal or regional. A regional one +// places its instances with placeBulk, and its names must be free in every +// zone of the region. func (s *Server) bulkInsertInstances(r *http.Request, opFault *apiError) (any, *apiError) { var in bulkInsertInput if err := decodeStrict(r, &in); err != nil { @@ -818,14 +885,14 @@ func (s *Server) bulkInsertInstances(r *http.Request, opFault *apiError) (any, * if err != nil { return nil, err } - zone, region := scopeOf(r), s.regionOfZone(r) + project := r.PathValue("project") s.mu.Lock() defer s.mu.Unlock() if op, ok := s.requests[reqID]; ok { return encoded(op), nil } if in.SourceInstanceTemplate != "" { - template, err := s.templateProperties(projectOf(zone), in.SourceInstanceTemplate) + template, err := s.templateProperties(project, in.SourceInstanceTemplate) if err != nil { return nil, err } @@ -837,11 +904,29 @@ func (s *Server) bulkInsertInstances(r *http.Request, opFault *apiError) (any, * if props.Name != "" { return nil, invalid("Invalid JSON payload received. Unknown name \"name\" at '%s': Cannot find field.", field) } - names, err := s.bulkNames(zone, &in) + regionName, regional := r.PathValue("region"), r.PathValue("zone") == "" + inRegion := []string{scopeOf(r)} + if regional { + inRegion = nil + for _, z := range s.regionZones[regionName] { + inRegion = append(inRegion, "projects/"+project+"/zones/"+z) + } + } else { + regionName = s.zoneRegion[r.PathValue("zone")] + } + region := "projects/" + project + "/regions/" + regionName + names, err := s.bulkNames(inRegion, &in) if err != nil { return nil, err } + placed := slices.Repeat(inRegion, len(names)) + if regional { + if placed, err = s.placeBulk(project, regionName, in.LocationPolicy, len(names)); err != nil { + return nil, err + } + } type built struct { + zone string inst *Instance disks []*Disk claims []claim @@ -850,10 +935,17 @@ func (s *Server) bulkInsertInstances(r *http.Request, opFault *apiError) (any, * batch []built insts []*Instance disks []*Disk - conflicts []operationError + conflicts []OperationError creating = map[string]bool{} + metadata = &bulkInsertMetadata{map[string]bulkInsertStatus{}} + created = map[string]bulkInsertStatus{} ) - for _, name := range names { + for i, name := range names { + zone := placed[i] + location := "zones/" + zone[strings.LastIndexByte(zone, '/')+1:] + status := metadata.PerLocationStatus[location] + status.Status, status.TargetVMCount = "DONE", status.TargetVMCount+1 + metadata.PerLocationStatus[location] = status p := *props p.Hostname = cmp.Or(in.PerInstanceProperties[name].Hostname, p.Hostname) inst, d, c, err := s.newInstance(zone, region, name, field, p, true) @@ -861,55 +953,66 @@ func (s *Server) bulkInsertInstances(r *http.Request, opFault *apiError) (any, * return nil, err } before := len(conflicts) - if _, ok := lookupIn(s.instances, zone, name); ok { - conflicts = append(conflicts, operationError{"RESOURCE_ALREADY_EXISTS", alreadyExists(instancePath(zone, name)).Message}) + for _, z := range inRegion { + if _, ok := lookupIn(s.instances, z, name); ok { + conflicts = append(conflicts, OperationError{"RESOURCE_ALREADY_EXISTS", alreadyExists(instancePath(z, name)).Message}) + } } for _, disk := range d { - if _, ok := lookupIn(s.disks, zone, disk.Name); ok || creating[disk.Name] { - conflicts = append(conflicts, operationError{"RESOURCE_ALREADY_EXISTS", alreadyExists(diskPath(zone, disk.Name)).Message}) + if _, ok := lookupIn(s.disks, zone, disk.Name); ok || creating[diskPath(zone, disk.Name)] { + conflicts = append(conflicts, OperationError{"RESOURCE_ALREADY_EXISTS", alreadyExists(diskPath(zone, disk.Name)).Message}) } } if len(conflicts) > before { continue } for _, disk := range d { - creating[disk.Name] = true + creating[diskPath(zone, disk.Name)] = true } - batch = append(batch, built{inst, d, c}) + batch = append(batch, built{zone, inst, d, c}) insts, disks = append(insts, inst), append(disks, d...) + done := created[location] + done.CreatedVMCount++ + created[location] = done } conflicted := len(batch) < int(in.MinCount) && opFault == nil if conflicted { opFault = &apiError{ Status: http.StatusConflict, Reason: "resourceAlreadyExists", Message: conflicts[0].Message, - opErrors: append([]operationError{{"VM_MIN_COUNT_NOT_REACHED", fmt.Sprintf("Requested minimum count of %d VMs could not be created.", in.MinCount)}}, conflicts...), + opErrors: append([]OperationError{{"VM_MIN_COUNT_NOT_REACHED", fmt.Sprintf("Requested minimum count of %d VMs could not be created.", in.MinCount)}}, conflicts...), } } - location := "zones/" + r.PathValue("zone") - status := bulkInsertStatus{Status: "DONE", TargetVMCount: len(names)} - metadata := &bulkInsertMetadata{map[string]bulkInsertStatus{location: status}} - target := "projects/" + r.PathValue("project") + target := "projects/" + project if opFault != nil { op := s.startOperation(r, reqID, "bulkInsert", target, 0, opFault, nil) if !conflicted { - status.FailedToCreateVMCount = len(names) + for location, status := range metadata.PerLocationStatus { + status.FailedToCreateVMCount = status.TargetVMCount + metadata.PerLocationStatus[location] = status + } } - metadata.PerLocationStatus[location], op.BulkInsert = status, metadata + op.BulkInsert = metadata return encoded(op), nil } for _, b := range batch { - s.storeInstance(zone, region, b.inst, b.disks, b.claims) + s.storeInstance(b.zone, region, b.inst, b.disks, b.claims) + } + final := map[string]bulkInsertStatus{} + for location, status := range metadata.PerLocationStatus { + status.CreatedVMCount = created[location].CreatedVMCount + status.FailedToCreateVMCount = status.TargetVMCount - status.CreatedVMCount + final[location] = status } - created := status - created.CreatedVMCount, created.FailedToCreateVMCount = len(batch), len(names)-len(batch) provisioned := s.provisioned(insts, disks) op := s.startOperation(r, reqID, "bulkInsert", target, 0, nil, func() { provisioned() - metadata.PerLocationStatus[location] = created + metadata.PerLocationStatus = final }) if op.complete != nil { - status.Status = "CREATING" - metadata.PerLocationStatus[location] = status + for location, status := range metadata.PerLocationStatus { + status.Status = "CREATING" + metadata.PerLocationStatus[location] = status + } } op.BulkInsert = metadata track(op, insts, disks, true) diff --git a/gcp/compute/operations.go b/gcp/compute/operations.go index de9d90f..06d21db 100644 --- a/gcp/compute/operations.go +++ b/gcp/compute/operations.go @@ -33,7 +33,7 @@ type operation struct { Zone string `json:"zone,omitzero"` Region string `json:"region,omitzero"` SelfLink string `json:"selfLink"` - Error *operationErrors `json:"error,omitzero"` + Error *OperationErrors `json:"error,omitzero"` HTTPErrorStatusCode int `json:"httpErrorStatusCode,omitzero"` HTTPErrorMessage string `json:"httpErrorMessage,omitzero"` BulkInsert *bulkInsertMetadata `json:"instancesBulkInsertOperationMetadata,omitzero"` @@ -45,13 +45,17 @@ type operation struct { complete func() // staging are instances that show STAGING on the operation's last read in progress. staging []*Instance + // progress, when set, runs on the operation's last read in progress. + progress func() } -type operationErrors struct { - Errors []operationError `json:"errors"` +// OperationErrors are the errors of a failed operation or attempt. +type OperationErrors struct { + Errors []OperationError `json:"errors"` } -type operationError struct { +// OperationError is one error of a failed operation or attempt. +type OperationError struct { Code string `json:"code"` Message string `json:"message"` } @@ -123,9 +127,9 @@ func (s *Server) startOperation(r *http.Request, requestID, opType, target strin case failure != nil: errs := failure.opErrors if errs == nil { - errs = []operationError{{Code: reason.UpperSnake(failure.Reason), Message: failure.Message}} + errs = []OperationError{{Code: reason.UpperSnake(failure.Reason), Message: failure.Message}} } - op.Error = &operationErrors{errs} + op.Error = &OperationErrors{errs} op.HTTPErrorStatusCode = failure.Status op.HTTPErrorMessage = strings.ToUpper(http.StatusText(failure.Status)) s.done(op) @@ -173,7 +177,7 @@ func (s *Server) finish(op *operation) { return } complete := op.complete - op.complete, op.staging = nil, nil + op.complete, op.staging, op.progress = nil, nil, nil delete(s.pending, op) complete() s.done(op) @@ -195,6 +199,9 @@ func (s *Server) observe(op *operation) { inst.Status = statusStaging } } + if op.progress != nil { + op.progress() + } } } diff --git a/gcp/compute/permissions.go b/gcp/compute/permissions.go index a62f6ab..32d61b9 100644 --- a/gcp/compute/permissions.go +++ b/gcp/compute/permissions.go @@ -30,19 +30,24 @@ var basePermissions = map[string][]string{ "compute.zones.list": {"compute.zones.list"}, "compute.zones.get": {"compute.zones.get"}, - "compute.instances.bulkInsert": {"compute.instances.create"}, - "compute.instances.insert": {"compute.instances.create"}, - "compute.instances.list": {"compute.instances.list"}, - "compute.instances.aggregatedList": {"compute.instances.list"}, - "compute.instances.get": {"compute.instances.get"}, - "compute.instances.delete": {"compute.instances.delete"}, - "compute.instances.stop": {"compute.instances.stop"}, - "compute.instances.start": {"compute.instances.start"}, - "compute.instances.setLabels": {"compute.instances.setLabels"}, - "compute.instances.setMachineType": {"compute.instances.setMachineType"}, - "compute.instances.addAccessConfig": {"compute.instances.addAccessConfig", "compute.subnetworks.useExternalIp|compute.networks.useExternalIp"}, - "compute.instances.attachDisk": {"compute.instances.attachDisk"}, - "compute.instances.detachDisk": {"compute.instances.detachDisk"}, + "compute.acceleratorTypes.aggregatedList": {"compute.acceleratorTypes.list"}, + "compute.acceleratorTypes.list": {"compute.acceleratorTypes.list"}, + "compute.acceleratorTypes.get": {"compute.acceleratorTypes.get"}, + + "compute.instances.bulkInsert": {"compute.instances.create"}, + "compute.regionInstances.bulkInsert": {"compute.instances.create"}, + "compute.instances.insert": {"compute.instances.create"}, + "compute.instances.list": {"compute.instances.list"}, + "compute.instances.aggregatedList": {"compute.instances.list"}, + "compute.instances.get": {"compute.instances.get"}, + "compute.instances.delete": {"compute.instances.delete"}, + "compute.instances.stop": {"compute.instances.stop"}, + "compute.instances.start": {"compute.instances.start"}, + "compute.instances.setLabels": {"compute.instances.setLabels"}, + "compute.instances.setMachineType": {"compute.instances.setMachineType"}, + "compute.instances.addAccessConfig": {"compute.instances.addAccessConfig", "compute.subnetworks.useExternalIp|compute.networks.useExternalIp"}, + "compute.instances.attachDisk": {"compute.instances.attachDisk"}, + "compute.instances.detachDisk": {"compute.instances.detachDisk"}, "compute.disks.list": {"compute.disks.list"}, "compute.disks.aggregatedList": {"compute.disks.list"}, @@ -65,7 +70,21 @@ var basePermissions = map[string][]string{ "compute.instanceTemplates.get": {"compute.instanceTemplates.get"}, "compute.instanceTemplates.delete": {"compute.instanceTemplates.delete"}, - "compute.instanceGroupManagers.aggregatedList": {"compute.instanceGroupManagers.list"}, + "compute.instanceGroupManagers.list": {"compute.instanceGroupManagers.list"}, + "compute.instanceGroupManagers.aggregatedList": {"compute.instanceGroupManagers.list"}, + "compute.instanceGroupManagers.insert": {"compute.instanceGroupManagers.create"}, + "compute.instanceGroupManagers.get": {"compute.instanceGroupManagers.get"}, + "compute.instanceGroupManagers.delete": {"compute.instanceGroupManagers.delete", "compute.instanceGroups.delete"}, + "compute.instanceGroupManagers.createInstances": {"compute.instanceGroupManagers.update"}, + "compute.instanceGroupManagers.deleteInstances": {"compute.instanceGroupManagers.update"}, + "compute.instanceGroupManagers.setInstanceTemplate": {"compute.instanceGroupManagers.update", "compute.instanceTemplates.get|compute.instanceTemplates.useReadOnly"}, + "compute.instanceGroupManagers.listManagedInstances": {"compute.instanceGroupManagers.get"}, + + "compute.instanceGroupManagerResizeRequests.list": {"compute.instanceGroupManagers.get"}, + "compute.instanceGroupManagerResizeRequests.insert": {"compute.instanceGroupManagers.update"}, + "compute.instanceGroupManagerResizeRequests.get": {"compute.instanceGroupManagers.get"}, + "compute.instanceGroupManagerResizeRequests.delete": {"compute.instanceGroupManagers.update"}, + "compute.instanceGroupManagerResizeRequests.cancel": {"compute.instanceGroupManagers.update"}, "compute.routes.list": {"compute.routes.list"}, "compute.routes.insert": {"compute.routes.create", "compute.networks.updatePolicy"}, @@ -174,7 +193,7 @@ func needs(method string, r *http.Request) []string { case "compute.instances.insert": perms = append(perms, f.needs()...) add(f.DeletionProtection, "compute.instances.setDeletionProtection") - case "compute.instances.bulkInsert": + case "compute.instances.bulkInsert", "compute.regionInstances.bulkInsert": add(f.SourceInstanceTemplate != "", "compute.instanceTemplates.useReadOnly") if f.InstanceProperties != nil { perms = append(perms, f.InstanceProperties.needs()...) diff --git a/gcp/compute/policies.go b/gcp/compute/policies.go index b749417..d8e44fc 100644 --- a/gcp/compute/policies.go +++ b/gcp/compute/policies.go @@ -274,6 +274,9 @@ func (s *Server) deleteTemplate(r *http.Request, opFault *apiError) (any, *apiEr if !ok { return nil, notFound(path) } + if user := s.groupUsing(t.SelfLink); user != "" { + return nil, inUse("instance_template", path, user) + } if opFault == nil { s.templates[global].remove(name) } @@ -299,18 +302,3 @@ func (s *Server) InstanceTemplates() []InstanceTemplate { each(s.templates, func(t *InstanceTemplate) { out = append(out, jsonClone(t)) }) return out } - -// groupManager stands in for instance group managers, which the server -// never holds: their aggregated list is always empty. -type groupManager struct{} - -func (groupManager) filterValue(string) string { return "" } - -func (s *Server) aggregatedGroupManagers(r *http.Request, _ *apiError) (any, *apiError) { - q, err := parseListQuery(r, namedFields) - if err != nil { - return nil, err - } - return listAggregated(map[string]*collection[groupManager]{}, r.PathValue("project"), q, - "compute#instanceGroupManagerAggregatedList", "instanceGroupManagers", nil), nil -} diff --git a/gcp/compute/resize.go b/gcp/compute/resize.go new file mode 100644 index 0000000..2de3ccc --- /dev/null +++ b/gcp/compute/resize.go @@ -0,0 +1,424 @@ +package compute + +import ( + "fmt" + "net/http" + "slices" + "strconv" + + "github.com/parallelworks/squall/internal/reason" +) + +const ( + resizeAccepted = "ACCEPTED" + resizeCreating = "CREATING" + resizeSucceeded = "SUCCEEDED" + resizeFailed = "FAILED" + resizeCancelled = "CANCELLED" +) + +// ResizeRequest is a request to add instances to a zonal managed instance +// group, in the API's JSON shape. +type ResizeRequest struct { + Kind string `json:"kind"` + ID uint64 `json:"id,string"` + CreationTimestamp string `json:"creationTimestamp"` + Name string `json:"name"` + Description string `json:"description,omitzero"` + Zone string `json:"zone"` + ResizeBy int `json:"resizeBy,omitzero"` + Instances []PerInstanceConfig `json:"instances,omitzero"` + RequestedRunDuration *Duration `json:"requestedRunDuration,omitzero"` + State string `json:"state"` + Status ResizeRequestStatus `json:"status"` + SelfLink string `json:"selfLink"` + + group *InstanceGroupManager + op *operation + names []string +} + +// Duration is a span of time, in the API's JSON shape. +type Duration struct { + Seconds Int64 `json:"seconds"` + Nanos int `json:"nanos,omitzero"` +} + +// ResizeRequestStatus is what went wrong with a resize request: Error once +// it has FAILED, or LastAttempt while it waits to try again. +type ResizeRequestStatus struct { + Error *OperationErrors `json:"error,omitzero"` + LastAttempt *ResizeRequestAttempt `json:"lastAttempt,omitzero"` +} + +// ResizeRequestAttempt is a resize request's last failed attempt at its instances. +type ResizeRequestAttempt struct { + Error OperationErrors `json:"error"` +} + +var resizeFields = fieldSet{names: []string{"name", "description", "id", "state"}} + +func (req *ResizeRequest) filterValue(field string) string { + switch field { + case "name": + return req.Name + case "description": + return req.Description + case "id": + return strconv.FormatUint(req.ID, 10) + case "state": + return req.State + } + return "" +} + +func resizePath(g *InstanceGroupManager, name string) string { + return groupPath(g.zone, g.Name) + "/resizeRequests/" + name +} + +func (req *ResizeRequest) active() bool { + return req.State == resizeAccepted || req.State == resizeCreating +} + +func errorsOf(code, message string) *OperationErrors { + if code == "" && message == "" { + return nil + } + return &OperationErrors{[]OperationError{{code, message}}} +} + +// lookupRequest returns the resize request r names in the group it names. +// The caller holds s.mu. +func (s *Server) lookupRequest(r *http.Request) (*ResizeRequest, *apiError) { + g, err := s.lookupGroup(r, "group") + if err != nil { + return nil, err + } + name := r.PathValue("name") + req, ok := g.requests.byName[name] + if !ok { + return nil, notFound(resizePath(g, name)) + } + return req, nil +} + +func (s *Server) insertResizeRequest(r *http.Request, opFault *apiError) (any, *apiError) { + var want ResizeRequest + if err := decodeStrict(r, &want); err != nil { + return nil, err + } + if !validName(want.Name) { + return nil, invalid("Invalid value for field 'resource.name': '%s'. Must be a match of regex '(?:[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?)'", want.Name) + } + if (want.ResizeBy != 0) == (len(want.Instances) != 0) { + return nil, invalid("Invalid value for field 'resource': exactly one of resizeBy and instances must be set.") + } + if want.ResizeBy < 0 || want.ResizeBy > maxGroupInstances { + return nil, invalid("Invalid value for field 'resource.resizeBy': '%d'. Must be between 1 and %d.", want.ResizeBy, maxGroupInstances) + } + if d := want.RequestedRunDuration; d != nil && (d.Seconds < 0 || d.Nanos < 0 || d.Nanos > 999_999_999) { + return nil, invalid("Invalid value for field 'resource.requestedRunDuration': seconds must not be negative and nanos must be from 0 to 999999999.") + } + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + g, err := s.lookupGroup(r, "group") + if err != nil { + return nil, err + } + s.refresh(g) + path := resizePath(g, want.Name) + if g.requests.has(want.Name) { + return nil, alreadyExists(path) + } + var names []string + for _, c := range want.Instances { + names = append(names, c.Name) + } + if len(names) > 0 && opFault == nil { + conflict, err := s.checkNewNames(g, "resource.instances", names) + if err != nil { + return nil, err + } + if conflict == "" { + conflict = s.queuedName(g, names) + } + if conflict != "" { + i := slices.Index(names, conflict) + msg := fmt.Sprintf("Invalid value for field 'resource.instances[%d].name': '%s'. Instance '%s' already exists", i, conflict, conflict) + opFault = &apiError{Status: http.StatusBadRequest, Reason: "invalid", Message: msg, opErrors: []OperationError{{"INVALID_FIELD_VALUE", msg}}} + } + } + if opFault != nil { + return encoded(s.startOperation(r, reqID, "insert", path, 0, opFault, nil)), nil + } + req := &ResizeRequest{ + Kind: "compute#instanceGroupManagerResizeRequest", ID: s.newID(), CreationTimestamp: timestamp(s.now()), + Name: want.Name, Description: want.Description, Zone: selfLinkBase + g.zone, ResizeBy: want.ResizeBy, + Instances: want.Instances, RequestedRunDuration: want.RequestedRunDuration, State: resizeAccepted, + SelfLink: selfLinkBase + path, group: g, names: names, + } + g.requests.put(req.Name, req) + op := s.startOperation(r, reqID, "insert", path, req.ID, nil, nil) + s.provision(req) + return encoded(op), nil +} + +// queuedName returns the first of names that another active resize request +// of g asks for, or "". The caller holds s.mu. +func (s *Server) queuedName(g *InstanceGroupManager, names []string) string { + for _, name := range names { + for _, other := range g.requests.byName { + if other.State == resizeAccepted && slices.Contains(other.names, name) { + return name + } + } + } + return "" +} + +// provision fulfills req in the background: it is CREATING its instances on +// the last read [WithSettleAfter] allows, and SUCCEEDED once they run. The +// caller holds s.mu. +func (s *Server) provision(req *ResizeRequest) { + var insts []*Instance + var disks []*Disk + create := func() bool { + if req.State != resizeAccepted { + return req.State == resizeCreating + } + g := req.group + if len(req.names) == 0 { + for range req.ResizeBy { + req.names = append(req.names, s.memberName(g, req.names)) + } + } + type built struct { + inst *Instance + disks []*Disk + claims []claim + } + var batch []built + for _, name := range req.names { + if g.members.has(name) { + s.failRequest(req, "ALREADY_EXISTS", alreadyExists(instancePath(g.zone, name)).Message) + return false + } + inst, d, c, err := s.buildMember(g, name) + if err != nil { + s.failRequest(req, reason.UpperSnake(err.Reason), err.Message) + return false + } + batch = append(batch, built{inst, d, c}) + } + for _, b := range batch { + s.storeInstance(g.zone, s.regionOf(g.zone), b.inst, b.disks, b.claims) + g.members.put(b.inst.Name, &member{name: b.inst.Name, template: g.InstanceTemplate, inst: b.inst}) + insts, disks = append(insts, b.inst), append(disks, b.disks...) + } + req.State, req.Status.LastAttempt = resizeCreating, nil + if req.op != nil { + track(req.op, insts, disks, true) + } + return true + } + op := s.inBackground(func() { + if create() { + s.provisioned(insts, disks)() + req.State = resizeSucceeded + } + req.op = nil + }) + if op.complete == nil { + return + } + req.op = op + op.progress = func() { create() } +} + +// stopRequest stops req's provisioning, if it is in progress, leaving the +// instances it has created as they are. The caller holds s.mu. +func (s *Server) stopRequest(req *ResizeRequest) { + op := req.op + if op == nil { + return + } + for _, inst := range op.staging { + if inst.op == op { + inst.op = nil + } + } + op.complete, op.progress, op.staging = nil, nil, nil + delete(s.pending, op) + s.done(op) + req.op = nil +} + +// failRequest ends req in FAILED with an error of code and message, deleting +// the instances it created, as the API rolls them back. The caller holds s.mu. +func (s *Server) failRequest(req *ResizeRequest, code, message string) { + s.stopRequest(req) + g := req.group + if req.State == resizeCreating { + for _, name := range req.names { + if m, ok := g.members.byName[name]; ok { + if s.holds(g.zone, m.inst) { + s.removeInstance(g.zone, m.inst) + } + g.members.remove(name) + } + } + } + req.State = resizeFailed + req.Status = ResizeRequestStatus{Error: errorsOf(code, message)} +} + +func (s *Server) getResizeRequest(r *http.Request, _ *apiError) (any, *apiError) { + s.mu.Lock() + defer s.mu.Unlock() + req, err := s.lookupRequest(r) + if err != nil { + return nil, err + } + s.observe(req.op) + return encoded(req), nil +} + +func (s *Server) listResizeRequests(r *http.Request, _ *apiError) (any, *apiError) { + q, err := parseListQuery(r, resizeFields) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + g, err := s.lookupGroup(r, "group") + if err != nil { + return nil, err + } + seen := s.observer() + return listScope(g.requests, q, "compute#instanceGroupManagerResizeRequestList", groupPath(g.zone, g.Name)+"/resizeRequests", + func(req *ResizeRequest) { seen(req.op) }), nil +} + +func finalState(verb string) *apiError { + return &apiError{Status: http.StatusPreconditionFailed, Reason: "conditionNotMet", Message: verb + " resize request that has reached a final state is not possible."} +} + +func (s *Server) cancelResizeRequest(r *http.Request, opFault *apiError) (any, *apiError) { + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + req, err := s.lookupRequest(r) + if err != nil { + return nil, err + } + switch req.State { + case resizeAccepted: + case resizeCreating: + return nil, &apiError{Status: http.StatusPreconditionFailed, Reason: "conditionNotMet", Message: "Cancelling resize request in state CREATING is not possible."} + default: + return nil, finalState("Cancelling") + } + if opFault == nil { + s.stopRequest(req) + req.State, req.Status = resizeCancelled, ResizeRequestStatus{} + } + return encoded(s.startOperation(r, reqID, "cancel", resizePath(req.group, req.Name), req.ID, opFault, nil)), nil +} + +func (s *Server) deleteResizeRequest(r *http.Request, opFault *apiError) (any, *apiError) { + reqID, err := requestID(r) + if err != nil { + return nil, err + } + s.mu.Lock() + defer s.mu.Unlock() + if op, ok := s.requests[reqID]; ok { + return encoded(op), nil + } + req, err := s.lookupRequest(r) + if err != nil { + return nil, err + } + if req.active() { + return nil, &apiError{Status: http.StatusPreconditionFailed, Reason: "conditionNotMet", Message: fmt.Sprintf("Deleting resize request in state %s is not possible. Only inactive resize requests can be deleted.", req.State)} + } + if opFault == nil { + req.group.requests.remove(req.Name) + } + return encoded(s.startOperation(r, reqID, "delete", resizePath(req.group, req.Name), req.ID, opFault, nil)), nil +} + +// resizeRequest returns the named resize request of a group. The caller holds s.mu. +func (s *Server) resizeRequest(project, zone, group, name string) (*ResizeRequest, *apiError) { + scope := "projects/" + project + "/zones/" + zone + g, ok := lookupIn(s.groups, scope, group) + if !ok { + return nil, notFound(groupPath(scope, group)) + } + req, ok := g.requests.byName[name] + if !ok { + return nil, notFound(resizePath(g, name)) + } + return req, nil +} + +// LookupResizeRequest returns the named resize request of the named group in +// project and zone. +func (s *Server) LookupResizeRequest(project, zone, group, name string) (ResizeRequest, bool) { + s.mu.Lock() + defer s.mu.Unlock() + req, err := s.resizeRequest(project, zone, group, name) + if err != nil { + return ResizeRequest{}, false + } + return jsonClone(req), true +} + +// FailResizeRequest ends the named resize request, which must be ACCEPTED or +// CREATING, in FAILED with an error of code and message in its status, as +// the API ends one it cannot fulfill, such as for want of quota. The +// instances it created are deleted. With no code and no message the status +// carries no error. +func (s *Server) FailResizeRequest(project, zone, group, name, code, message string) error { + s.mu.Lock() + defer s.mu.Unlock() + req, err := s.resizeRequest(project, zone, group, name) + if err != nil { + return err + } + if !req.active() { + return finalState("Failing") + } + s.failRequest(req, code, message) + return nil +} + +// FailResizeAttempt records a failed attempt at the named resize request, +// which must be ACCEPTED, in its status's lastAttempt, as a stockout does, +// and leaves it ACCEPTED to try again. +func (s *Server) FailResizeAttempt(project, zone, group, name, code, message string) error { + s.mu.Lock() + defer s.mu.Unlock() + req, err := s.resizeRequest(project, zone, group, name) + if err != nil { + return err + } + if req.State != resizeAccepted { + return &apiError{Status: http.StatusPreconditionFailed, Reason: "conditionNotMet", Message: fmt.Sprintf("The resize request is %s, not ACCEPTED.", req.State)} + } + req.Status.LastAttempt = &ResizeRequestAttempt{Error: OperationErrors{[]OperationError{{code, message}}}} + return nil +} diff --git a/gcp/compute/server.go b/gcp/compute/server.go index ef8a317..279ae33 100644 --- a/gcp/compute/server.go +++ b/gcp/compute/server.go @@ -12,14 +12,20 @@ // // - regional addresses: get, list, insert, delete, setLabels; // - zones: list, get; +// - accelerator types: aggregatedList, list, get; // - instances: bulkInsert, insert, get, list, aggregatedList, delete, stop, -// start, setLabels, setMachineType, addAccessConfig, attachDisk, -// detachDisk; +// start, suspend, resume, setLabels, setMachineType, addAccessConfig, +// attachDisk, detachDisk; +// - region instances: bulkInsert; // - disks: get, list, aggregatedList, insert, delete; // - snapshots: insert, get, list, delete; // - resource policies, on the beta API: list, get, insert, delete; // - instance templates: list, get, insert, delete; -// - instance group managers: aggregatedList, which is always empty; +// - zonal instance group managers: list, aggregatedList, get, insert, +// delete, createInstances, deleteInstances, listManagedInstances, +// setInstanceTemplate; +// - instance group manager resize requests: list, get, insert, cancel, +// delete; // - routes: list, get, insert, delete; // - networks: list, get, insert, delete; // - subnetworks: list, aggregatedList, get, insert, delete; @@ -35,8 +41,9 @@ // makes them returns, so the SDK's Operation.Wait returns at once. // [WithSettleAfter] holds them in progress, with their operation RUNNING, // for more reads or until [Server.Settle]: a new instance is PROVISIONING -// and then STAGING, a stopping or deleted one STOPPING, a starting one -// STAGING, a new snapshot CREATING and a deleted one DELETING. A +// and then STAGING, a stopping or deleted one STOPPING, a starting or +// resuming one STAGING, a suspending one SUSPENDING, a new snapshot +// CREATING and a deleted one DELETING. A // change to an instance that has another in progress finishes that one // first. Every other change finishes before its call returns. // - A call that repeats an earlier call's requestId in the same project, for @@ -54,8 +61,17 @@ // sourceDisk, storageLocations and labels are rejected. Machine and // disk types are any well-formed name, in the zone of the call; nothing // checks that they exist or fit together. +// - A disk is CREATING, READY or DELETING. One that is FAILED, as Compute +// Engine leaves a disk whose creation failed, is set up with +// [Server.PutDisk], since a fault that fails an insert's operation +// creates nothing. A FAILED disk can be read, listed and deleted, but not +// attached or snapshotted. // - Zones come from a fixed set per region, which [WithZones] changes. -// Regional calls take any region. +// Regional calls take any region, except a regional bulkInsert, which +// needs one with zones. Every zone offers the accelerator types +// nvidia-l4 and nvidia-tesla-t4, unless [WithAcceleratorTypes] says +// otherwise; a type the server has no description for is described by +// its name and takes up to 8 cards. // - Networks are custom mode only: an insert must set autoCreateSubnetworks // to false, and legacy and auto mode networks are rejected with 400. Each // network gets the default route to 0.0.0.0/0 the API creates with it, @@ -89,19 +105,60 @@ // either, and fields the server only // records, such as guestAccelerators or reservationAffinity, keep the // JSON the caller sent. Fields it does not know are rejected with 400. -// Instance group managers, deletion protection and resource policies -// other than group placement are not supported. +// Deletion protection and resource policies other than group placement +// are not supported. +// - A group creates each instance from its template as a bulk insertion +// would, and adds "created-by" and "instance-template" metadata naming +// the group and template by project ID. A createInstances or +// deleteInstances operation finishes at once while its instances are +// created or deleted in the background, which [WithSettleAfter] holds in +// progress as it holds any instance change; listManagedInstances then +// reports them CREATING or DELETING. An instance the template cannot +// make, such as one naming a resource policy that does not exist, stays a +// member, CREATING with no instance, whose lastAttempt holds the error. A +// createInstances naming an instance that exists in the zone, or a +// member, fails with 409 alreadyExists; one with a change in progress +// counts a read of it first. A group's targetSize is its number of +// members: an instance deleted other than through its group leaves it, +// and the group does not replace it. Deleting a group deletes its +// instances and resize requests, and deleting a template a group uses +// fails with 400 resourceInUseByAnotherResource. Groups are zonal only; +// versions, autohealing, target pools and stateful policies are +// rejected, and instanceLifecyclePolicy, resourcePolicies, updatePolicy, +// targetSizePolicy and namedPorts keep the JSON the caller sent, unchecked. +// - A resize request is ACCEPTED when its insert finishes, CREATING while +// its instances are created and SUCCEEDED once they run, all before the +// insert returns unless [WithSettleAfter] holds it: then each read of the +// request or its instances counts, it is CREATING on the last read in +// progress, and with a negative count it stays ACCEPTED until +// [Server.Settle]. A queued request makes no instances, and the group's +// targetSize grows when it does. A request naming an instance that exists, +// or one another ACCEPTED request names, fails in its operation with 400. +// Only an ACCEPTED request can be cancelled, and it stays CANCELLED until +// deleted; only a SUCCEEDED, FAILED or CANCELLED one can be deleted. +// Either call otherwise fails with 412 conditionNotMet, saying the request +// "has reached a final state" when it has. Capacity never runs out on its +// own: [Server.FailResizeRequest] ends a request in FAILED, deleting what +// it created, and [Server.FailResizeAttempt] records a failed attempt in +// its lastAttempt while it waits. requestedRunDuration is recorded, not +// enforced. // - A bulkInsert skips each instance whose name, or a disk it would // create, already exists, and creates the rest when they number at least // minCount: its operation succeeds, counting both in its // perLocationStatus, with no warning for what it skipped. With fewer, its // operation fails with VM_MIN_COUNT_NOT_REACHED and a // RESOURCE_ALREADY_EXISTS error per conflict and creates nothing. It -// takes no fixed IP addresses or disk names, as the API does not, and -// ignores locationPolicy. A name pattern numbers new names after the -// highest existing match. A disk created with an instance is named after -// it: the boot disk takes the instance's name, the others the instance's -// name and their index. +// takes no fixed IP addresses or disk names, as the API does not. A name +// pattern numbers new names after the highest existing match. A disk +// created with an instance is named after it: the boot disk takes the +// instance's name, the others the instance's name and their index. +// - A zonal bulkInsert ignores locationPolicy. A regional one places every +// instance in the first zone, in name order, that its locationPolicy does +// not deny, or with targetShape BALANCED spreads them across those zones +// in turn; it ignores location constraints, and does not weigh machine +// types, accelerators or capacity. Its names must be free in every zone of +// the region, and its name pattern numbers after the matches in all of +// them. // - IP addresses come from 100.64.0.0/10 (external) and 10.0.0.0/8 // (internal), never from routable ranges. An external address is unique // across every project and region; an internal one is unique within its @@ -119,9 +176,12 @@ // orderBy=creationTimestamp desc, is rejected with 400 rather than // ignored. An aggregatedList lists only the scopes that have items. // - A fault rule's Resource for an insert is the resource being created, so -// a rule can target the insert of one name. For a bulkInsert, it is the -// first instance it names in perInstanceProperties, or the zone's -// instances when it names none. +// a rule can target the insert of one name. For a bulkInsert, zonal or +// regional, it is the first instance it names in perInstanceProperties, +// such as "projects/p/regions/us-east1/instances/node-1", or the zone's or +// region's instances when it names none. For a group's createInstances, +// deleteInstances, setInstanceTemplate or listManagedInstances it is the +// group, and for a resize request's cancel the request. // // [WithPolicy] grants the caller a set of IAM permissions and refuses a call // that needs one it lacks with 403 forbidden, "Required '' @@ -176,10 +236,11 @@ type Server struct { policy *access.Policy now func() time.Time - settleAfter int - regionZones map[string][]string - zoneRegion map[string]string - zoneIDs map[string]uint64 + settleAfter int + regionZones map[string][]string + accelerators map[string][]string + zoneRegion map[string]string + zoneIDs map[string]uint64 mu sync.Mutex nextID uint64 @@ -197,6 +258,7 @@ type Server struct { snapshots map[string]*collection[*Snapshot] policies map[string]*collection[*ResourcePolicy] templates map[string]*collection[*InstanceTemplate] + groups map[string]*collection[*InstanceGroupManager] routes map[string]*collection[*Route] networks map[string]*collection[*Network] @@ -246,22 +308,24 @@ func WithZones(region string, zones ...string) Option { // New returns an empty server. func New(opts ...Option) *Server { s := &Server{ - mux: http.NewServeMux(), - now: time.Now, - regionZones: defaultZones(), - nextID: 1_000_000_000_000_000_000, - addresses: map[string]*collection[*Address]{}, - ipHolders: map[string]string{}, - operations: map[string]*operation{}, - requests: map[string]*operation{}, - pending: map[*operation]struct{}{}, - instances: map[string]*collection[*Instance]{}, - disks: map[string]*collection[*Disk]{}, - images: map[string]*Image{}, - snapshots: map[string]*collection[*Snapshot]{}, - policies: map[string]*collection[*ResourcePolicy]{}, - templates: map[string]*collection[*InstanceTemplate]{}, - routes: map[string]*collection[*Route]{}, + mux: http.NewServeMux(), + now: time.Now, + regionZones: defaultZones(), + accelerators: map[string][]string{}, + nextID: 1_000_000_000_000_000_000, + addresses: map[string]*collection[*Address]{}, + ipHolders: map[string]string{}, + operations: map[string]*operation{}, + requests: map[string]*operation{}, + pending: map[*operation]struct{}{}, + instances: map[string]*collection[*Instance]{}, + disks: map[string]*collection[*Disk]{}, + images: map[string]*Image{}, + snapshots: map[string]*collection[*Snapshot]{}, + policies: map[string]*collection[*ResourcePolicy]{}, + templates: map[string]*collection[*InstanceTemplate]{}, + groups: map[string]*collection[*InstanceGroupManager]{}, + routes: map[string]*collection[*Route]{}, networks: map[string]*collection[*Network]{}, subnetworks: map[string]*collection[*Subnetwork]{}, @@ -299,13 +363,18 @@ func (s *Server) registerRoutes() { s.route("GET "+project+"/zones", "compute.zones.list", "", s.listZones, nil) s.route("GET "+zone, "compute.zones.get", "", s.getZone, nil) + s.route("GET "+project+"/aggregated/acceleratorTypes", "compute.acceleratorTypes.aggregatedList", "", s.aggregatedAcceleratorTypes, nil) + s.route("GET "+zone+"/acceleratorTypes", "compute.acceleratorTypes.list", "", s.listAcceleratorTypes, nil) + s.route("GET "+zone+"/acceleratorTypes/{name}", "compute.acceleratorTypes.get", "", s.getAcceleratorType, nil) + s.route("POST "+zone+"/instances/bulkInsert", "compute.instances.bulkInsert", "/bulkInsert", s.bulkInsertInstances, withBulkTarget) + s.route("POST "+region+"/instances/bulkInsert", "compute.regionInstances.bulkInsert", "/bulkInsert", s.bulkInsertInstances, withBulkTarget) s.route("POST "+zone+"/instances", "compute.instances.insert", "", s.insertInstance, withNameFromBody) s.route("GET "+zone+"/instances", "compute.instances.list", "", s.listInstances, nil) s.route("GET "+project+"/aggregated/instances", "compute.instances.aggregatedList", "", s.aggregatedInstances, nil) s.route("GET "+zone+"/instances/{name}", "compute.instances.get", "", s.getInstance, nil) s.route("DELETE "+zone+"/instances/{name}", "compute.instances.delete", "", s.deleteInstance, nil) - for _, verb := range []string{"stop", "start", "setLabels", "setMachineType", "addAccessConfig", "attachDisk", "detachDisk"} { + for _, verb := range []string{"stop", "start", "suspend", "resume", "setLabels", "setMachineType", "addAccessConfig", "attachDisk", "detachDisk"} { s.route("POST "+zone+"/instances/{name}/"+verb, "compute.instances."+verb, "/"+verb, s.instanceVerb(verb), nil) } @@ -329,7 +398,26 @@ func (s *Server) registerRoutes() { s.route("POST "+global+"/instanceTemplates", "compute.instanceTemplates.insert", "", s.insertTemplate, withNameFromBody) s.route("GET "+global+"/instanceTemplates/{name}", "compute.instanceTemplates.get", "", s.getTemplate, nil) s.route("DELETE "+global+"/instanceTemplates/{name}", "compute.instanceTemplates.delete", "", s.deleteTemplate, nil) + + const ( + groups = zone + "/instanceGroupManagers" + resizes = groups + "/{group}/resizeRequests" + ) + s.route("GET "+groups, "compute.instanceGroupManagers.list", "", s.listGroupManagers, nil) s.route("GET "+project+"/aggregated/instanceGroupManagers", "compute.instanceGroupManagers.aggregatedList", "", s.aggregatedGroupManagers, nil) + s.route("POST "+groups, "compute.instanceGroupManagers.insert", "", s.insertGroupManager, withNameFromBody) + s.route("GET "+groups+"/{name}", "compute.instanceGroupManagers.get", "", s.getGroupManager, nil) + s.route("DELETE "+groups+"/{name}", "compute.instanceGroupManagers.delete", "", s.deleteGroupManager, nil) + s.route("POST "+groups+"/{name}/createInstances", "compute.instanceGroupManagers.createInstances", "/createInstances", s.createGroupInstances, nil) + s.route("POST "+groups+"/{name}/deleteInstances", "compute.instanceGroupManagers.deleteInstances", "/deleteInstances", s.deleteGroupInstances, nil) + s.route("POST "+groups+"/{name}/setInstanceTemplate", "compute.instanceGroupManagers.setInstanceTemplate", "/setInstanceTemplate", s.setGroupTemplate, nil) + s.route("POST "+groups+"/{name}/listManagedInstances", "compute.instanceGroupManagers.listManagedInstances", "/listManagedInstances", s.listManagedInstances, nil) + + s.route("GET "+resizes, "compute.instanceGroupManagerResizeRequests.list", "", s.listResizeRequests, nil) + s.route("POST "+resizes, "compute.instanceGroupManagerResizeRequests.insert", "", s.insertResizeRequest, withNameFromBody) + s.route("GET "+resizes+"/{name}", "compute.instanceGroupManagerResizeRequests.get", "", s.getResizeRequest, nil) + s.route("DELETE "+resizes+"/{name}", "compute.instanceGroupManagerResizeRequests.delete", "", s.deleteResizeRequest, nil) + s.route("POST "+resizes+"/{name}/cancel", "compute.instanceGroupManagerResizeRequests.cancel", "/cancel", s.cancelResizeRequest, nil) s.route("GET "+global+"/routes", "compute.routes.list", "", s.listRoutes, nil) s.route("POST "+global+"/routes", "compute.routes.insert", "", s.insertRoute, withNameFromBody) @@ -409,7 +497,7 @@ func withNameFromBody(r *http.Request, collection string) string { // route registers h for pattern as method. A non-nil target names the call's // resource from the request, in place of its path. func (s *Server) route(pattern, method, verb string, h handler, target func(*http.Request, string) string) { - startsOperation := !strings.HasPrefix(pattern, http.MethodGet+" ") && verb != "/wait" + startsOperation := !strings.HasPrefix(pattern, http.MethodGet+" ") && verb != "/wait" && verb != "/listManagedInstances" s.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { resource := strings.TrimSuffix(resourcePath(r), verb) if target != nil { diff --git a/gcp/lustre/server.go b/gcp/lustre/server.go index e13828b..d5b4bb7 100644 --- a/gcp/lustre/server.go +++ b/gcp/lustre/server.go @@ -563,7 +563,7 @@ func unimplemented(r *http.Request) *apiError { func faultError(f fault.Fault) *apiError { return &apiError{ Status: cmp.Or(f.Status, http.StatusServiceUnavailable), - Message: fmt.Sprintf("squall: injected fault (%s)", f), + Message: f.ErrorMessage(), Reason: reason.UpperSnake(f.Reason), Domain: "lustre.googleapis.com", } diff --git a/gcp/resourcemanager/errors.go b/gcp/resourcemanager/errors.go index a87197f..75bca04 100644 --- a/gcp/resourcemanager/errors.go +++ b/gcp/resourcemanager/errors.go @@ -43,7 +43,7 @@ func aborted() *apiError { func faultError(f fault.Fault) *apiError { return &apiError{ Status: cmp.Or(f.Status, http.StatusServiceUnavailable), - Message: fmt.Sprintf("squall: injected fault (%s)", f), + Message: f.ErrorMessage(), Reason: reason.UpperSnake(f.Reason), Domain: service, } diff --git a/gcp/servicenetworking/errors.go b/gcp/servicenetworking/errors.go index ae84bd1..48a1817 100644 --- a/gcp/servicenetworking/errors.go +++ b/gcp/servicenetworking/errors.go @@ -44,7 +44,7 @@ func unimplemented(r *http.Request) *apiError { func faultError(f fault.Fault) *apiError { return &apiError{ Status: cmp.Or(f.Status, http.StatusServiceUnavailable), - Message: fmt.Sprintf("squall: injected fault (%s)", f), + Message: f.ErrorMessage(), Reason: reason.UpperSnake(f.Reason), Domain: service, } diff --git a/gcp/serviceusage/errors.go b/gcp/serviceusage/errors.go index 696e739..0d01410 100644 --- a/gcp/serviceusage/errors.go +++ b/gcp/serviceusage/errors.go @@ -62,7 +62,7 @@ func permissionDenied(perm, action string) *apiError { func faultError(f fault.Fault) *apiError { return &apiError{ Status: cmp.Or(f.Status, http.StatusServiceUnavailable), - Message: fmt.Sprintf("squall: injected fault (%s)", f), + Message: f.ErrorMessage(), Reason: reason.UpperSnake(f.Reason), } } diff --git a/gcp/storage/server.go b/gcp/storage/server.go index d7d2515..86c7921 100644 --- a/gcp/storage/server.go +++ b/gcp/storage/server.go @@ -538,7 +538,7 @@ func conditionNotMet() *apiError { func faultError(f fault.Fault) *apiError { status := cmp.Or(f.Status, http.StatusServiceUnavailable) - return &apiError{Status: status, Reason: cmp.Or(f.Reason, "backendError"), Message: fmt.Sprintf("squall: injected fault (%s)", f)} + return &apiError{Status: status, Reason: cmp.Or(f.Reason, "backendError"), Message: f.ErrorMessage()} } type errorBody struct { diff --git a/sdktest/azure/arm/arm_test.go b/sdktest/azure/arm/arm_test.go index 4c9cea1..2c6d535 100644 --- a/sdktest/azure/arm/arm_test.go +++ b/sdktest/azure/arm/arm_test.go @@ -561,3 +561,65 @@ func TestResourceSKUsListNone(t *testing.T) { t.Fatalf("skus = %v, %v", page.Value, err) } } + +func TestResourceSKUs(t *testing.T) { + c := setup(t, arm.WithResourceSKUs( + arm.ResourceSKU{ + Name: "Standard_D2s_v5", Tier: "Standard", Size: "D2s_v5", Family: "standardDSv5Family", Location: "East US", Zones: []string{"1", "2", "3"}, + Capabilities: map[string]string{"vCPUs": "2", "AcceleratedNetworkingEnabled": "True"}, + Restrictions: []arm.SKURestriction{{Zones: []string{"3"}, ReasonCode: "NotAvailableForSubscription"}}, + }, + arm.ResourceSKU{ + Name: "Standard_D2s_v5", Location: "westus", Capabilities: map[string]string{"AcceleratedNetworkingEnabled": "True"}, + Restrictions: []arm.SKURestriction{{ReasonCode: "QuotaId"}}, + }, + arm.ResourceSKU{ResourceType: "disks", Name: "Premium_LRS", Tier: "Premium", Location: "eastus"}, + )) + list := func(filter *string) ([]*armcompute.ResourceSKU, error) { + var out []*armcompute.ResourceSKU + pager := c.skus.NewListPager(&armcompute.ResourceSKUsClientListOptions{Filter: filter, IncludeExtendedLocations: new("true")}) + for pager.More() { + page, err := pager.NextPage(t.Context()) + if err != nil { + return nil, err + } + out = append(out, page.Value...) + } + return out, nil + } + all, err := list(nil) + if err != nil || len(all) != 3 { + t.Fatalf("all skus = %v, %v", all, err) + } + eastus, err := list(new("location eq 'eastus'")) + if err != nil || len(eastus) != 2 || *eastus[0].Name != "Standard_D2s_v5" || *eastus[1].ResourceType != "disks" { + t.Fatalf("skus in eastus = %v, %v", eastus, err) + } + vm := eastus[0] + if *vm.ResourceType != "virtualMachines" || *vm.Tier != "Standard" || *vm.Size != "D2s_v5" || *vm.Family != "standardDSv5Family" || + len(vm.Locations) != 1 || *vm.Locations[0] != "eastus" || *vm.LocationInfo[0].Location != "eastus" || len(vm.LocationInfo[0].Zones) != 3 { + t.Fatalf("vm size = %+v", vm) + } + if len(vm.Capabilities) != 2 || *vm.Capabilities[0].Name != "AcceleratedNetworkingEnabled" || *vm.Capabilities[0].Value != "True" || + *vm.Capabilities[1].Name != "vCPUs" || *vm.Capabilities[1].Value != "2" { + t.Fatalf("capabilities = %+v", vm.Capabilities) + } + r := vm.Restrictions + if len(r) != 1 || *r[0].Type != armcompute.ResourceSKURestrictionsTypeZone || *r[0].ReasonCode != armcompute.ResourceSKURestrictionsReasonCodeNotAvailableForSubscription || + *r[0].Values[0] != "eastus" || *r[0].RestrictionInfo.Locations[0] != "eastus" || *r[0].RestrictionInfo.Zones[0] != "3" { + t.Fatalf("zone restriction = %+v", r) + } + westus, err := list(new("location eq 'WestUS'")) + if err != nil || len(westus) != 1 { + t.Fatalf("skus in westus = %v, %v", westus, err) + } + if r := westus[0].Restrictions; len(r) != 1 || *r[0].Type != armcompute.ResourceSKURestrictionsTypeLocation || + *r[0].ReasonCode != armcompute.ResourceSKURestrictionsReasonCodeQuotaID || r[0].RestrictionInfo.Zones != nil { + t.Fatalf("location restriction = %+v", r) + } + for _, f := range []string{"name eq 'Standard_D2s_v5'", "location eq 'eastus' and name eq 'x'"} { + if _, err := list(new(f)); status(err) != http.StatusBadRequest { + t.Errorf("filter %q = %v", f, err) + } + } +} diff --git a/sdktest/azure/arm/compute_test.go b/sdktest/azure/arm/compute_test.go index c6ece41..6bb0eba 100644 --- a/sdktest/azure/arm/compute_test.go +++ b/sdktest/azure/arm/compute_test.go @@ -259,10 +259,21 @@ func TestVirtualMachineFailedOperation(t *testing.T) { if _, err := p.PollUntilDone(t.Context(), nil); code(err) != "AllocationFailed" { t.Fatalf("failed create = %v", err) } - if got := c.server.VirtualMachines(); len(got) != 0 { - t.Fatalf("a failed create took effect: %+v", got) + if got := c.server.VirtualMachines(); len(got) != 1 || got[0].ProvisioningState != "Failed" || got[0].PowerState != "" { + t.Fatalf("after a failed create = %+v", got) + } + if got, err := c.vms.Get(t.Context(), group, "vm", nil); err != nil || *got.Properties.ProvisioningState != "Failed" { + t.Fatalf("failed vm = %+v, %v", got.Properties, err) + } + view, err := c.vms.InstanceView(t.Context(), group, "vm", nil) + if err != nil || len(view.Statuses) != 1 || *view.Statuses[0].Code != "ProvisioningState/failed/AllocationFailed" || + *view.Statuses[0].Level != armcompute.StatusLevelTypesError || *view.Statuses[0].DisplayStatus != "Provisioning failed" { + t.Fatalf("failed vm's instance view = %+v, %v", view.Statuses, err) } vm := c.createVM(t, "vm", nic) + if view, err := c.vms.InstanceView(t.Context(), group, "vm", nil); err != nil || powerState(view.Statuses) != "running" { + t.Fatalf("recreated vm's instance view = %+v, %v", view.Statuses, err) + } sp, err := c.vms.BeginStart(t.Context(), group, "vm", nil) if _, err = wait(t, sp, err); code(err) != "InternalServerError" { t.Fatalf("failed start = %v", err) @@ -357,3 +368,80 @@ func TestVirtualMachineChangePreemptsTheOneInProgress(t *testing.T) { t.Fatalf("VMs = %+v", got) } } + +func TestVirtualMachinePowerOff(t *testing.T) { + c := setup(t, arm.WithSettleAfter(1)) + c.createGroup(t, group, nil) + nic := c.createNIC(t, group, "nic", nil) + c.createVM(t, "vm", nic) + p, err := c.vms.BeginPowerOff(t.Context(), group, "vm", &armcompute.VirtualMachinesClientBeginPowerOffOptions{SkipShutdown: new(true)}) + if err != nil || p.Done() { + t.Fatalf("begin power off = %v", err) + } + if view, err := c.vms.InstanceView(t.Context(), group, "vm", nil); err != nil || powerState(view.Statuses) != "stopping" { + t.Fatalf("while powering off = %+v, %v", view.Statuses, err) + } + if _, err := p.PollUntilDone(t.Context(), nil); err != nil { + t.Fatal(err) + } + view, err := c.vms.InstanceView(t.Context(), group, "vm", nil) + if err != nil || powerState(view.Statuses) != "stopped" || *view.Statuses[len(view.Statuses)-1].DisplayStatus != "VM stopped" { + t.Fatalf("after power off = %+v, %v", view.Statuses, err) + } + if got := c.server.Disks(); len(got) != 1 || got[0].State != "Attached" { + t.Fatalf("a stopped VM's disk = %+v", got) + } + sp, err := c.vms.BeginStart(t.Context(), group, "vm", nil) + if _, err = wait(t, sp, err); err != nil { + t.Fatal(err) + } + if got := c.server.VirtualMachines(); got[0].PowerState != "running" { + t.Fatalf("after start = %+v", got) + } +} + +func TestVirtualMachineSecretsDoNotChange(t *testing.T) { + c := setup(t) + c.createGroup(t, group, nil) + nic := c.createNIC(t, group, "nic", nil) + linux := func(customData *string, key string) armcompute.VirtualMachine { + vm := vmBody(nic.ID) + vm.Properties.OSProfile.CustomData = customData + vm.Properties.OSProfile.LinuxConfiguration = &armcompute.LinuxConfiguration{SSH: &armcompute.SSHConfiguration{ + PublicKeys: []*armcompute.SSHPublicKey{{KeyData: new(key), Path: new("/home/azureuser/.ssh/authorized_keys")}}, + }} + return vm + } + put := func(vm armcompute.VirtualMachine) error { + p, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm", vm, nil) + _, err = wait(t, p, err) + return err + } + if err := put(linux(new("Y2xvdWQtaW5pdA=="), "ssh-rsa AAAA")); err != nil { + t.Fatal(err) + } + for name, tc := range map[string]struct { + vm armcompute.VirtualMachine + target string + }{ + "customData": {linux(new("b3RoZXI="), "ssh-rsa AAAA"), "customData"}, + "ssh key": {linux(new("Y2xvdWQtaW5pdA=="), "ssh-rsa BBBB"), "linuxConfiguration.ssh.publicKeys"}, + } { + err := put(tc.vm) + if code(err) != "PropertyChangeNotAllowed" || status(err) != http.StatusConflict || + !strings.Contains(err.Error(), "Changing property '"+tc.target+"' is not allowed.") { + t.Errorf("changing the %s = %v", name, err) + } + } + got, err := c.vms.Get(t.Context(), group, "vm", nil) + if err != nil || got.Properties.OSProfile.CustomData != nil { + t.Fatalf("get = %+v, %v", got.Properties.OSProfile, err) + } + got.Properties.OSProfile.AdminPassword = nil + if err := put(got.VirtualMachine); err != nil { + t.Fatalf("putting back what a get read = %v", err) + } + if err := put(linux(new("Y2xvdWQtaW5pdA=="), "ssh-rsa AAAA")); err != nil { + t.Fatalf("putting the same secrets again = %v", err) + } +} diff --git a/sdktest/azure/arm/datadisks_test.go b/sdktest/azure/arm/datadisks_test.go new file mode 100644 index 0000000..f3f1dc3 --- /dev/null +++ b/sdktest/azure/arm/datadisks_test.go @@ -0,0 +1,235 @@ +package arm_test + +import ( + "net/http" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v8" + + "github.com/parallelworks/squall/azure/arm" + "github.com/parallelworks/squall/fault" +) + +const dataGroup = "data" + +func (c *clients) dataDisk(t *testing.T, name string) string { + t.Helper() + p, err := c.disks.BeginCreateOrUpdate(t.Context(), dataGroup, name, diskBody(location, 16), nil) + res, err := wait(t, p, err) + if err != nil { + t.Fatal(err) + } + return *res.ID +} + +func attach(lun int32, id string) *armcompute.DataDisk { + return &armcompute.DataDisk{ + Lun: new(lun), CreateOption: new(armcompute.DiskCreateOptionTypesAttach), ManagedDisk: &armcompute.ManagedDiskParameters{ID: new(id)}, + } +} + +func (c *clients) updateDisks(t *testing.T, vm string, disks []*armcompute.DataDisk) (armcompute.VirtualMachine, error) { + t.Helper() + got, err := c.vms.Get(t.Context(), group, vm, nil) + if err != nil { + t.Fatal(err) + } + got.Properties.StorageProfile.DataDisks = disks + p, err := c.vms.BeginUpdate(t.Context(), group, vm, armcompute.VirtualMachineUpdate{ + Properties: &armcompute.VirtualMachineProperties{StorageProfile: got.Properties.StorageProfile}, + }, nil) + res, err := wait(t, p, err) + return res.VirtualMachine, err +} + +func (c *clients) holder(t *testing.T, id string) string { + t.Helper() + for _, d := range c.server.Disks() { + if d.ID == id { + return d.VirtualMachine + } + } + t.Fatalf("no disk %s", id) + return "" +} + +func TestVirtualMachineDataDisks(t *testing.T) { + var now time.Time + c := setup(t, arm.WithClock(func() time.Time { return now })) + now = time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + c.createGroup(t, group, nil) + c.createGroup(t, dataGroup, nil) + scratch, logs := c.dataDisk(t, "scratch"), c.dataDisk(t, "logs") + body := vmBody(c.createNIC(t, group, "nic-1", nil).ID) + body.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{attach(0, scratch)} + p, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-1", body, nil) + created, err := wait(t, p, err) + if err != nil { + t.Fatal(err) + } + listed := created.Properties.StorageProfile.DataDisks + if len(listed) != 1 || *listed[0].Name != "scratch" || *listed[0].Lun != 0 || *listed[0].DiskSizeGB != 16 || *listed[0].ToBeDetached || + *listed[0].DeleteOption != armcompute.DiskDeleteOptionTypesDetach || *listed[0].ManagedDisk.ID != scratch { + t.Fatalf("data disks = %+v", listed) + } + disk, err := c.disks.Get(t.Context(), dataGroup, "scratch", nil) + if err != nil || *disk.ManagedBy != *created.ID || *disk.Properties.DiskState != armcompute.DiskStateAttached || + !disk.Properties.LastOwnershipUpdateTime.Equal(now) { + t.Fatalf("attached disk = %+v, %v", disk, err) + } + dp, err := c.disks.BeginDelete(t.Context(), dataGroup, "scratch", nil) + if _, err = wait(t, dp, err); code(err) != "OperationNotAllowed" || status(err) != http.StatusConflict { + t.Fatalf("deleting an attached data disk = %v", err) + } + other := vmBody(c.createNIC(t, group, "nic-2", nil).ID) + other.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{attach(0, scratch)} + if _, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-2", other, nil); code(err) != "OperationNotAllowed" || status(err) != http.StatusConflict { + t.Fatalf("attaching a disk another VM holds = %v", err) + } + + now = now.Add(time.Hour) + updated, err := c.updateDisks(t, "vm-1", append(listed, attach(1, logs))) + if err != nil || len(updated.Properties.StorageProfile.DataDisks) != 2 || c.holder(t, logs) != *created.ID { + t.Fatalf("attaching with PATCH = %+v, %v", updated.Properties.StorageProfile.DataDisks, err) + } + now = now.Add(time.Hour) + updated, err = c.updateDisks(t, "vm-1", updated.Properties.StorageProfile.DataDisks[1:]) + if err != nil || len(updated.Properties.StorageProfile.DataDisks) != 1 || c.holder(t, scratch) != "" || c.holder(t, logs) != *created.ID { + t.Fatalf("detaching by leaving the disk out = %+v, %v", updated.Properties.StorageProfile.DataDisks, err) + } + disk, err = c.disks.Get(t.Context(), dataGroup, "scratch", nil) + if err != nil || disk.ManagedBy != nil || *disk.Properties.DiskState != armcompute.DiskStateUnattached || !disk.Properties.LastOwnershipUpdateTime.Equal(now) { + t.Fatalf("detached disk = %+v, %v", disk, err) + } + marked := updated.Properties.StorageProfile.DataDisks + marked[0].ToBeDetached = new(true) + updated, err = c.updateDisks(t, "vm-1", marked) + if err != nil || len(updated.Properties.StorageProfile.DataDisks) != 0 || c.holder(t, logs) != "" { + t.Fatalf("detaching with toBeDetached = %+v, %v", updated.Properties.StorageProfile.DataDisks, err) + } + + for name, tc := range map[string]struct { + disks []*armcompute.DataDisk + code string + }{ + "two disks at one lun": {[]*armcompute.DataDisk{attach(2, scratch), attach(2, logs)}, "InvalidParameter"}, + "a lun past 63": {[]*armcompute.DataDisk{attach(64, scratch)}, "InvalidParameter"}, + "no lun": {[]*armcompute.DataDisk{{CreateOption: new(armcompute.DiskCreateOptionTypesAttach), ManagedDisk: &armcompute.ManagedDiskParameters{ID: new(scratch)}}}, "InvalidParameter"}, + "an empty disk": {[]*armcompute.DataDisk{{Lun: new(int32(0)), CreateOption: new(armcompute.DiskCreateOptionTypesEmpty), DiskSizeGB: new(int32(8))}}, "BadRequest"}, + } { + if _, err := c.updateDisks(t, "vm-1", tc.disks); code(err) != tc.code || status(err) != http.StatusBadRequest { + t.Errorf("%s = %v, want %s", name, err, tc.code) + } + } + if c.holder(t, scratch) != "" || c.holder(t, logs) != "" { + t.Fatal("a refused update attached a disk") + } +} + +func TestVirtualMachineUpdate(t *testing.T) { + c := setup(t, arm.WithSettleAfter(1)) + c.createGroup(t, group, nil) + c.createGroup(t, dataGroup, nil) + scratch := c.dataDisk(t, "scratch") + body := vmBody(c.createNIC(t, group, "nic-1", nil).ID) + body.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{attach(0, scratch)} + p, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-1", body, nil) + if _, err = wait(t, p, err); err != nil { + t.Fatal(err) + } + up, err := c.vms.BeginUpdate(t.Context(), group, "vm-1", armcompute.VirtualMachineUpdate{Tags: map[string]*string{"team": new("a")}}, nil) + if err != nil || up.Done() { + t.Fatalf("an update in progress = %v", err) + } + updated, err := up.PollUntilDone(t.Context(), nil) + if err != nil || *updated.Tags["team"] != "a" || len(updated.Properties.StorageProfile.DataDisks) != 1 || *updated.Properties.ProvisioningState != "Succeeded" { + t.Fatalf("a tags update = %+v, %v", updated, err) + } + if c.holder(t, scratch) != *updated.ID { + t.Fatal("an update that leaves out dataDisks detached one") + } + + body.Properties.StorageProfile.DataDisks = nil + p, err = c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-1", body, nil) + put, err := wait(t, p, err) + if err != nil || len(put.Properties.StorageProfile.DataDisks) != 1 || c.holder(t, scratch) != *updated.ID { + t.Fatalf("a PUT that leaves out dataDisks = %+v, %v", put.Properties.StorageProfile.DataDisks, err) + } + + resize := armcompute.VirtualMachineUpdate{Properties: &armcompute.VirtualMachineProperties{ + HardwareProfile: &armcompute.HardwareProfile{VMSize: new(armcompute.VirtualMachineSizeTypes("Standard_D4s_v5"))}, + }} + if _, err := c.vms.BeginUpdate(t.Context(), group, "vm-1", resize, nil); code(err) != "BadRequest" { + t.Fatalf("a resize with PATCH = %v", err) + } + renamed := armcompute.VirtualMachineUpdate{Properties: &armcompute.VirtualMachineProperties{StorageProfile: &armcompute.StorageProfile{ + OSDisk: &armcompute.OSDisk{Name: new("other")}, + }}} + if _, err := c.vms.BeginUpdate(t.Context(), group, "vm-1", renamed, nil); code(err) != "PropertyChangeNotAllowed" || status(err) != http.StatusConflict { + t.Fatalf("renaming the OS disk with PATCH = %v", err) + } + if _, err := c.vms.BeginUpdate(t.Context(), group, "missing", armcompute.VirtualMachineUpdate{Tags: map[string]*string{}}, nil); code(err) != "ResourceNotFound" { + t.Fatalf("updating a missing VM = %v", err) + } +} + +func TestVirtualMachineUpdateFaults(t *testing.T) { + faults := fault.New() + c := setupRetrying(t, arm.WithFaults(faults)) + c.createGroup(t, group, nil) + c.createGroup(t, dataGroup, nil) + scratch := c.dataDisk(t, "scratch") + body := vmBody(c.createNIC(t, group, "nic-1", nil).ID) + body.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{attach(0, scratch)} + p, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-1", body, nil) + vm, err := wait(t, p, err) + if err != nil { + t.Fatal(err) + } + failed := fault.FailOperation(http.StatusConflict) + failed.Reason = "OperationNotAllowed" + faults.Add(fault.Rule{Method: "Microsoft.Compute/virtualMachines/write", Times: 1, Fault: failed}) + if _, err := c.updateDisks(t, "vm-1", []*armcompute.DataDisk{}); code(err) != "OperationNotAllowed" || c.holder(t, scratch) != *vm.ID { + t.Fatalf("a detach whose operation failed = %v, held by %q", err, c.holder(t, scratch)) + } + refused := fault.FailAfter(http.StatusConflict) + refused.Reason = "Conflict" + faults.Add(fault.Rule{Method: "Microsoft.Compute/virtualMachines/write", Times: 1, Fault: refused}) + if _, err := c.updateDisks(t, "vm-1", []*armcompute.DataDisk{}); code(err) != "Conflict" || c.holder(t, scratch) != "" { + t.Fatalf("a detach that failed after taking effect = %v, held by %q", err, c.holder(t, scratch)) + } +} + +func TestDeletingDataDisksWithTheirVM(t *testing.T) { + c := setup(t) + c.createGroup(t, group, nil) + c.createGroup(t, dataGroup, nil) + kept, gone := c.dataDisk(t, "kept"), c.dataDisk(t, "gone") + body := vmBody(c.createNIC(t, group, "nic-1", nil).ID) + deleted := attach(1, gone) + deleted.DeleteOption = new(armcompute.DiskDeleteOptionTypesDelete) + body.Properties.StorageProfile.DataDisks = []*armcompute.DataDisk{attach(0, kept), deleted} + p, err := c.vms.BeginCreateOrUpdate(t.Context(), group, "vm-1", body, nil) + if _, err = wait(t, p, err); err != nil { + t.Fatal(err) + } + gp, err := c.groups.BeginDelete(t.Context(), dataGroup, nil) + if _, err = wait(t, gp, err); code(err) != "ResourceGroupDeletionBlocked" { + t.Fatalf("deleting a group whose disks a VM elsewhere holds = %v", err) + } + if len(c.server.Disks()) != 3 { + t.Fatalf("Disks() after a blocked group delete = %+v", c.server.Disks()) + } + vp, err := c.vms.BeginDelete(t.Context(), group, "vm-1", nil) + if _, err = wait(t, vp, err); err != nil { + t.Fatal(err) + } + if disks := c.server.Disks(); len(disks) != 1 || disks[0].ID != kept || disks[0].State != "Unattached" { + t.Fatalf("Disks() after deleting the VM = %+v", disks) + } + gp, err = c.groups.BeginDelete(t.Context(), dataGroup, nil) + if _, err = wait(t, gp, err); err != nil { + t.Fatalf("deleting the group once its disks are free = %v", err) + } +} diff --git a/sdktest/azure/arm/lustre_test.go b/sdktest/azure/arm/lustre_test.go index d354d71..ec6d2e0 100644 --- a/sdktest/azure/arm/lustre_test.go +++ b/sdktest/azure/arm/lustre_test.go @@ -1,12 +1,14 @@ package arm_test import ( + "errors" "net/http" "net/netip" "strings" "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storagecache/armstoragecache/v3" @@ -169,3 +171,33 @@ func TestManagedLustrePollingNeedsAscOperations(t *testing.T) { t.Fatalf("polling without %s = %v", poll, err) } } + +func TestFailSubnetCheck(t *testing.T) { + c := setup(t) + check := func() error { + _, err := c.cache.CheckAmlFSSubnets(t.Context(), &armstoragecache.ManagementClientCheckAmlFSSubnetsOptions{ + AmlFilesystemSubnetInfo: &armstoragecache.AmlFilesystemSubnetInfo{ + FilesystemSubnet: new(subnet), Location: new(location), SKU: &armstoragecache.SKUName{Name: new("AMLFS-Durable-Premium-250")}, + StorageCapacityTiB: new(float32(16)), + }, + }) + return err + } + const reason = "Subnet has 12 available IPs; 16 are required for this AML file system." + c.server.FailSubnetCheck(strings.ToUpper(subnet), reason) + err := check() + respErr, ok := errors.AsType[*azcore.ResponseError](err) + if !ok || respErr.StatusCode != http.StatusBadRequest || respErr.RawResponse.Header.Get("x-ms-error-code") != "" { + t.Fatalf("a failed subnet check = %v", err) + } + var body struct { + FilesystemSubnet struct{ Status, Message string } `json:"filesystemSubnet"` + } + if err := runtime.UnmarshalAsJSON(respErr.RawResponse, &body); err != nil || body.FilesystemSubnet.Status != "Invalid" || body.FilesystemSubnet.Message != reason { + t.Fatalf("a failed subnet check's body = %+v, %v", body, err) + } + c.server.FailSubnetCheck(subnet, "") + if err := check(); err != nil { + t.Fatalf("a subnet check let pass again = %v", err) + } +} diff --git a/sdktest/azure/arm/openai_test.go b/sdktest/azure/arm/openai_test.go new file mode 100644 index 0000000..fb87189 --- /dev/null +++ b/sdktest/azure/arm/openai_test.go @@ -0,0 +1,180 @@ +package arm_test + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/operationalinsights/armoperationalinsights/v3" + + "github.com/parallelworks/squall/azure/arm" + "github.com/parallelworks/squall/fault" +) + +// openAI creates an AIServices account with the subdomain domain and returns +// a client of its Azure OpenAI data plane that sends its second key. +func (c *clients) openAI(t *testing.T, name, domain string) *rest { + t.Helper() + c.createGroup(t, group, nil) + c.createCognitiveAccount(t, name, domain) + keys, err := c.cognitive.ListKeys(t.Context(), group, name, nil) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(c.server.OpenAI()) + t.Cleanup(srv.Close) + return &rest{t: t, base: srv.URL + "/" + domain + "/openai", key: *keys.Key2, version: "2024-05-01-preview"} +} + +func ingestionJob() map[string]any { + return map[string]any{ + "kind": "SystemCompute", + "searchServiceConnection": map[string]any{ + "kind": "EndpointWithKey", "endpoint": "https://find.search.windows.net", "key": "k", + }, + "datasource": map[string]any{ + "kind": "Storage", "connection": map[string]any{"kind": "ConnectionString", "connectionString": "c"}, "containerName": "docs", + "chunking": map[string]any{"maxChunkSizeInTokens": 1024}, + "embeddings": []any{map[string]any{"connection": map[string]any{"kind": "RelativeConnection"}, "deploymentName": "ada"}}, + }, + "dataRefreshIntervalInHours": 24, + "completionAction": "keepAllAssets", + } +} + +func TestIngestionJobs(t *testing.T) { + c := setup(t, arm.WithSettleAfter(1)) + api := c.openAI(t, "ai", "ai-sub") + status, got := api.do("PUT", "/ingestion/jobs/nightly", ingestionJob()) + if status != http.StatusOK || got["jobId"] != "nightly" || got["status"] != "running" || got["completionAction"] != "keepAllAssets" { + t.Fatalf("create = %d %v", status, got) + } + if _, got := api.do("GET", "/ingestion/jobs/nightly", nil); got["status"] != "running" { + t.Fatalf("a job's first read = %v", got) + } + if status, got := api.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusOK || got["status"] != "succeeded" { + t.Fatalf("a job after its reads = %d %v", status, got) + } + api.do("PUT", "/ingestion/jobs/nightly", ingestionJob()) + c.server.Settle() + if _, got := api.do("GET", "/ingestion/jobs/nightly", nil); got["status"] != "succeeded" { + t.Fatalf("a settled job = %v", got) + } + if status, got := api.do("GET", "/ingestion/jobs/weekly", nil); status != http.StatusNotFound { + t.Fatalf("a job that does not exist = %d %v", status, got) + } + for name, body := range map[string]map[string]any{ + "no kind": {"datasource": map[string]any{}}, + "no search connection": {"kind": "SystemCompute", "datasource": map[string]any{}}, + "an unknown member": {"kind": "SystemCompute", "colour": "red"}, + "a bad action": {"kind": "SystemCompute", "searchServiceConnection": map[string]any{}, "datasource": map[string]any{}, "completionAction": "x"}, + } { + if status, _ := api.do("PUT", "/ingestion/jobs/bad", body); status != http.StatusBadRequest { + t.Fatalf("a job with %s = %d", name, status) + } + } +} + +func TestIngestionJobAuthentication(t *testing.T) { + c := setup(t) + api := c.openAI(t, "ai", "ai-sub") + keys, err := c.cognitive.ListKeys(t.Context(), group, "ai", nil) + if err != nil { + t.Fatal(err) + } + api.key = *keys.Key1 + if status, _ := api.do("PUT", "/ingestion/jobs/nightly", ingestionJob()); status != http.StatusOK { + t.Fatalf("the first key = %d", status) + } + api.key = "wrong" + if status, got := api.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusUnauthorized || + !strings.HasPrefix(errorMessage(got), "Access denied due to invalid subscription key") { + t.Fatalf("a wrong key = %d %v", status, got) + } + api.key = "" + if status, got := api.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusUnauthorized || + !strings.HasPrefix(errorMessage(got), "Access denied due to missing subscription key") { + t.Fatalf("no key = %d %v", status, got) + } + api.key, api.version = *keys.Key1, "" + if status, _ := api.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusNotFound { + t.Fatalf("no api-version = %d", status) + } + api.version = "2024-05-01-preview" + + p, err := c.cognitive.BeginCreate(t.Context(), group, "speech", armcognitiveservices.Account{ + Location: new(location), Kind: new("SpeechServices"), SKU: &armcognitiveservices.SKU{Name: new("S0")}, + Properties: &armcognitiveservices.AccountProperties{CustomSubDomainName: new("speech-sub")}, + }, nil) + if _, err := wait(t, p, err); err != nil { + t.Fatal(err) + } + speechKeys, err := c.cognitive.ListKeys(t.Context(), group, "speech", nil) + if err != nil { + t.Fatal(err) + } + speech := &rest{t: t, base: strings.Replace(api.base, "/ai-sub/", "/speech-sub/", 1), key: *speechKeys.Key1, version: api.version} + if status, _ := speech.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusNotFound { + t.Fatalf("an account of another kind = %d", status) + } + + if _, err := c.cognitive.BeginDelete(t.Context(), group, "ai", nil); err != nil { + t.Fatal(err) + } + if status, _ := api.do("GET", "/ingestion/jobs/nightly", nil); status != http.StatusNotFound { + t.Fatalf("a deleted account = %d", status) + } +} + +func TestIngestionJobFaults(t *testing.T) { + faults := fault.New() + c := setup(t, arm.WithFaults(faults), arm.WithSettleAfter(-1)) + api := c.openAI(t, "ai", "ai-sub") + faults.Add( + fault.Rule{Method: "IngestionJobs_Create", Resource: "ai-sub/ingestion/jobs/broken", Fault: fault.FailOperation(http.StatusBadRequest).WithMessage("The container is empty.")}, + fault.Rule{Method: "IngestionJobs_Create", Resource: "ai-sub/ingestion/jobs/refused", Fault: fault.Reject(http.StatusBadRequest, "BadRequest")}, + fault.Rule{Method: "IngestionJobs_Get", Times: 1, Fault: fault.Unavailable()}, + ) + if status, got := api.do("PUT", "/ingestion/jobs/broken", ingestionJob()); status != http.StatusOK || got["status"] != "failed" || + got["error"].(map[string]any)["message"] != "The container is empty." { + t.Fatalf("a job that fails = %d %v", status, got) + } + if status, got := api.do("PUT", "/ingestion/jobs/refused", ingestionJob()); status != http.StatusBadRequest || got["error"].(map[string]any)["code"] != "BadRequest" { + t.Fatalf("a refused job = %d %v", status, got) + } + api.do("PUT", "/ingestion/jobs/held", ingestionJob()) + if status, got := api.do("GET", "/ingestion/jobs/held", nil); status != http.StatusServiceUnavailable || got["error"].(map[string]any)["code"] != "503" { + t.Fatalf("a faulted get = %d %v", status, got) + } + for range 3 { + if _, got := api.do("GET", "/ingestion/jobs/held", nil); got["status"] != "running" { + t.Fatalf("a held job = %v", got) + } + } + c.server.Settle() + if _, got := api.do("GET", "/ingestion/jobs/held", nil); got["status"] != "succeeded" { + t.Fatalf("a held job after Settle = %v", got) + } +} + +func TestFailProvisioning(t *testing.T) { + c := setup(t) + c.createGroup(t, group, nil) + ws := c.createLogWorkspace(t, "logs") + if err := c.server.FailProvisioning(*ws.ID); err != nil { + t.Fatal(err) + } + got, err := c.logs.Get(t.Context(), group, "logs", nil) + if err != nil || *got.Properties.ProvisioningState != armoperationalinsights.WorkspaceEntityStatusFailed { + t.Fatalf("a failed workspace = %+v, %v", got.Properties, err) + } + again := c.createLogWorkspace(t, "logs") + if *again.Properties.ProvisioningState != armoperationalinsights.WorkspaceEntityStatusSucceeded || *again.Properties.CustomerID != *ws.Properties.CustomerID { + t.Fatalf("a failed workspace put again = %+v", again.Properties) + } + if err := c.server.FailProvisioning(*ws.ID + "x"); err == nil { + t.Fatal("failing a resource that does not exist succeeded") + } +} diff --git a/sdktest/azure/arm/permissions_test.go b/sdktest/azure/arm/permissions_test.go index 9b7ebcd..89cbe80 100644 --- a/sdktest/azure/arm/permissions_test.go +++ b/sdktest/azure/arm/permissions_test.go @@ -6,6 +6,8 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute/v8" + "github.com/parallelworks/squall/access" "github.com/parallelworks/squall/azure/arm" ) @@ -74,3 +76,34 @@ func TestPolicyRecordsWhatAllowedCallsNeeded(t *testing.T) { t.Errorf("Used() = %v, want %v", got, want) } } + +func TestPolicyChecksComputeActions(t *testing.T) { + policy := access.Allow( + "Microsoft.Resources/subscriptions/resourceGroups/write", + "Microsoft.Network/networkInterfaces/*", + "Microsoft.Network/virtualNetworks/subnets/join/action", + "Microsoft.Compute/virtualMachines/write", + ) + c := setup(t, arm.WithPolicy(policy)) + c.createGroup(t, group, nil) + nic := c.createNIC(t, group, "nic", nil) + c.createVM(t, "vm", nic) + for action, call := range map[string]func() error{ + "Microsoft.Compute/virtualMachines/powerOff/action": func() error { + _, err := c.vms.BeginPowerOff(t.Context(), group, "vm", nil) + return err + }, + "Microsoft.Compute/skus/read": func() error { + _, err := c.skus.NewListPager(nil).NextPage(t.Context()) + return err + }, + "Microsoft.Compute/galleries/images/versions/write": func() error { + _, err := c.versions.BeginUpdate(t.Context(), group, "gallery", "image", "1.0.0", armcompute.GalleryImageVersionUpdate{}, nil) + return err + }, + } { + if err := call(); code(err) != "AuthorizationFailed" || !strings.Contains(err.Error(), "'"+action+"'") { + t.Errorf("%s = %v", action, err) + } + } +} diff --git a/sdktest/azure/arm/searchdata_test.go b/sdktest/azure/arm/searchdata_test.go new file mode 100644 index 0000000..13b4295 --- /dev/null +++ b/sdktest/azure/arm/searchdata_test.go @@ -0,0 +1,414 @@ +package arm_test + +import ( + "bytes" + "encoding/json" + "io" + "maps" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/parallelworks/squall/azure/arm" + "github.com/parallelworks/squall/fault" +) + +// rest calls a data plane that has no Go client library in use, as its REST +// reference documents the calls. +type rest struct { + t *testing.T + base string + key string + version string + header http.Header + lastETag string +} + +func (r *rest) do(method, path string, body any) (int, map[string]any) { + r.t.Helper() + var reader io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + r.t.Fatal(err) + } + reader = bytes.NewReader(b) + } + sep := "?" + if strings.Contains(path, "?") { + sep = "&" + } + if r.version != "" { + path += sep + "api-version=" + r.version + } + req, err := http.NewRequestWithContext(r.t.Context(), method, r.base+path, reader) + if err != nil { + r.t.Fatal(err) + } + if r.key != "" { + req.Header.Set("api-key", r.key) + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + maps.Copy(req.Header, r.header) + resp, err := http.DefaultClient.Do(req) + if err != nil { + r.t.Fatal(err) + } + defer resp.Body.Close() + r.lastETag = resp.Header.Get("ETag") + raw, err := io.ReadAll(resp.Body) + if err != nil { + r.t.Fatal(err) + } + var out map[string]any + if len(raw) > 0 { + if err := json.Unmarshal(raw, &out); err != nil { + r.t.Fatalf("%s %s answered %d %q: %v", method, path, resp.StatusCode, raw, err) + } + } + return resp.StatusCode, out +} + +func errorMessage(body map[string]any) string { + e, _ := body["error"].(map[string]any) + m, _ := e["message"].(string) + return m +} + +// searchService creates a search service and returns a client of its data +// plane that sends its secondary admin key. +func (c *clients) searchService(t *testing.T, name string) *rest { + t.Helper() + c.createGroup(t, group, nil) + p, err := c.beginSearch(t, name) + if _, err := wait(t, p, err); err != nil { + t.Fatal(err) + } + keys, err := c.searchKeys.Get(t.Context(), group, name, nil, nil) + if err != nil { + t.Fatal(err) + } + srv := httptest.NewServer(c.server.Search()) + t.Cleanup(srv.Close) + return &rest{t: t, base: srv.URL + "/" + name, key: *keys.SecondaryKey, version: "2024-07-01"} +} + +func docsIndex(name string, extra ...map[string]any) map[string]any { + fields := []any{ + map[string]any{"name": "id", "type": "Edm.String", "key": true}, + map[string]any{"name": "title", "type": "Edm.String", "searchable": true}, + map[string]any{"name": "secret", "type": "Edm.String", "retrievable": false}, + } + for _, f := range extra { + fields = append(fields, f) + } + return map[string]any{"name": name, "fields": fields, "corsOptions": map[string]any{"allowedOrigins": []any{"*"}}} +} + +func TestSearchIndexes(t *testing.T) { + c := setup(t) + api := c.searchService(t, "find") + status, created := api.do("PUT", "/indexes/docs", docsIndex("docs")) + if status != http.StatusCreated || created["name"] != "docs" || created["@odata.etag"] == nil || api.lastETag != created["@odata.etag"] { + t.Fatalf("create = %d %v, ETag %q", status, created, api.lastETag) + } + etag := api.lastETag + if status, got := api.do("GET", "/indexes('docs')", nil); status != http.StatusOK || got["corsOptions"] == nil { + t.Fatalf("get by key = %d %v", status, got) + } + update := docsIndex("docs", map[string]any{"name": "url", "type": "Edm.String"}) + update["@odata.etag"] = etag + if status, got := api.do("PUT", "/indexes/docs", update); status != http.StatusOK || len(got["fields"].([]any)) != 4 || api.lastETag == etag { + t.Fatalf("update = %d %v", status, got) + } + if status, got := api.do("PUT", "/indexes/docs", map[string]any{"fields": docsIndex("docs")["fields"].([]any)[:1]}); status != http.StatusBadRequest { + t.Fatalf("removing fields = %d %v", status, got) + } + if status, got := api.do("PUT", "/indexes/docs", map[string]any{"name": "other", "fields": []any{}}); status != http.StatusBadRequest { + t.Fatalf("a body naming another index = %d %v", status, got) + } + if status, got := api.do("PUT", "/indexes/two", map[string]any{"fields": []any{map[string]any{"name": "n", "type": "Edm.Int32", "key": true}}}); status != http.StatusBadRequest { + t.Fatalf("a key that is not a string = %d %v", status, got) + } + if status, got := api.do("PUT", "/indexes/two", map[string]any{"fields": []any{}, "colour": "red"}); status != http.StatusBadRequest || + !strings.Contains(errorMessage(got), "'colour' does not exist") { + t.Fatalf("an unknown member = %d %v", status, got) + } + if status, _ := api.do("PUT", "/indexes/Upper", docsIndex("Upper")); status != http.StatusBadRequest { + t.Fatalf("an upper-case index name = %d", status) + } + + api.header = http.Header{"If-None-Match": {"*"}} + if status, _ := api.do("PUT", "/indexes/docs", docsIndex("docs")); status != http.StatusPreconditionFailed { + t.Fatalf("If-None-Match * on an index = %d", status) + } + api.header = http.Header{"If-Match": {etag}} + if status, _ := api.do("DELETE", "/indexes/docs", nil); status != http.StatusPreconditionFailed { + t.Fatalf("a delete with a stale If-Match = %d", status) + } + api.header = http.Header{"Prefer": {"return=minimal"}} + if status, body := api.do("PUT", "/indexes/minimal", docsIndex("minimal")); status != http.StatusNoContent || body != nil { + t.Fatalf("return=minimal = %d %v", status, body) + } + api.header = nil + + if status, _ := api.do("DELETE", "/indexes/docs", nil); status != http.StatusNoContent { + t.Fatalf("delete = %d", status) + } + if status, got := api.do("GET", "/indexes/docs", nil); status != http.StatusNotFound || errorMessage(got) != "No index with the name 'docs' was found in a service named 'find'." { + t.Fatalf("a deleted index = %d %v", status, got) + } + if status, _ := api.do("DELETE", "/indexes('docs')", nil); status != http.StatusNotFound { + t.Fatalf("deleting a missing index = %d", status) + } +} + +func TestSearchDataPlaneAuthentication(t *testing.T) { + c := setup(t) + api := c.searchService(t, "find") + keys, err := c.searchKeys.Get(t.Context(), group, "find", nil, nil) + if err != nil { + t.Fatal(err) + } + api.key = *keys.PrimaryKey + if status, _ := api.do("PUT", "/indexes/docs", docsIndex("docs")); status != http.StatusCreated { + t.Fatalf("the primary key = %d", status) + } + api.key = "wrong" + if status, _ := api.do("GET", "/indexes/docs", nil); status != http.StatusForbidden { + t.Fatalf("a wrong key = %d", status) + } + api.key = "" + if status, _ := api.do("GET", "/indexes/docs", nil); status != http.StatusForbidden { + t.Fatalf("no key = %d", status) + } + api.key, api.version = *keys.PrimaryKey, "" + if status, got := api.do("GET", "/indexes/docs", nil); status != http.StatusBadRequest || !strings.Contains(errorMessage(got), "api-version") { + t.Fatalf("no api-version = %d %v", status, got) + } + api.version = "2024-07-01" + other := &rest{t: t, base: strings.TrimSuffix(api.base, "/find") + "/lost", key: api.key, version: "2024-07-01"} + if status, _ := other.do("GET", "/indexes/docs", nil); status != http.StatusNotFound { + t.Fatalf("a service that does not exist = %d", status) + } + + // The service's host name names it too. + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, strings.TrimSuffix(api.base, "/find")+"/indexes/docs?api-version=2024-07-01", nil) + if err != nil { + t.Fatal(err) + } + req.Host = "find.search.windows.net" + req.Header.Set("api-key", api.key) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("addressed by host name = %d", resp.StatusCode) + } + + if _, err := c.search.Delete(t.Context(), group, "find", nil, nil); err != nil { + t.Fatal(err) + } + if status, _ := api.do("GET", "/indexes/docs", nil); status != http.StatusNotFound { + t.Fatalf("a deleted service = %d", status) + } + c.server.Settle() + p, err := c.beginSearch(t, "find") + if _, err := wait(t, p, err); err != nil { + t.Fatal(err) + } + keys, err = c.searchKeys.Get(t.Context(), group, "find", nil, nil) + if err != nil { + t.Fatal(err) + } + api.key = *keys.PrimaryKey + if status, _ := api.do("GET", "/indexes/docs", nil); status != http.StatusNotFound { + t.Fatalf("an index of a service deleted and made again = %d", status) + } +} + +func dataSource(name string) map[string]any { + return map[string]any{ + "name": name, "type": "azureblob", "credentials": map[string]any{"connectionString": "DefaultEndpointsProtocol=https;AccountName=a;AccountKey=k"}, + "container": map[string]any{"name": "docs"}, + } +} + +func lastRun(t *testing.T, api *rest, indexer string) (string, map[string]any) { + t.Helper() + status, got := api.do("GET", "/indexers('"+indexer+"')/search.status", nil) + if status != http.StatusOK || got["status"] != "running" { + t.Fatalf("status = %d %v", status, got) + } + last, _ := got["lastResult"].(map[string]any) + s, _ := last["status"].(string) + return s, got +} + +func TestSearchDataSourcesAndIndexers(t *testing.T) { + c := setup(t, arm.WithSettleAfter(1)) + api := c.searchService(t, "find") + if status, got := api.do("PUT", "/datasources/blobs", dataSource("blobs")); status != http.StatusCreated || + got["credentials"].(map[string]any)["connectionString"] != nil { + t.Fatalf("create data source = %d %v", status, got) + } + keep := dataSource("blobs") + keep["credentials"] = map[string]any{"connectionString": ""} + if status, _ := api.do("PUT", "/datasources('blobs')", keep); status != http.StatusOK { + t.Fatalf("an update keeping the connection string = %d", status) + } + if status, _ := api.do("PUT", "/datasources/other", map[string]any{"type": "azureblob", "container": map[string]any{"name": "x"}}); status != http.StatusBadRequest { + t.Fatalf("a data source without credentials = %d", status) + } + if status, _ := api.do("PUT", "/datasources/other", map[string]any{"type": "ftp"}); status != http.StatusBadRequest { + t.Fatalf("an unknown data source type = %d", status) + } + indexer := map[string]any{"dataSourceName": "blobs", "targetIndexName": "docs"} + if status, got := api.do("PUT", "/indexers/nightly", indexer); status != http.StatusBadRequest || !strings.Contains(errorMessage(got), "target index 'docs'") { + t.Fatalf("an indexer of a missing index = %d %v", status, got) + } + api.do("PUT", "/indexes/docs", docsIndex("docs")) + if status, got := api.do("PUT", "/indexers/nightly", indexer); status != http.StatusCreated || got["dataSourceName"] != "blobs" { + t.Fatalf("create indexer = %d %v", status, got) + } + if run, _ := lastRun(t, api, "nightly"); run != "inProgress" { + t.Fatalf("a new indexer's run = %q", run) + } + if status, got := api.do("POST", "/indexers('nightly')/search.run", nil); status != http.StatusConflict || + errorMessage(got) != "Another indexer invocation is currently in progress; concurrent invocations are not allowed." { + t.Fatalf("a run while one is in progress = %d %v", status, got) + } + run, got := lastRun(t, api, "nightly") + if run != "success" || got["lastResult"].(map[string]any)["itemsProcessed"] != 0.0 { + t.Fatalf("a run after its reads = %q %v", run, got) + } + if status, _ := api.do("POST", "/indexers/nightly/search.run", nil); status != http.StatusAccepted { + t.Fatalf("run = %d", status) + } + c.server.Settle() + if run, got := lastRun(t, api, "nightly"); run != "success" || len(got["executionHistory"].([]any)) != 2 { + t.Fatalf("a settled run = %q %v", run, got) + } + disabled := map[string]any{"dataSourceName": "blobs", "targetIndexName": "docs", "disabled": true} + api.do("PUT", "/indexers/off", disabled) + if _, got := lastRun(t, api, "off"); got["lastResult"] != nil { + t.Fatalf("a disabled indexer ran: %v", got) + } + if status, _ := api.do("PUT", "/indexers/skilled", map[string]any{"dataSourceName": "blobs", "targetIndexName": "docs", "skillsetName": "s"}); status != http.StatusBadRequest { + t.Fatalf("an indexer with a skillset = %d", status) + } + if status, _ := api.do("GET", "/indexers('nightly')", nil); status != http.StatusOK { + t.Fatalf("get indexer = %d", status) + } + for _, path := range []string{"/indexers('nightly')", "/datasources/blobs"} { + if status, _ := api.do("DELETE", path, nil); status != http.StatusNoContent { + t.Fatalf("delete %s = %d", path, status) + } + if status, _ := api.do("DELETE", path, nil); status != http.StatusNotFound { + t.Fatalf("delete %s again = %d", path, status) + } + } + if status, got := api.do("GET", "/indexers/nightly/search.status", nil); status != http.StatusNotFound || + errorMessage(got) != "No indexer with the name 'nightly' was found in a service named 'find'." { + t.Fatalf("status of a deleted indexer = %d %v", status, got) + } +} + +func TestSearchDocuments(t *testing.T) { + c := setup(t) + api := c.searchService(t, "find") + api.do("PUT", "/indexes/docs", docsIndex("docs")) + batch := map[string]any{"value": []any{ + map[string]any{"@search.action": "upload", "id": "b", "title": "guide.pdf", "secret": "s"}, + map[string]any{"id": "a", "title": "notes.txt"}, + map[string]any{"@search.action": "upload", "id": "c", "title": "guide.pdf"}, + }} + if status, got := api.do("POST", "/indexes/docs/docs/index", batch); status != http.StatusOK || len(got["value"].([]any)) != 3 || + got["value"].([]any)[0].(map[string]any)["statusCode"] != 201.0 { + t.Fatalf("index = %d %v", status, got) + } + status, got := api.do("POST", "/indexes('docs')/docs/search.index", map[string]any{"value": []any{ + map[string]any{"@search.action": "merge", "id": "a", "title": "renamed.txt"}, + map[string]any{"@search.action": "merge", "id": "z", "title": "x"}, + map[string]any{"@search.action": "delete", "id": "c"}, + map[string]any{"@search.action": "mergeOrUpload", "id": "d", "title": "new.md"}, + }}) + results, _ := got["value"].([]any) + codes := []float64{} + for _, r := range results { + codes = append(codes, r.(map[string]any)["statusCode"].(float64)) + } + if status != http.StatusMultiStatus || !slices.Equal(codes, []float64{200, 404, 200, 201}) { + t.Fatalf("a batch with a failure = %d %v", status, got) + } + status, got = api.do("GET", "/indexes('docs')/docs?$select=title&$count=true", nil) + var titles []any + for _, hit := range got["value"].([]any) { + h := hit.(map[string]any) + if len(h) != 2 || h["@search.score"] != 1.0 { + t.Fatalf("a hit = %v", h) + } + titles = append(titles, h["title"]) + } + if status != http.StatusOK || got["@odata.count"] != 3.0 || !slices.Equal(titles, []any{"renamed.txt", "guide.pdf", "new.md"}) { + t.Fatalf("search = %d %v", status, got) + } + if _, got := api.do("GET", "/indexes/docs/docs?search=*&$top=1&$skip=1", nil); len(got["value"].([]any)) != 1 || + got["value"].([]any)[0].(map[string]any)["id"] != "b" || got["value"].([]any)[0].(map[string]any)["secret"] != nil { + t.Fatalf("a page = %v", got) + } + for _, query := range []string{"?search=guide", "?$filter=title eq 'x'", "?$select=colour", "?$top=-1"} { + if status, _ := api.do("GET", "/indexes/docs/docs"+strings.ReplaceAll(query, " ", "%20"), nil); status != http.StatusBadRequest { + t.Fatalf("search %s = %d", query, status) + } + } + for _, body := range []map[string]any{ + {"value": []any{map[string]any{"id": "e", "colour": "red"}}}, + {"value": []any{map[string]any{"title": "keyless"}}}, + } { + if status, _ := api.do("POST", "/indexes/docs/docs/index", body); status != http.StatusBadRequest { + t.Fatalf("index %v = %d", body, status) + } + } + api.do("DELETE", "/indexes/docs", nil) + api.do("PUT", "/indexes/docs", docsIndex("docs")) + if _, got := api.do("GET", "/indexes/docs/docs", nil); len(got["value"].([]any)) != 0 { + t.Fatalf("an index made again kept documents: %v", got) + } +} + +func TestSearchDataPlaneFaults(t *testing.T) { + faults := fault.New() + c := setup(t, arm.WithFaults(faults)) + api := c.searchService(t, "find") + api.do("PUT", "/indexes/docs", docsIndex("docs")) + api.do("PUT", "/datasources/blobs", dataSource("blobs")) + api.do("PUT", "/indexers/nightly", map[string]any{"dataSourceName": "blobs", "targetIndexName": "docs"}) + faults.Add( + fault.Rule{Method: "Indexers_Run", Fault: fault.FailOperation(http.StatusInternalServerError).WithMessage("The data source is unreachable.")}, + fault.Rule{Method: "Indexes_Delete", Resource: "find/indexes/docs", Times: 1, Fault: fault.Reject(http.StatusInternalServerError, "")}, + fault.Rule{Method: "Documents_SearchGet", Times: 1, Fault: fault.Unavailable().WithMessage("busy")}, + ) + if status, _ := api.do("POST", "/indexers/nightly/search.run", nil); status != http.StatusAccepted { + t.Fatalf("a run whose execution fails = %d", status) + } + run, got := lastRun(t, api, "nightly") + if last := got["lastResult"].(map[string]any); run != "transientFailure" || last["errorMessage"] != "The data source is unreachable." { + t.Fatalf("a failed run = %v", got) + } + if status, got := api.do("GET", "/indexes/docs/docs", nil); status != http.StatusServiceUnavailable || errorMessage(got) != "busy" { + t.Fatalf("a faulted search = %d %v", status, got) + } + if status, _ := api.do("DELETE", "/indexes/docs", nil); status != http.StatusInternalServerError { + t.Fatalf("a faulted delete = %d", status) + } + if status, _ := api.do("DELETE", "/indexes/docs", nil); status != http.StatusNoContent { + t.Fatalf("a delete after the fault = %d", status) + } +} diff --git a/sdktest/azure/arm/snapshot_test.go b/sdktest/azure/arm/snapshot_test.go index b6deec1..b496ad1 100644 --- a/sdktest/azure/arm/snapshot_test.go +++ b/sdktest/azure/arm/snapshot_test.go @@ -628,3 +628,59 @@ func TestSnapshotAccess(t *testing.T) { t.Fatalf("granting write access = %v", err) } } + +func TestGalleryImageVersionUpdate(t *testing.T) { + c := setup(t, arm.WithSettleAfter(1)) + c.createGroup(t, group, nil) + gp, err := c.galleries.BeginCreateOrUpdate(t.Context(), group, "gallery", armcompute.Gallery{Location: new(location)}, nil) + if _, err = wait(t, gp, err); err != nil { + t.Fatal(err) + } + ip, err := c.images.BeginCreateOrUpdate(t.Context(), group, "gallery", "image", imageBody(armcompute.OperatingSystemTypesLinux), nil) + if _, err = wait(t, ip, err); err != nil { + t.Fatal(err) + } + dp, err := c.disks.BeginCreateOrUpdate(t.Context(), group, "disk", diskBody(location, 10), nil) + if _, err = wait(t, dp, err); err != nil { + t.Fatal(err) + } + body := versionBody(computePrefix + "disks/disk") + body.Properties.SafetyProfile = &armcompute.GalleryImageVersionSafetyProfile{BlockDeletionBeforeEndOfLife: new(true)} + body.Properties.PublishingProfile.EndOfLifeDate = new(time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC)) + vp, err := c.versions.BeginCreateOrUpdate(t.Context(), group, "gallery", "image", "1.0.0", body, nil) + if _, err = wait(t, vp, err); err != nil { + t.Fatal(err) + } + + up, err := c.versions.BeginUpdate(t.Context(), group, "gallery", "image", "1.0.0", armcompute.GalleryImageVersionUpdate{ + Tags: map[string]*string{"k": new("v")}, + Properties: &armcompute.GalleryImageVersionProperties{ + SafetyProfile: &armcompute.GalleryImageVersionSafetyProfile{BlockDeletionBeforeEndOfLife: new(false)}, + }, + }, nil) + if err != nil || up.Done() { + t.Fatalf("begin update = %v", err) + } + if got, err := c.versions.Get(t.Context(), group, "gallery", "image", "1.0.0", nil); err != nil || *got.Properties.ProvisioningState != armcompute.GalleryProvisioningStateUpdating { + t.Fatalf("version being updated = %+v, %v", got.Properties, err) + } + updated, err := up.PollUntilDone(t.Context(), &runtime.PollUntilDoneOptions{Frequency: time.Millisecond}) + if err != nil { + t.Fatal(err) + } + props := updated.Properties + if *props.ProvisioningState != armcompute.GalleryProvisioningStateSucceeded || *props.SafetyProfile.BlockDeletionBeforeEndOfLife || + !props.PublishingProfile.EndOfLifeDate.Equal(time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC)) || + *props.StorageProfile.OSDiskImage.Source.ID != computePrefix+"disks/disk" || *updated.Tags["k"] != "v" { + t.Fatalf("updated version = %+v, %+v", props, updated.Tags) + } + + if _, err := c.versions.BeginUpdate(t.Context(), group, "gallery", "image", "1.0.0", armcompute.GalleryImageVersionUpdate{ + Properties: &armcompute.GalleryImageVersionProperties{StorageProfile: body.Properties.StorageProfile}, + }, nil); status(err) != http.StatusBadRequest { + t.Fatalf("a PATCH of the storage profile = %v", err) + } + if _, err := c.versions.BeginUpdate(t.Context(), group, "gallery", "image", "2.0.0", armcompute.GalleryImageVersionUpdate{}, nil); code(err) != "ResourceNotFound" { + t.Fatalf("updating a missing version = %v", err) + } +} diff --git a/sdktest/azure/graph/graph_test.go b/sdktest/azure/graph/graph_test.go index 42af62b..a7694be 100644 --- a/sdktest/azure/graph/graph_test.go +++ b/sdktest/azure/graph/graph_test.go @@ -217,6 +217,25 @@ func TestOrganization(t *testing.T) { } } +func TestOrganizationWithoutCountry(t *testing.T) { + _, client := setup(t, graph.WithOrganization(graph.Organization{NoCountry: true, DefaultUsageLocation: "GB"})) + resp, err := client.Organization().Get(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + if org := resp.GetValue()[0]; len(resp.GetValue()) != 1 || org.GetCountryLetterCode() != nil || org.GetCountry() != nil || *org.GetDefaultUsageLocation() != "GB" { + t.Fatalf("an organization without a country = %v %v", org.GetCountryLetterCode(), org.GetDefaultUsageLocation()) + } + + _, client = setup(t, graph.WithOrganization(graph.Organization{NoCountry: true, NoDefaultUsageLocation: true})) + if resp, err = client.Organization().Get(t.Context(), nil); err != nil { + t.Fatal(err) + } + if org := resp.GetValue()[0]; org.GetCountryLetterCode() != nil || org.GetDefaultUsageLocation() != nil || *org.GetDisplayName() != "Squall" { + t.Fatalf("an organization with neither = %v %v", org.GetCountryLetterCode(), org.GetDefaultUsageLocation()) + } +} + func TestNewUsersAreChecked(t *testing.T) { _, client := setup(t) for _, tc := range []struct{ upn, password, message string }{ diff --git a/sdktest/gcp/compute/accelerators_test.go b/sdktest/gcp/compute/accelerators_test.go new file mode 100644 index 0000000..7f5c314 --- /dev/null +++ b/sdktest/gcp/compute/accelerators_test.go @@ -0,0 +1,119 @@ +package compute_test + +import ( + "errors" + "fmt" + "net/http" + "testing" + + gcompute "cloud.google.com/go/compute/apiv1" + "cloud.google.com/go/compute/apiv1/computepb" + "google.golang.org/api/iterator" + "google.golang.org/api/option" + + "github.com/parallelworks/squall/access" + "github.com/parallelworks/squall/gcp/compute" + "github.com/parallelworks/squall/sdktest/internal/sdkerr" +) + +func acceleratorsClient(t *testing.T, c *clients) *gcompute.AcceleratorTypesClient { + t.Helper() + client, err := gcompute.NewAcceleratorTypesRESTClient(t.Context(), option.WithEndpoint(c.url), option.WithoutAuthentication()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = client.Close() }) + return client +} + +func TestAcceleratorTypes(t *testing.T) { + c := setup(t, + compute.WithZones("asia-east1", "asia-east1-a"), + compute.WithAcceleratorTypes("us-east1-c", "nvidia-tesla-t4", "nvidia-tesla-p100"), + compute.WithAcceleratorTypes("us-east1-d"), + ) + accel := acceleratorsClient(t, c) + + aggregated := func(filter string) map[string][]string { + req := &computepb.AggregatedListAcceleratorTypesRequest{Project: project} + if filter != "" { + req.Filter = new(filter) + } + it := accel.AggregatedList(t.Context(), req) + out := map[string][]string{} + for { + pair, err := it.Next() + if errors.Is(err, iterator.Done) { + return out + } + if err != nil { + t.Fatal(err) + } + for _, a := range pair.Value.GetAcceleratorTypes() { + out[pair.Key] = append(out[pair.Key], a.GetName()) + } + } + } + all := aggregated("") + if fmt.Sprint(all["zones/us-east1-b"]) != "[nvidia-l4 nvidia-tesla-t4]" || fmt.Sprint(all["zones/asia-east1-a"]) != "[nvidia-l4 nvidia-tesla-t4]" || + fmt.Sprint(all["zones/us-east1-c"]) != "[nvidia-tesla-p100 nvidia-tesla-t4]" { + t.Errorf("aggregatedList = %v", all) + } + if _, ok := all["zones/us-east1-d"]; ok { + t.Errorf("aggregatedList lists a zone that offers none: %v", all) + } + if got := fmt.Sprint(aggregated("name=nvidia-tesla-p100")); got != "map[zones/us-east1-c:[nvidia-tesla-p100]]" { + t.Errorf("aggregatedList filtered = %s", got) + } + + a, err := accel.Get(t.Context(), &computepb.GetAcceleratorTypeRequest{Project: project, Zone: "us-east1-c", AcceleratorType: "nvidia-tesla-p100"}) + if err != nil { + t.Fatal(err) + } + if a.GetDescription() != "NVIDIA Tesla P100" || a.GetMaximumCardsPerInstance() != 4 || a.GetId() == 0 || + a.GetZone() != "https://www.googleapis.com/compute/v1/projects/p/zones/us-east1-c" || + a.GetSelfLink() != "https://www.googleapis.com/compute/v1/projects/p/zones/us-east1-c/acceleratorTypes/nvidia-tesla-p100" { + t.Errorf("accelerator type = %v", a) + } + _, err = accel.Get(t.Context(), &computepb.GetAcceleratorTypeRequest{Project: project, Zone: "us-east1-b", AcceleratorType: "nvidia-tesla-p100"}) + if sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("get of a type the zone does not offer = %v, want HTTP 404", err) + } + + list := func(zone string) ([]string, error) { + it := accel.List(t.Context(), &computepb.ListAcceleratorTypesRequest{Project: project, Zone: zone}) + var out []string + for { + a, err := it.Next() + if errors.Is(err, iterator.Done) { + return out, nil + } + if err != nil { + return out, err + } + out = append(out, a.GetName()) + } + } + if got, err := list("us-east1-c"); err != nil || fmt.Sprint(got) != "[nvidia-tesla-p100 nvidia-tesla-t4]" { + t.Errorf("list us-east1-c = %v, %v", got, err) + } + if got, err := list("us-east1-d"); err != nil || len(got) != 0 { + t.Errorf("list of a zone that offers none = %v, %v", got, err) + } + if _, err := list("us-east1-z"); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("list of an unknown zone = %v, want HTTP 400", err) + } +} + +func TestAcceleratorTypesNeedTheirPermissions(t *testing.T) { + policy := access.Allow("compute.acceleratorTypes.list") + c := setup(t, compute.WithPolicy(policy)) + accel := acceleratorsClient(t, c) + if _, err := accel.AggregatedList(t.Context(), &computepb.AggregatedListAcceleratorTypesRequest{Project: project}).Next(); err != nil { + t.Errorf("aggregatedList = %v", err) + } + _, err := accel.Get(t.Context(), &computepb.GetAcceleratorTypeRequest{Project: project, Zone: zone, AcceleratorType: "nvidia-tesla-t4"}) + if sdkerr.GoogleCode(err) != http.StatusForbidden { + t.Errorf("get without compute.acceleratorTypes.get = %v, want HTTP 403", err) + } +} diff --git a/sdktest/gcp/compute/addresses_test.go b/sdktest/gcp/compute/addresses_test.go index 5c0952a..01a6311 100644 --- a/sdktest/gcp/compute/addresses_test.go +++ b/sdktest/gcp/compute/addresses_test.go @@ -343,6 +343,26 @@ func TestLostResponseReachesTheCaller(t *testing.T) { } } +func TestFaultMessageReachesTheCaller(t *testing.T) { + const message = "The resource 'ip-1' is in use" + for _, tc := range []struct { + name string + fault fault.Fault + }{ + {"rejected", fault.Reject(http.StatusBadRequest, "resourceInUseByAnotherResource").WithMessage(message)}, + {"operation failed", fault.FailOperation(http.StatusBadRequest).WithMessage(message)}, + } { + t.Run(tc.name, func(t *testing.T) { + faults := fault.New().Add(fault.Rule{Method: "compute.addresses.insert", Nth: 1, Fault: tc.fault}) + c := newClient(t, compute.New(compute.WithFaults(faults))) + err := insert(t, c, &computepb.Address{Name: new("ip-1")}) + if sdkerr.GoogleCode(err) != http.StatusBadRequest || !strings.Contains(err.Error(), message) { + t.Fatalf("insert = %v, want HTTP 400 saying %q", err, message) + } + }) + } +} + func TestOperationFailedOnAReadFailsTheRead(t *testing.T) { faults := fault.New().Add(fault.Rule{Method: "compute.regionOperations.get", Nth: 1, Fault: fault.FailOperation(http.StatusForbidden)}) s := compute.New(compute.WithFaults(faults)) diff --git a/sdktest/gcp/compute/disks_test.go b/sdktest/gcp/compute/disks_test.go new file mode 100644 index 0000000..fcc3ea1 --- /dev/null +++ b/sdktest/gcp/compute/disks_test.go @@ -0,0 +1,83 @@ +package compute_test + +import ( + "net/http" + "strings" + "testing" + + "cloud.google.com/go/compute/apiv1/computepb" + + "github.com/parallelworks/squall/gcp/compute" + "github.com/parallelworks/squall/sdktest/internal/sdkerr" +) + +func TestPutDiskSetsUpAFailedDisk(t *testing.T) { + c := setup(t) + put, err := c.server.PutDisk(project, zone, compute.Disk{Name: "broken", Status: "FAILED", SizeGB: 20, Labels: map[string]string{"session-id": "s"}}) + if err != nil || put.Status != "FAILED" || put.ID == 0 || put.SizeGB != 20 || put.CreationTimestamp == "" { + t.Fatalf("PutDisk = %+v, %v", put, err) + } + got, err := c.disks.Get(t.Context(), &computepb.GetDiskRequest{Project: project, Zone: zone, Disk: "broken"}) + if err != nil || got.GetStatus() != "FAILED" || got.GetId() != put.ID || got.GetLabels()["session-id"] != "s" || + got.GetType() != "https://www.googleapis.com/compute/v1/projects/p/zones/us-east1-b/diskTypes/pd-standard" { + t.Fatalf("get = %v, %v", got, err) + } + if listed := c.aggregatedDisks(t, "status=FAILED"); len(listed) != 1 || !strings.HasSuffix(listed[0], "broken") { + t.Fatalf("aggregated list of FAILED disks = %v", listed) + } + + if err := c.insert(t, single("vm-1", "s")); err != nil { + t.Fatal(err) + } + attach, err := c.instances.AttachDisk(t.Context(), &computepb.AttachDiskInstanceRequest{ + Project: project, Zone: zone, Instance: "vm-1", + AttachedDiskResource: &computepb.AttachedDisk{Source: new("zones/" + zone + "/disks/broken")}, + }) + if err == nil { + err = attach.Wait(t.Context()) + } + if sdkerr.GoogleCode(err) != http.StatusBadRequest || !strings.Contains(err.Error(), "is not ready") { + t.Fatalf("attaching a FAILED disk = %v, want resourceNotReady", err) + } + if err := c.insertSnapshot(t, &computepb.Snapshot{Name: new("broken-1"), SourceDisk: new("zones/" + zone + "/disks/broken")}); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Fatalf("a snapshot of a FAILED disk = %v, want HTTP 400", err) + } + + op, err := c.disks.Delete(t.Context(), &computepb.DeleteDiskRequest{Project: project, Zone: zone, Disk: "broken"}) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatalf("deleting a FAILED disk = %v", err) + } + if _, ok := c.server.LookupDisk(project, zone, "broken"); ok { + t.Fatal("the FAILED disk is still there after its delete") + } +} + +func TestPutDiskRejectsWhatAnInsertWould(t *testing.T) { + c := setup(t) + if _, err := c.server.PutDisk(project, zone, compute.Disk{Name: "data"}); err != nil { + t.Fatal(err) + } + if got, ok := c.server.LookupDisk(project, zone, "data"); !ok || got.Status != "READY" { + t.Fatalf("a disk put with no status = %+v, %v; want READY", got, ok) + } + for name, d := range map[string]struct { + zone string + disk compute.Disk + }{ + "a name already taken": {zone, compute.Disk{Name: "data"}}, + "an invalid name": {zone, compute.Disk{Name: "Data"}}, + "a status in progress": {zone, compute.Disk{Name: "creating", Status: "CREATING"}}, + "an unknown zone": {"mars-1a", compute.Disk{Name: "elsewhere"}}, + "an image that is absent": {zone, compute.Disk{Name: "imaged", SourceImage: "projects/p/global/images/missing"}}, + } { + if _, err := c.server.PutDisk(project, d.zone, d.disk); err == nil { + t.Errorf("PutDisk took %s", name) + } + } + if got := c.server.Disks(); len(got) != 1 { + t.Fatalf("disks = %+v", got) + } +} diff --git a/sdktest/gcp/compute/groups_test.go b/sdktest/gcp/compute/groups_test.go new file mode 100644 index 0000000..b7718bf --- /dev/null +++ b/sdktest/gcp/compute/groups_test.go @@ -0,0 +1,605 @@ +package compute_test + +import ( + "errors" + "fmt" + "net/http" + "slices" + "strings" + "testing" + + "cloud.google.com/go/compute/apiv1/computepb" + "google.golang.org/api/iterator" + + "github.com/parallelworks/squall/access" + "github.com/parallelworks/squall/fault" + "github.com/parallelworks/squall/gcp/compute" + "github.com/parallelworks/squall/sdktest/internal/sdkerr" +) + +const group = "workers" + +func (c *clients) insertTemplate(t *testing.T, name string, props *computepb.InstanceProperties) { + t.Helper() + op, err := c.templates.Insert(t.Context(), &computepb.InsertInstanceTemplateRequest{Project: project, InstanceTemplateResource: &computepb.InstanceTemplate{ + Name: new(name), Properties: props, + }}) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatalf("insert template %s: %v", name, err) + } +} + +// insertGroup creates group from a new template of the same name. +func (c *clients) insertGroup(t *testing.T, targetSize int32) { + t.Helper() + c.insertTemplate(t, group, properties("s")) + op, err := c.managers.Insert(t.Context(), &computepb.InsertInstanceGroupManagerRequest{Project: project, Zone: zone, InstanceGroupManagerResource: &computepb.InstanceGroupManager{ + Name: new(group), Description: new("owned"), TargetSize: new(targetSize), + InstanceTemplate: new("projects/" + project + "/global/instanceTemplates/" + group), + InstanceLifecyclePolicy: &computepb.InstanceGroupManagerInstanceLifecyclePolicy{ + DefaultActionOnFailure: new("DO_NOTHING"), + }, + }}) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatalf("insert group: %v", err) + } +} + +func (c *clients) getGroup(t *testing.T) *computepb.InstanceGroupManager { + t.Helper() + g, err := c.managers.Get(t.Context(), &computepb.GetInstanceGroupManagerRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + if err != nil { + t.Fatalf("get group: %v", err) + } + return g +} + +func (c *clients) createInstances(t *testing.T, names ...string) error { + t.Helper() + var configs []*computepb.PerInstanceConfig + for _, name := range names { + configs = append(configs, &computepb.PerInstanceConfig{Name: new(name)}) + } + op, err := c.managers.CreateInstances(t.Context(), &computepb.CreateInstancesInstanceGroupManagerRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, + InstanceGroupManagersCreateInstancesRequestResource: &computepb.InstanceGroupManagersCreateInstancesRequest{Instances: configs}, + }) + if err != nil { + return err + } + return op.Wait(t.Context()) +} + +func (c *clients) deleteInstances(t *testing.T, skip bool, refs ...string) error { + t.Helper() + op, err := c.managers.DeleteInstances(t.Context(), &computepb.DeleteInstancesInstanceGroupManagerRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, + InstanceGroupManagersDeleteInstancesRequestResource: &computepb.InstanceGroupManagersDeleteInstancesRequest{ + Instances: refs, SkipInstancesOnValidationError: new(skip), + }, + }) + if err != nil { + return err + } + return op.Wait(t.Context()) +} + +// managed lists the group's instances as name:status:action. +func (c *clients) managed(t *testing.T) []string { + t.Helper() + it := c.managers.ListManagedInstances(t.Context(), &computepb.ListManagedInstancesInstanceGroupManagersRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + var out []string + for { + m, err := it.Next() + if errors.Is(err, iterator.Done) { + return out + } + if err != nil { + t.Fatalf("listManagedInstances: %v", err) + } + out = append(out, m.GetName()+":"+m.GetInstanceStatus()+":"+m.GetCurrentAction()) + } +} + +func TestInstanceGroupManagerCreatesAndDeletesInstances(t *testing.T) { + c := setup(t) + c.insertGroup(t, 0) + g := c.getGroup(t) + if g.GetTargetSize() != 0 || g.GetBaseInstanceName() != group || g.GetDescription() != "owned" || + g.GetZone() != "https://www.googleapis.com/compute/v1/projects/p/zones/"+zone || + g.GetInstanceTemplate() != "https://www.googleapis.com/compute/v1/projects/p/global/instanceTemplates/"+group || + g.GetInstanceLifecyclePolicy().GetDefaultActionOnFailure() != "DO_NOTHING" || !g.GetStatus().GetIsStable() { + t.Fatalf("group = %v", g) + } + + if err := c.createInstances(t, "node-1", "node-2"); err != nil { + t.Fatal(err) + } + inst, err := c.get(t, "node-1") + if err != nil || inst.GetStatus() != "RUNNING" || !strings.HasSuffix(inst.GetMachineType(), "/n2-standard-4") { + t.Fatalf("a group instance = %v, %v", inst, err) + } + var createdBy string + for _, item := range inst.GetMetadata().GetItems() { + if item.GetKey() == "created-by" { + createdBy = item.GetValue() + } + } + if createdBy != "projects/p/zones/"+zone+"/instanceGroupManagers/"+group { + t.Errorf("created-by = %q", createdBy) + } + if got := c.managed(t); fmt.Sprint(got) != "[node-1:RUNNING:NONE node-2:RUNNING:NONE]" { + t.Errorf("managed instances = %v", got) + } + if g := c.getGroup(t); g.GetTargetSize() != 2 || g.GetCurrentActions().GetNone() != 2 { + t.Errorf("group after createInstances = %v", g) + } + + if err := c.createInstances(t, "node-2", "node-3"); sdkerr.GoogleCode(err) != http.StatusConflict { + t.Errorf("createInstances naming a member = %v, want HTTP 409", err) + } + if err := c.insert(t, single("loner", "s")); err != nil { + t.Fatal(err) + } + if err := c.createInstances(t, "loner"); sdkerr.GoogleCode(err) != http.StatusConflict { + t.Errorf("createInstances naming an existing instance = %v, want HTTP 409", err) + } + + if err := c.deleteInstances(t, false, "zones/"+zone+"/instances/node-1", "zones/"+zone+"/instances/loner"); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("deleteInstances naming a non-member = %v, want HTTP 400", err) + } + if got := c.managed(t); len(got) != 2 { + t.Errorf("a failed deleteInstances took effect: %v", got) + } + if err := c.deleteInstances(t, true, "zones/"+zone+"/instances/node-1", "zones/"+zone+"/instances/loner"); err != nil { + t.Fatalf("deleteInstances skipping a non-member = %v", err) + } + if _, err := c.get(t, "node-1"); sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("a deleted member = %v, want HTTP 404", err) + } + if _, err := c.get(t, "loner"); err != nil { + t.Errorf("a skipped non-member = %v", err) + } + if err := c.deleteInstances(t, true, "zones/us-east1-c/instances/node-2"); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("deleteInstances in another zone = %v, want HTTP 400", err) + } + + _, err = c.templates.Delete(t.Context(), &computepb.DeleteInstanceTemplateRequest{Project: project, InstanceTemplate: group}) + if sdkerr.GoogleCode(err) != http.StatusBadRequest || apiReason(err) != "resourceInUseByAnotherResource" { + t.Errorf("deleting the group's template = %v, want resourceInUseByAnotherResource", err) + } + + op, err := c.managers.Delete(t.Context(), &computepb.DeleteInstanceGroupManagerRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatal(err) + } + if _, err := c.get(t, "node-2"); sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("an instance of a deleted group = %v, want HTTP 404", err) + } + if _, ok := c.server.LookupDisk(project, zone, "node-2"); ok { + t.Error("the boot disk of a deleted group's instance remains") + } + op, err = c.templates.Delete(t.Context(), &computepb.DeleteInstanceTemplateRequest{Project: project, InstanceTemplate: group}) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Errorf("deleting a template no group uses = %v", err) + } +} + +func TestInstanceGroupManagerListsAndTemplates(t *testing.T) { + c := setup(t) + c.insertGroup(t, 2) + insts, _ := c.list(t, "", 0) + if len(insts) != 2 || !strings.HasPrefix(insts[0].GetName(), group+"-") || len(insts[0].GetName()) != len(group)+5 { + t.Fatalf("instances of a group created with targetSize 2 = %s", names(insts)) + } + + it := c.managers.AggregatedList(t.Context(), &computepb.AggregatedListInstanceGroupManagersRequest{Project: project, Filter: new("name eq work.*")}) + var found []string + for { + pair, err := it.Next() + if errors.Is(err, iterator.Done) { + break + } + if err != nil { + t.Fatal(err) + } + for _, g := range pair.Value.GetInstanceGroupManagers() { + found = append(found, pair.Key+"/"+g.GetName()+fmt.Sprintf(":%d", g.GetTargetSize())) + } + } + if fmt.Sprint(found) != "[zones/"+zone+"/workers:2]" { + t.Errorf("aggregated groups = %v", found) + } + list := c.managers.List(t.Context(), &computepb.ListInstanceGroupManagersRequest{Project: project, Zone: zone, Filter: new("name = other")}) + if g, err := list.Next(); !errors.Is(err, iterator.Done) { + t.Errorf("filtered list = %v, %v; want none", g, err) + } + if _, err := c.managers.AggregatedList(t.Context(), &computepb.AggregatedListInstanceGroupManagersRequest{Project: project, Filter: new("targetSize = 1")}).Next(); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("an unsupported filter = %v, want HTTP 400", err) + } + + p := properties("t") + p.MachineType = new("n2-standard-8") + c.insertTemplate(t, "bigger", p) + set := func(template string) error { + op, err := c.managers.SetInstanceTemplate(t.Context(), &computepb.SetInstanceTemplateInstanceGroupManagerRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, + InstanceGroupManagersSetInstanceTemplateRequestResource: &computepb.InstanceGroupManagersSetInstanceTemplateRequest{InstanceTemplate: new(template)}, + }) + if err != nil { + return err + } + return op.Wait(t.Context()) + } + if err := set("global/instanceTemplates/missing"); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("setInstanceTemplate to a missing template = %v, want HTTP 400", err) + } + if err := set("projects/p/global/instanceTemplates/bigger"); err != nil { + t.Fatal(err) + } + if err := c.createInstances(t, "big-1"); err != nil { + t.Fatal(err) + } + if inst, err := c.get(t, "big-1"); err != nil || !strings.HasSuffix(inst.GetMachineType(), "/n2-standard-8") || inst.GetLabels()["session-id"] != "t" { + t.Errorf("an instance after setInstanceTemplate = %v, %v", inst, err) + } + if inst, _ := c.get(t, insts[0].GetName()); !strings.HasSuffix(inst.GetMachineType(), "/n2-standard-4") { + t.Errorf("an existing instance changed template: %s", inst.GetMachineType()) + } + if got := c.server.InstanceGroupManagers(); len(got) != 1 || got[0].TargetSize != 3 || !strings.HasSuffix(got[0].InstanceTemplate, "/bigger") { + t.Errorf("InstanceGroupManagers() = %+v", got) + } + + _, err := c.managers.Insert(t.Context(), &computepb.InsertInstanceGroupManagerRequest{Project: project, Zone: zone, InstanceGroupManagerResource: &computepb.InstanceGroupManager{ + Name: new("other"), TargetSize: new(int32(0)), InstanceTemplate: new("global/instanceTemplates/missing"), + }}) + if sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("a group of a missing template = %v, want HTTP 400", err) + } + _, err = c.managers.Insert(t.Context(), &computepb.InsertInstanceGroupManagerRequest{Project: project, Zone: zone, InstanceGroupManagerResource: &computepb.InstanceGroupManager{ + Name: new(group), TargetSize: new(int32(0)), InstanceTemplate: new("global/instanceTemplates/bigger"), + }}) + if sdkerr.GoogleCode(err) != http.StatusConflict { + t.Errorf("a second group of the same name = %v, want HTTP 409", err) + } +} + +func TestGroupInstancesSettleAfterReads(t *testing.T) { + c := setup(t, compute.WithSettleAfter(2)) + c.insertGroup(t, 0) + if err := c.createInstances(t, "node-1"); err != nil { + t.Fatal(err) + } + if got := c.managed(t); fmt.Sprint(got) != "[node-1:PROVISIONING:CREATING]" { + t.Errorf("managed instances while creating = %v", got) + } + var statuses []string + for range 3 { + inst, err := c.get(t, "node-1") + if err != nil { + t.Fatal(err) + } + statuses = append(statuses, inst.GetStatus()) + } + if fmt.Sprint(statuses) != "[PROVISIONING STAGING RUNNING]" { + t.Errorf("statuses = %v", statuses) + } + if err := c.deleteInstances(t, false, "node-1"); err != nil { + t.Fatal(err) + } + if got := c.managed(t); fmt.Sprint(got) != "[node-1:STOPPING:DELETING]" { + t.Errorf("managed instances while deleting = %v", got) + } + c.server.Settle() + if got := c.managed(t); len(got) != 0 { + t.Errorf("managed instances after the delete = %v", got) + } +} + +func TestGroupKeepsTryingAnInstanceItCannotCreate(t *testing.T) { + c := setup(t) + p := properties("s") + p.ResourcePolicies = []string{"missing-policy"} + c.insertTemplate(t, "broken", p) + c.insertGroup(t, 0) + op, err := c.managers.SetInstanceTemplate(t.Context(), &computepb.SetInstanceTemplateInstanceGroupManagerRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, + InstanceGroupManagersSetInstanceTemplateRequestResource: &computepb.InstanceGroupManagersSetInstanceTemplateRequest{InstanceTemplate: new("global/instanceTemplates/broken")}, + }) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatal(err) + } + if err := c.createInstances(t, "node-1"); err != nil { + t.Fatalf("createInstances = %v; the group accepts it and keeps trying", err) + } + it := c.managers.ListManagedInstances(t.Context(), &computepb.ListManagedInstancesInstanceGroupManagersRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + m, err := it.Next() + if err != nil { + t.Fatal(err) + } + errs := m.GetLastAttempt().GetErrors().GetErrors() + if m.GetCurrentAction() != "CREATING" || m.GetInstance() != "" || len(errs) != 1 || !strings.Contains(errs[0].GetMessage(), "missing-policy") { + t.Errorf("managed instance = %v", m) + } + if _, err := c.get(t, "node-1"); sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("an instance the group could not create = %v, want HTTP 404", err) + } + if err := c.deleteInstances(t, false, "node-1"); err != nil || len(c.managed(t)) != 0 { + t.Errorf("deleting it by name = %v, leaving %v", err, c.managed(t)) + } +} + +func (c *clients) insertResize(t *testing.T, name string, instances ...string) error { + t.Helper() + req := &computepb.InstanceGroupManagerResizeRequest{Name: new(name), RequestedRunDuration: &computepb.Duration{Seconds: new(int64(3600))}} + for _, inst := range instances { + req.Instances = append(req.Instances, &computepb.PerInstanceConfig{Name: new(inst)}) + } + op, err := c.resizes.Insert(t.Context(), &computepb.InsertInstanceGroupManagerResizeRequestRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, InstanceGroupManagerResizeRequestResource: req, + }) + if err != nil { + return err + } + return op.Wait(t.Context()) +} + +func (c *clients) getResize(t *testing.T, name string) (*computepb.InstanceGroupManagerResizeRequest, error) { + t.Helper() + return c.resizes.Get(t.Context(), &computepb.GetInstanceGroupManagerResizeRequestRequest{Project: project, Zone: zone, InstanceGroupManager: group, ResizeRequest: name}) +} + +func (c *clients) cancelResize(t *testing.T, name string) error { + t.Helper() + op, err := c.resizes.Cancel(t.Context(), &computepb.CancelInstanceGroupManagerResizeRequestRequest{Project: project, Zone: zone, InstanceGroupManager: group, ResizeRequest: name}) + if err != nil { + return err + } + return op.Wait(t.Context()) +} + +func (c *clients) deleteResize(t *testing.T, name string) error { + t.Helper() + op, err := c.resizes.Delete(t.Context(), &computepb.DeleteInstanceGroupManagerResizeRequestRequest{Project: project, Zone: zone, InstanceGroupManager: group, ResizeRequest: name}) + if err != nil { + return err + } + return op.Wait(t.Context()) +} + +// resizeStates lists the group's resize requests as name:state. +func (c *clients) resizeStates(t *testing.T) []string { + t.Helper() + it := c.resizes.List(t.Context(), &computepb.ListInstanceGroupManagerResizeRequestsRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + var out []string + for { + req, err := it.Next() + if errors.Is(err, iterator.Done) { + return out + } + if err != nil { + t.Fatalf("list resize requests: %v", err) + } + out = append(out, req.GetName()+":"+req.GetState()) + } +} + +func TestResizeRequestCreatesItsInstances(t *testing.T) { + c := setup(t) + c.insertGroup(t, 0) + if err := c.insertResize(t, "rr-1", "node-1", "node-2"); err != nil { + t.Fatal(err) + } + req, err := c.getResize(t, "rr-1") + if err != nil || req.GetState() != "SUCCEEDED" || req.GetRequestedRunDuration().GetSeconds() != 3600 || len(req.GetInstances()) != 2 || + req.GetSelfLink() != "https://www.googleapis.com/compute/v1/projects/p/zones/"+zone+"/instanceGroupManagers/workers/resizeRequests/rr-1" { + t.Fatalf("resize request = %v, %v", req, err) + } + if got := c.managed(t); fmt.Sprint(got) != "[node-1:RUNNING:NONE node-2:RUNNING:NONE]" { + t.Errorf("managed instances = %v", got) + } + if g := c.getGroup(t); g.GetTargetSize() != 2 { + t.Errorf("target size = %d", g.GetTargetSize()) + } + if err := c.insertResize(t, "rr-1", "node-3"); sdkerr.GoogleCode(err) != http.StatusConflict { + t.Errorf("a second request of the same name = %v, want HTTP 409", err) + } + err = c.insertResize(t, "rr-2", "node-3", "node-2") + if sdkerr.GoogleCode(err) != http.StatusBadRequest || !strings.Contains(err.Error(), "Instance 'node-2' already exists") { + t.Errorf("a request naming an existing instance = %v, want its operation to fail with HTTP 400", err) + } + if _, err := c.getResize(t, "rr-2"); sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("the failed request = %v, want HTTP 404", err) + } + + err = c.cancelResize(t, "rr-1") + if sdkerr.GoogleCode(err) != http.StatusPreconditionFailed || !strings.Contains(err.Error(), "reached a final state") { + t.Errorf("cancelling a SUCCEEDED request = %v, want HTTP 412", err) + } + if err := c.deleteResize(t, "rr-1"); err != nil { + t.Fatal(err) + } + if got := c.resizeStates(t); len(got) != 0 { + t.Errorf("requests after the delete = %v", got) + } + if got := c.managed(t); len(got) != 2 { + t.Errorf("deleting a request deleted its instances: %v", got) + } + + resizeBy := &computepb.InstanceGroupManagerResizeRequest{Name: new("rr-3"), ResizeBy: new(int32(2))} + op, err := c.resizes.Insert(t.Context(), &computepb.InsertInstanceGroupManagerResizeRequestRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, InstanceGroupManagerResizeRequestResource: resizeBy, + }) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil || len(c.managed(t)) != 4 { + t.Errorf("a request to resize by 2 = %v, leaving %v", err, c.managed(t)) + } + _, err = c.resizes.Insert(t.Context(), &computepb.InsertInstanceGroupManagerResizeRequestRequest{ + Project: project, Zone: zone, InstanceGroupManager: "missing", InstanceGroupManagerResizeRequestResource: resizeBy, + }) + if sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("a request to a missing group = %v, want HTTP 404", err) + } +} + +func TestResizeRequestWaitsUntilSettled(t *testing.T) { + c := setup(t, compute.WithSettleAfter(-1)) + c.insertGroup(t, 0) + for _, name := range []string{"rr-wait", "rr-cancel", "rr-fail", "rr-stockout"} { + if err := c.insertResize(t, name, name+"-node"); err != nil { + t.Fatalf("insert %s: %v", name, err) + } + } + if got := c.resizeStates(t); fmt.Sprint(got) != "[rr-cancel:ACCEPTED rr-fail:ACCEPTED rr-stockout:ACCEPTED rr-wait:ACCEPTED]" { + t.Fatalf("requests = %v", got) + } + if got := c.managed(t); len(got) != 0 { + t.Errorf("a queued request created instances: %v", got) + } + if err := c.insertResize(t, "rr-again", "rr-wait-node"); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("a request naming a queued instance = %v, want HTTP 400", err) + } + if err := c.deleteResize(t, "rr-wait"); sdkerr.GoogleCode(err) != http.StatusPreconditionFailed { + t.Errorf("deleting an ACCEPTED request = %v, want HTTP 412", err) + } + + if err := c.cancelResize(t, "rr-cancel"); err != nil { + t.Fatal(err) + } + if err := c.server.FailResizeRequest(project, zone, group, "rr-fail", "QUOTA_EXCEEDED", "Quota 'CPUS' exceeded."); err != nil { + t.Fatal(err) + } + if err := c.server.FailResizeAttempt(project, zone, group, "rr-stockout", "ZONE_RESOURCE_POOL_EXHAUSTED", "Not enough resources."); err != nil { + t.Fatal(err) + } + failed, err := c.getResize(t, "rr-fail") + if errs := failed.GetStatus().GetError().GetErrors(); err != nil || failed.GetState() != "FAILED" || len(errs) != 1 || errs[0].GetCode() != "QUOTA_EXCEEDED" { + t.Errorf("failed request = %v, %v", failed, err) + } + waiting, err := c.getResize(t, "rr-stockout") + if errs := waiting.GetStatus().GetLastAttempt().GetError().GetErrors(); err != nil || waiting.GetState() != "ACCEPTED" || len(errs) != 1 || errs[0].GetMessage() != "Not enough resources." { + t.Errorf("waiting request = %v, %v", waiting, err) + } + if err := c.server.FailResizeRequest(project, zone, group, "rr-cancel", "", ""); err == nil { + t.Error("failing a CANCELLED request succeeded") + } + if err := c.cancelResize(t, "rr-cancel"); sdkerr.GoogleCode(err) != http.StatusPreconditionFailed || !strings.Contains(err.Error(), "final state") { + t.Errorf("cancelling a CANCELLED request = %v, want HTTP 412", err) + } + + c.server.Settle() + if got := c.resizeStates(t); fmt.Sprint(got) != "[rr-cancel:CANCELLED rr-fail:FAILED rr-stockout:SUCCEEDED rr-wait:SUCCEEDED]" { + t.Errorf("requests after Settle = %v", got) + } + if got := c.managed(t); fmt.Sprint(got) != "[rr-stockout-node:RUNNING:NONE rr-wait-node:RUNNING:NONE]" { + t.Errorf("managed instances after Settle = %v", got) + } + if req, ok := c.server.LookupResizeRequest(project, zone, group, "rr-stockout"); !ok || req.State != "SUCCEEDED" || req.Status.LastAttempt != nil { + t.Errorf("LookupResizeRequest = %+v, %v", req, ok) + } + for _, name := range []string{"rr-cancel", "rr-fail"} { + if err := c.deleteResize(t, name); err != nil { + t.Errorf("deleting the %s request: %v", name, err) + } + } +} + +func TestResizeRequestIsCreatingOnItsLastReadInProgress(t *testing.T) { + c := setup(t, compute.WithSettleAfter(1)) + c.insertGroup(t, 0) + if err := c.insertResize(t, "rr-1", "node-1"); err != nil { + t.Fatal(err) + } + if got := c.resizeStates(t); fmt.Sprint(got) != "[rr-1:CREATING]" { + t.Fatalf("requests = %v", got) + } + if err := c.cancelResize(t, "rr-1"); sdkerr.GoogleCode(err) != http.StatusPreconditionFailed { + t.Errorf("cancelling a CREATING request = %v, want HTTP 412", err) + } + if got := c.managed(t); fmt.Sprint(got) != "[node-1:PROVISIONING:CREATING]" { + t.Errorf("managed instances = %v", got) + } + if req, err := c.getResize(t, "rr-1"); err != nil || req.GetState() != "SUCCEEDED" { + t.Errorf("request after its reads = %v, %v", req, err) + } + if inst, err := c.get(t, "node-1"); err != nil || inst.GetStatus() != "RUNNING" { + t.Errorf("instance = %v, %v", inst, err) + } + + if err := c.insertResize(t, "rr-2", "node-2"); err != nil { + t.Fatal(err) + } + if req, _ := c.getResize(t, "rr-2"); req.GetState() != "CREATING" { + t.Fatalf("state = %s", req.GetState()) + } + if err := c.server.FailResizeRequest(project, zone, group, "rr-2", "", ""); err != nil { + t.Fatal(err) + } + if _, err := c.get(t, "node-2"); sdkerr.GoogleCode(err) != http.StatusNotFound { + t.Errorf("an instance of a failed request = %v, want HTTP 404", err) + } + if req, _ := c.getResize(t, "rr-2"); req.GetState() != "FAILED" || req.GetStatus().GetError() != nil { + t.Errorf("failed request = %v", req) + } +} + +func TestGroupFaultsAndPermissions(t *testing.T) { + faults := fault.New() + c := setup(t, compute.WithFaults(faults)) + c.insertGroup(t, 0) + groupPath := "projects/p/zones/" + zone + "/instanceGroupManagers/" + group + faults.Add( + fault.Rule{Method: "compute.instanceGroupManagers.createInstances", Resource: groupPath, Times: 1, Fault: fault.FailOperation(http.StatusInternalServerError)}, + fault.Rule{ + Method: "compute.instanceGroupManagerResizeRequests.insert", Resource: groupPath + "/resizeRequests/rr-1", Times: 1, + Fault: fault.Reject(http.StatusServiceUnavailable, "").WithMessage("Internal error."), + }, + fault.Rule{Method: "compute.instanceGroupManagers.listManagedInstances", Resource: groupPath, Times: 1, Fault: fault.FailOperation(http.StatusInternalServerError)}, + ) + if err := c.createInstances(t, "node-1"); sdkerr.GoogleCode(err) != http.StatusInternalServerError { + t.Errorf("createInstances with a failed operation = %v, want HTTP 500", err) + } + if got := c.server.Instances(); len(got) != 0 { + t.Errorf("a failed createInstances took effect: %d instances", len(got)) + } + if err := c.insertResize(t, "rr-1", "node-1"); sdkerr.GoogleCode(err) != http.StatusServiceUnavailable || !strings.Contains(err.Error(), "Internal error.") { + t.Errorf("a rejected resize request = %v, want HTTP 503", err) + } + it := c.managers.ListManagedInstances(t.Context(), &computepb.ListManagedInstancesInstanceGroupManagersRequest{Project: project, Zone: zone, InstanceGroupManager: group}) + if _, err := it.Next(); sdkerr.GoogleCode(err) != http.StatusInternalServerError { + t.Errorf("listManagedInstances with an operation fault = %v, want HTTP 500", err) + } + if err := c.insertResize(t, "rr-1", "node-1"); err != nil { + t.Errorf("the resize request after its fault = %v", err) + } + + policy := access.Allow("compute.instanceGroupManagers.get", "compute.zoneOperations.get") + d := setup(t, compute.WithPolicy(policy)) + _, err := d.managers.CreateInstances(t.Context(), &computepb.CreateInstancesInstanceGroupManagerRequest{ + Project: project, Zone: zone, InstanceGroupManager: group, + InstanceGroupManagersCreateInstancesRequestResource: &computepb.InstanceGroupManagersCreateInstancesRequest{}, + }) + if sdkerr.GoogleCode(err) != http.StatusForbidden || !strings.Contains(err.Error(), "compute.instanceGroupManagers.update") { + t.Errorf("createInstances without compute.instanceGroupManagers.update = %v, want HTTP 403", err) + } + if denials := policy.Denials(); len(denials) != 1 || !slices.Equal(denials[0].Missing, []string{"compute.instanceGroupManagers.update"}) { + t.Errorf("Denials() = %+v", denials) + } +} diff --git a/sdktest/gcp/compute/instances_test.go b/sdktest/gcp/compute/instances_test.go index 69a10a7..0b2ffee 100644 --- a/sdktest/gcp/compute/instances_test.go +++ b/sdktest/gcp/compute/instances_test.go @@ -38,6 +38,7 @@ type clients struct { routes *gcompute.RoutesClient templates *gcompute.InstanceTemplatesClient managers *gcompute.InstanceGroupManagersClient + resizes *gcompute.InstanceGroupManagerResizeRequestsClient policies *gcomputebeta.ResourcePoliciesClient networks *gcompute.NetworksClient subnets *gcompute.SubnetworksClient @@ -70,6 +71,10 @@ func setup(t *testing.T, opts ...compute.Option) *clients { func() error { c.routes, err = gcompute.NewRoutesRESTClient(ctx, o...); return err }, func() error { c.templates, err = gcompute.NewInstanceTemplatesRESTClient(ctx, o...); return err }, func() error { c.managers, err = gcompute.NewInstanceGroupManagersRESTClient(ctx, o...); return err }, + func() error { + c.resizes, err = gcompute.NewInstanceGroupManagerResizeRequestsRESTClient(ctx, o...) + return err + }, func() error { c.policies, err = gcomputebeta.NewResourcePoliciesRESTClient(ctx, o...); return err }, func() error { c.networks, err = gcompute.NewNetworksRESTClient(ctx, o...); return err }, func() error { c.subnets, err = gcompute.NewSubnetworksRESTClient(ctx, o...); return err }, diff --git a/sdktest/gcp/compute/region_instances_test.go b/sdktest/gcp/compute/region_instances_test.go new file mode 100644 index 0000000..f5beb21 --- /dev/null +++ b/sdktest/gcp/compute/region_instances_test.go @@ -0,0 +1,195 @@ +package compute_test + +import ( + "net/http" + "slices" + "strings" + "testing" + + gcompute "cloud.google.com/go/compute/apiv1" + "cloud.google.com/go/compute/apiv1/computepb" + "google.golang.org/api/option" + + "github.com/parallelworks/squall/access" + "github.com/parallelworks/squall/fault" + "github.com/parallelworks/squall/gcp/compute" + "github.com/parallelworks/squall/sdktest/internal/sdkerr" +) + +func regionInstancesClient(t *testing.T, c *clients) *gcompute.RegionInstancesClient { + t.Helper() + client, err := gcompute.NewRegionInstancesRESTClient(t.Context(), option.WithEndpoint(c.url), option.WithoutAuthentication()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = client.Close() }) + return client +} + +func regionBulkRequest(policy *computepb.LocationPolicy, names ...string) *computepb.BulkInsertRegionInstanceRequest { + zonal := bulkRequest("s", names...) + zonal.BulkInsertInstanceResourceResource.LocationPolicy = policy + return &computepb.BulkInsertRegionInstanceRequest{Project: project, Region: "us-east1", BulkInsertInstanceResourceResource: zonal.BulkInsertInstanceResourceResource} +} + +// placement is the zone of each instance, as name@zone in name order. +func placement(c *clients) []string { + var out []string + for _, inst := range c.server.Instances() { + out = append(out, inst.Name+"@"+inst.Zone[strings.LastIndexByte(inst.Zone, '/')+1:]) + } + slices.Sort(out) + return out +} + +func TestRegionBulkInsertPlacesInstancesInTheRegionsZones(t *testing.T) { + c := setup(t) + region := regionInstancesClient(t, c) + + op, err := region.BulkInsert(t.Context(), regionBulkRequest(nil, "node-1", "node-2")) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatal(err) + } + p := op.Proto() + st := p.GetInstancesBulkInsertOperationMetadata().GetPerLocationStatus() + if p.GetOperationType() != "bulkInsert" || !strings.HasSuffix(p.GetRegion(), "/regions/us-east1") || p.GetZone() != "" || + p.GetTargetLink() != "https://www.googleapis.com/compute/v1/projects/p" || + len(st) != 1 || st["zones/us-east1-b"].GetCreatedVmCount() != 2 || st["zones/us-east1-b"].GetStatus() != "DONE" { + t.Errorf("operation = %v", p) + } + if got := placement(c); !slices.Equal(got, []string{"node-1@us-east1-b", "node-2@us-east1-b"}) { + t.Errorf("placement = %v, want every instance in the first zone", got) + } + + balanced := &computepb.LocationPolicy{ + TargetShape: new("BALANCED"), + Locations: map[string]*computepb.LocationPolicyLocation{"zones/us-east1-b": {Preference: new("DENY")}, "zones/us-east1-c": {Preference: new("ALLOW")}}, + } + op, err = region.BulkInsert(t.Context(), regionBulkRequest(balanced, "node-3", "node-4", "node-5")) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatal(err) + } + st = op.Proto().GetInstancesBulkInsertOperationMetadata().GetPerLocationStatus() + if len(st) != 2 || st["zones/us-east1-c"].GetCreatedVmCount() != 2 || st["zones/us-east1-d"].GetCreatedVmCount() != 1 { + t.Errorf("perLocationStatus = %v", st) + } + want := []string{"node-1@us-east1-b", "node-2@us-east1-b", "node-3@us-east1-c", "node-4@us-east1-d", "node-5@us-east1-c"} + if got := placement(c); !slices.Equal(got, want) { + t.Errorf("placement = %v, want %v", got, want) + } + if _, ok := c.server.LookupDisk(project, "us-east1-d", "node-4"); !ok { + t.Error("node-4's boot disk is not in its zone") + } +} + +func TestRegionBulkInsertSharesTheZonalRules(t *testing.T) { + c := setup(t) + region := regionInstancesClient(t, c) + if err := c.bulkInsert(t, bulkRequest("s", "vm-07")); err != nil { + t.Fatal(err) + } + + pattern := &computepb.BulkInsertRegionInstanceRequest{Project: project, Region: "us-east1", BulkInsertInstanceResourceResource: &computepb.BulkInsertInstanceResource{ + Count: new(int64(2)), NamePattern: new("vm-##"), InstanceProperties: properties("s"), + LocationPolicy: &computepb.LocationPolicy{Locations: map[string]*computepb.LocationPolicyLocation{"zones/" + zone: {Preference: new("DENY")}}}, + }} + op, err := region.BulkInsert(t.Context(), pattern) + if err == nil { + err = op.Wait(t.Context()) + } + if err != nil { + t.Fatal(err) + } + if got := placement(c); !slices.Equal(got, []string{"vm-07@us-east1-b", "vm-08@us-east1-c", "vm-09@us-east1-c"}) { + t.Errorf("placement = %v, want the pattern numbered after every zone's instances", got) + } + + op, err = region.BulkInsert(t.Context(), regionBulkRequest(nil, "vm-08")) + if err == nil { + err = op.Wait(t.Context()) + } + if sdkerr.GoogleCode(err) != http.StatusConflict || !strings.Contains(err.Error(), "VM_MIN_COUNT_NOT_REACHED") || + !strings.Contains(err.Error(), "projects/p/zones/us-east1-c/instances/vm-08' already exists") { + t.Errorf("a name another zone of the region holds = %v, want a 409 operation error", err) + } + + for name, policy := range map[string]*computepb.LocationPolicy{ + "a zone of another region": {Locations: map[string]*computepb.LocationPolicyLocation{"zones/us-west1-a": {Preference: new("ALLOW")}}}, + "every zone denied": {Locations: map[string]*computepb.LocationPolicyLocation{ + "zones/us-east1-b": {Preference: new("DENY")}, "zones/us-east1-c": {Preference: new("DENY")}, "zones/us-east1-d": {Preference: new("DENY")}, + }}, + } { + if _, err := region.BulkInsert(t.Context(), regionBulkRequest(policy, "other")); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("%s = %v, want HTTP 400", name, err) + } + } + unknown := regionBulkRequest(nil, "other") + unknown.Region = "mars-north1" + if _, err := region.BulkInsert(t.Context(), unknown); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("a region with no zones = %v, want HTTP 400", err) + } +} + +func TestRegionBulkInsertFaults(t *testing.T) { + faults := fault.New().Add(fault.Rule{ + Method: "compute.regionInstances.bulkInsert", Resource: "projects/p/regions/us-east1/instances/node-1", + Fault: fault.FailOperation(http.StatusBadRequest).WithMessage("no capacity"), + }) + c := setup(t, compute.WithFaults(faults)) + region := regionInstancesClient(t, c) + + op, err := region.BulkInsert(t.Context(), regionBulkRequest(nil, "node-2", "node-1")) + if err != nil { + t.Fatal(err) + } + if err := op.Wait(t.Context()); sdkerr.GoogleCode(err) != http.StatusBadRequest || !strings.Contains(err.Error(), "no capacity") { + t.Errorf("wait = %v, want the fault's message", err) + } + if st := op.Proto().GetInstancesBulkInsertOperationMetadata().GetPerLocationStatus()["zones/us-east1-b"]; st.GetFailedToCreateVmCount() != 2 { + t.Errorf("perLocationStatus = %v", st) + } + if len(c.server.Instances()) != 0 { + t.Error("a failed operation created instances") + } + if got := faults.Injected(); len(got) != 1 { + t.Errorf("injected = %v", got) + } +} + +func TestRegionBulkInsertSettles(t *testing.T) { + c := setup(t, compute.WithSettleAfter(-1)) + region := regionInstancesClient(t, c) + op, err := region.BulkInsert(t.Context(), regionBulkRequest(nil, "node-1")) + if err != nil { + t.Fatal(err) + } + if st := op.Proto().GetInstancesBulkInsertOperationMetadata().GetPerLocationStatus()["zones/us-east1-b"]; st.GetStatus() != "CREATING" || op.Done() { + t.Errorf("before Settle: done %v, perLocationStatus %v", op.Done(), st) + } + c.server.Settle() + if err := op.Poll(t.Context()); err != nil { + t.Fatal(err) + } + if st := op.Proto().GetInstancesBulkInsertOperationMetadata().GetPerLocationStatus()["zones/us-east1-b"]; !op.Done() || st.GetCreatedVmCount() != 1 { + t.Errorf("after Settle: done %v, perLocationStatus %v", op.Done(), st) + } +} + +func TestRegionBulkInsertNeedsInstancesCreate(t *testing.T) { + c := setup(t, compute.WithPolicy(access.Allow( + "compute.instances.create", "compute.disks.create", "compute.images.useReadOnly", "compute.disks.setLabels", + "compute.subnetworks.use", "compute.subnetworks.useExternalIp", "compute.instances.setTags", + "compute.instances.setLabels", "compute.instances.setServiceAccount", "iam.serviceAccounts.actAs", + ))) + region := regionInstancesClient(t, c) + if _, err := region.BulkInsert(t.Context(), regionBulkRequest(nil, "node-1")); sdkerr.GoogleCode(err) != http.StatusForbidden || + !strings.Contains(err.Error(), "compute.instances.setMetadata") { + t.Errorf("bulkInsert without compute.instances.setMetadata = %v, want HTTP 403 naming it", err) + } +} diff --git a/sdktest/gcp/compute/suspend_test.go b/sdktest/gcp/compute/suspend_test.go new file mode 100644 index 0000000..4520c9b --- /dev/null +++ b/sdktest/gcp/compute/suspend_test.go @@ -0,0 +1,77 @@ +package compute_test + +import ( + "net/http" + "strings" + "testing" + + "cloud.google.com/go/compute/apiv1/computepb" + + "github.com/parallelworks/squall/gcp/compute" + "github.com/parallelworks/squall/sdktest/internal/sdkerr" +) + +func TestSuspendAndResume(t *testing.T) { + c := setup(t) + if err := c.insert(t, single("vm-1", "s")); err != nil { + t.Fatal(err) + } + suspend := func() error { + op, err := c.instances.Suspend(t.Context(), &computepb.SuspendInstanceRequest{Project: project, Zone: zone, Instance: "vm-1"}) + if err != nil { + return err + } + return op.Wait(t.Context()) + } + resume := func() error { + op, err := c.instances.Resume(t.Context(), &computepb.ResumeInstanceRequest{Project: project, Zone: zone, Instance: "vm-1"}) + if err != nil { + return err + } + return op.Wait(t.Context()) + } + if err := suspend(); err != nil { + t.Fatal(err) + } + if got, _ := c.get(t, "vm-1"); got.GetStatus() != "SUSPENDED" || got.GetLastSuspendedTimestamp() == "" { + t.Fatalf("suspended instance = %v", got) + } + if err := suspend(); err != nil { + t.Fatalf("suspending again = %v, want a no-op", err) + } + if err := resume(); err != nil { + t.Fatal(err) + } + if got, _ := c.get(t, "vm-1"); got.GetStatus() != "RUNNING" { + t.Fatalf("resumed instance = %v", got) + } + + stop, err := c.instances.Stop(t.Context(), &computepb.StopInstanceRequest{Project: project, Zone: zone, Instance: "vm-1"}) + if err != nil || stop.Wait(t.Context()) != nil { + t.Fatalf("stop = %v", err) + } + if err := suspend(); sdkerr.GoogleCode(err) != http.StatusBadRequest || !strings.Contains(err.Error(), "RESOURCE_NOT_READY") { + t.Errorf("suspending a stopped instance = %v, want an operation that fails with RESOURCE_NOT_READY", err) + } + if err := resume(); sdkerr.GoogleCode(err) != http.StatusBadRequest { + t.Errorf("resuming a stopped instance = %v, want HTTP 400", err) + } +} + +func TestSuspendInProgress(t *testing.T) { + c := setup(t, compute.WithSettleAfter(-1)) + if _, err := c.instances.Insert(t.Context(), &computepb.InsertInstanceRequest{Project: project, Zone: zone, InstanceResource: single("vm-1", "s")}); err != nil { + t.Fatal(err) + } + c.server.Settle() + if _, err := c.instances.Suspend(t.Context(), &computepb.SuspendInstanceRequest{Project: project, Zone: zone, Instance: "vm-1"}); err != nil { + t.Fatal(err) + } + if got, _ := c.get(t, "vm-1"); got.GetStatus() != "SUSPENDING" { + t.Errorf("status while suspending = %s", got.GetStatus()) + } + c.server.Settle() + if got, _ := c.get(t, "vm-1"); got.GetStatus() != "SUSPENDED" { + t.Errorf("status once settled = %s", got.GetStatus()) + } +}