From 36e7d4486629eb96ad1649570d320042c7cf171d Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Mon, 15 Jul 2024 10:05:23 +0000 Subject: [PATCH 1/9] Instance Create: Migrate to egoscale v3 and add multiple sshkeys Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- cmd/instance_create.go | 158 ++-- go.mod | 3 +- go.sum | 6 +- .../exoscale/egoscale/v2/staticcheck.conf | 2 + .../github.com/exoscale/egoscale/v3/LICENSE | 201 +++++ .../github.com/exoscale/egoscale/v3/README.md | 2 +- vendor/github.com/exoscale/egoscale/v3/api.go | 49 -- .../github.com/exoscale/egoscale/v3/client.go | 13 +- .../github.com/exoscale/egoscale/v3/errors.go | 125 ++++ .../exoscale/egoscale/v3/operations.go | 694 +++++++++--------- .../exoscale/egoscale/v3/schemas.go | 148 ++-- .../exoscale/egoscale/v3/version.go | 4 + vendor/modules.txt | 8 +- 13 files changed, 917 insertions(+), 496 deletions(-) create mode 100644 vendor/github.com/exoscale/egoscale/v2/staticcheck.conf create mode 100644 vendor/github.com/exoscale/egoscale/v3/LICENSE create mode 100644 vendor/github.com/exoscale/egoscale/v3/errors.go create mode 100644 vendor/github.com/exoscale/egoscale/v3/version.go diff --git a/cmd/instance_create.go b/cmd/instance_create.go index ec34aa884..a70869d44 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -19,9 +19,7 @@ import ( "github.com/exoscale/cli/pkg/output" exossh "github.com/exoscale/cli/pkg/ssh" "github.com/exoscale/cli/pkg/userdata" - "github.com/exoscale/cli/utils" - egoscale "github.com/exoscale/egoscale/v2" - exoapi "github.com/exoscale/egoscale/v2/api" + v3 "github.com/exoscale/egoscale/v3" ) type instanceCreateCmd struct { @@ -41,11 +39,11 @@ type instanceCreateCmd struct { Labels map[string]string `cli-flag:"label" cli-usage:"instance label (format: key=value)"` PrivateNetworks []string `cli-flag:"private-network" cli-usage:"instance Private Network NAME|ID (can be specified multiple times)"` PrivateInstance bool `cli-flag:"private-instance" cli-usage:"enable private instance to be created"` - SSHKey string `cli-flag:"ssh-key" cli-usage:"SSH key to deploy on the instance"` + SSHKeys []string `cli-flag:"ssh-key" cli-usage:"SSH keys to deploy on the instance"` SecurityGroups []string `cli-flag:"security-group" cli-usage:"instance Security Group NAME|ID (can be specified multiple times)"` Template string `cli-usage:"instance template NAME|ID"` TemplateVisibility string `cli-usage:"instance template visibility (public|private)"` - Zone string `cli-short:"z" cli-usage:"instance zone"` + Zone v3.ZoneName `cli-short:"z" cli-usage:"instance zone"` } func (c *instanceCreateCmd) cmdAliases() []string { return gCreateAlias } @@ -75,59 +73,79 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin var ( singleUseSSHPrivateKey *rsa.PrivateKey singleUseSSHPublicKey ssh.PublicKey - sshKey *egoscale.SSHKey ) + ctx := gContext + client, err := switchClientZoneV3(ctx, globalstate.EgoscaleV3Client, c.Zone) + if err != nil { + return err + } - instance := &egoscale.Instance{ - DiskSize: &c.DiskSize, - IPv6Enabled: &c.IPv6, - Labels: func() (v *map[string]string) { - if len(c.Labels) > 0 { - return &c.Labels - } - return - }(), - Name: &c.Name, - SSHKey: utils.NonEmptyStringPtr(c.SSHKey), + var sshKeys []v3.SSHKey + for _, sshkeyName := range c.SSHKeys { + sshKeys = append(sshKeys, v3.SSHKey{Name: sshkeyName}) } - if c.PrivateInstance { - t := "none" - instance.PublicIPAssignment = &t + instanceReq := v3.CreateInstanceRequest{ + DiskSize: c.DiskSize, + Ipv6Enabled: &c.IPv6, + Labels: c.Labels, + Name: c.Name, + SSHKeys: sshKeys, } - ctx := exoapi.WithEndpoint(gContext, exoapi.NewReqEndpoint(account.CurrentAccount.Environment, c.Zone)) + if c.PrivateInstance { + instanceReq.PublicIPAssignment = v3.PublicIPAssignmentNone + } if l := len(c.AntiAffinityGroups); l > 0 { - antiAffinityGroupIDs := make([]string, l) + antiAffinityGroupIDs := make([]v3.AntiAffinityGroup, l) + af, err := client.ListAntiAffinityGroups(ctx) + if err != nil { + return fmt.Errorf("error listing Anti-Affinity Group: %w", err) + } for i := range c.AntiAffinityGroups { - antiAffinityGroup, err := globalstate.EgoscaleClient.FindAntiAffinityGroup(ctx, c.Zone, c.AntiAffinityGroups[i]) + antiAffinityGroup, err := af.FindAntiAffinityGroup(c.AntiAffinityGroups[i]) if err != nil { return fmt.Errorf("error retrieving Anti-Affinity Group: %w", err) } - antiAffinityGroupIDs[i] = *antiAffinityGroup.ID + antiAffinityGroupIDs[i] = antiAffinityGroup } - instance.AntiAffinityGroupIDs = &antiAffinityGroupIDs + + instanceReq.AntiAffinityGroups = antiAffinityGroupIDs } if c.DeployTarget != "" { - deployTarget, err := globalstate.EgoscaleClient.FindDeployTarget(ctx, c.Zone, c.DeployTarget) + targets, err := client.ListDeployTargets(ctx) + if err != nil { + return fmt.Errorf("error listing Deploy Target: %w", err) + } + deployTarget, err := targets.FindDeployTarget(c.DeployTarget) if err != nil { return fmt.Errorf("error retrieving Deploy Target: %w", err) } - instance.DeployTargetID = deployTarget.ID + instanceReq.DeployTarget = &deployTarget } - instanceType, err := globalstate.EgoscaleClient.FindInstanceType(ctx, c.Zone, c.InstanceType) + instanceTypes, err := client.ListInstanceTypes(ctx) + if err != nil { + return fmt.Errorf("error listing instance type: %w", err) + } + + instanceType, err := instanceTypes.FindInstanceType(c.InstanceType) if err != nil { return fmt.Errorf("error retrieving instance type: %w", err) } - instance.InstanceTypeID = instanceType.ID + instanceReq.InstanceType = &instanceType - privateNetworks := make([]*egoscale.PrivateNetwork, len(c.PrivateNetworks)) + privateNetworks := make([]v3.PrivateNetwork, len(c.PrivateNetworks)) if l := len(c.PrivateNetworks); l > 0 { + pNetworks, err := client.ListPrivateNetworks(ctx) + if err != nil { + return fmt.Errorf("error listing Private Network: %w", err) + } + for i := range c.PrivateNetworks { - privateNetwork, err := globalstate.EgoscaleClient.FindPrivateNetwork(ctx, c.Zone, c.PrivateNetworks[i]) + privateNetwork, err := pNetworks.FindPrivateNetwork(c.PrivateNetworks[i]) if err != nil { return fmt.Errorf("error retrieving Private Network: %w", err) } @@ -136,23 +154,26 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin } if l := len(c.SecurityGroups); l > 0 { - securityGroupIDs := make([]string, l) + sgs, err := client.ListSecurityGroups(ctx) + if err != nil { + return fmt.Errorf("error listing Security Group: %w", err) + } + instanceReq.SecurityGroups = make([]v3.SecurityGroup, l) for i := range c.SecurityGroups { - securityGroup, err := globalstate.EgoscaleClient.FindSecurityGroup(ctx, c.Zone, c.SecurityGroups[i]) + securityGroup, err := sgs.FindSecurityGroup(c.SecurityGroups[i]) if err != nil { return fmt.Errorf("error retrieving Security Group: %w", err) } - securityGroupIDs[i] = *securityGroup.ID + instanceReq.SecurityGroups[i] = securityGroup } - instance.SecurityGroupIDs = &securityGroupIDs } - if instance.SSHKey == nil && account.CurrentAccount.DefaultSSHKey != "" { - instance.SSHKey = &account.CurrentAccount.DefaultSSHKey + if instanceReq.SSHKeys == nil && account.CurrentAccount.DefaultSSHKey != "" { + instanceReq.SSHKeys = []v3.SSHKey{{Name: account.CurrentAccount.DefaultSSHKey}} } // Generating a single-use SSH key pair for this instance. - if instance.SSHKey == nil { + if instanceReq.SSHKeys == nil { singleUseSSHPrivateKey, err = rsa.GenerateKey(rand.Reader, 2048) if err != nil { return fmt.Errorf("error generating SSH private key: %w", err) @@ -166,20 +187,30 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin return fmt.Errorf("error generating SSH public key: %w", err) } - sshKey, err = globalstate.EgoscaleClient.RegisterSSHKey( + sshKeyName := fmt.Sprintf("%s-%d", c.Name, time.Now().Unix()) + op, err := client.RegisterSSHKey( ctx, - c.Zone, - fmt.Sprintf("%s-%d", c.Name, time.Now().Unix()), - string(ssh.MarshalAuthorizedKey(singleUseSSHPublicKey)), + v3.RegisterSSHKeyRequest{ + Name: sshKeyName, + PublicKey: string(ssh.MarshalAuthorizedKey(singleUseSSHPublicKey)), + }, ) if err != nil { return fmt.Errorf("error registering SSH key: %w", err) } + _, err = client.Wait(ctx, op, v3.OperationStateSuccess) + if err != nil { + return fmt.Errorf("error wait registering SSH key: %w", err) + } - instance.SSHKey = sshKey.Name + instanceReq.SSHKeys = []v3.SSHKey{{Name: sshKeyName}} } - template, err := globalstate.EgoscaleClient.FindTemplate(ctx, c.Zone, c.Template, c.TemplateVisibility) + templates, err := client.ListTemplates(ctx, v3.ListTemplatesWithVisibility(v3.ListTemplatesVisibility(c.TemplateVisibility))) + if err != nil { + return fmt.Errorf("error listing template with visibility %q: %w", c.TemplateVisibility, err) + } + template, err := templates.FindTemplate(c.Template) if err != nil { return fmt.Errorf( "no template %q found with visibility %s in zone %s", @@ -188,24 +219,41 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin c.Zone, ) } - instance.TemplateID = template.ID + instanceReq.Template = &template if c.CloudInitFile != "" { userData, err := userdata.GetUserDataFromFile(c.CloudInitFile, c.CloudInitCompress) if err != nil { return fmt.Errorf("error parsing cloud-init user data: %w", err) } - instance.UserData = &userData + instanceReq.UserData = userData } + var instanceID v3.UUID decorateAsyncOperation(fmt.Sprintf("Creating instance %q...", c.Name), func() { - instance, err = globalstate.EgoscaleClient.CreateInstance(ctx, c.Zone, instance) + var op *v3.Operation + op, err = client.CreateInstance(ctx, instanceReq) if err != nil { return } + op, err = client.Wait(ctx, op, v3.OperationStateSuccess) + if err != nil { + return + } + if op.Reference != nil { + instanceID = op.Reference.ID + } + for _, p := range privateNetworks { - if err = globalstate.EgoscaleClient.AttachInstanceToPrivateNetwork(ctx, c.Zone, instance, p); err != nil { + op, err = client.AttachInstanceToPrivateNetwork(ctx, p.ID, v3.AttachInstanceToPrivateNetworkRequest{ + Instance: &v3.AttachInstanceToPrivateNetworkRequestInstance{ID: instanceID}, + }) + if err != nil { + return + } + _, err = client.Wait(ctx, op) + if err != nil { return } } @@ -215,7 +263,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin } if singleUseSSHPrivateKey != nil { - privateKeyFilePath := exossh.GetInstanceSSHKeyPath(*instance.ID) + privateKeyFilePath := exossh.GetInstanceSSHKeyPath(instanceID.String()) if err = os.MkdirAll(path.Dir(privateKeyFilePath), 0o700); err != nil { return fmt.Errorf("error writing SSH private key file: %w", err) @@ -232,16 +280,22 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin return fmt.Errorf("error writing SSH private key file: %w", err) } - if err = globalstate.EgoscaleClient.DeleteSSHKey(ctx, c.Zone, sshKey); err != nil { + op, err := client.DeleteSSHKey(ctx, sshKeys[0].Name) + if err != nil { return fmt.Errorf("error deleting SSH key: %w", err) } + _, err = client.Wait(ctx, op, v3.OperationStateSuccess) + if err != nil { + return fmt.Errorf("error wait deleting SSH key: %w", err) + } } if !globalstate.Quiet { return (&instanceShowCmd{ cliCommandSettings: c.cliCommandSettings, - Instance: *instance.ID, - Zone: c.Zone, + Instance: instanceID.String(), + // migrate instanceShow to v3 to pass v3.ZoneName + Zone: string(c.Zone), }).cmdRun(nil, nil) } diff --git a/go.mod b/go.mod index 7989945a0..c2e314f65 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,8 @@ require ( github.com/aws/aws-sdk-go-v2/service/s3 v1.2.0 github.com/aws/smithy-go v1.1.0 github.com/dustin/go-humanize v1.0.1 - github.com/exoscale/egoscale v0.102.4-0.20240506093113-3ae83713b097 + github.com/exoscale/egoscale v0.102.5-0.20240712161721-275fc20694fd + github.com/exoscale/egoscale/v3 v3.1.1-0.20240712161721-275fc20694fd github.com/exoscale/openapi-cli-generator v1.1.0 github.com/fatih/camelcase v1.0.0 github.com/google/uuid v1.4.0 diff --git a/go.sum b/go.sum index f1f9c465c..8afdc2a3f 100644 --- a/go.sum +++ b/go.sum @@ -195,8 +195,10 @@ github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go. github.com/envoyproxy/go-control-plane v0.10.1/go.mod h1:AY7fTTXNdv/aJ2O5jwpxAPOWUZ7hQAEvzN5Pf27BkQQ= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/envoyproxy/protoc-gen-validate v0.6.2/go.mod h1:2t7qjJNvHPx8IjnBOzl9E9/baC+qXE/TeeyBRzgJDws= -github.com/exoscale/egoscale v0.102.4-0.20240506093113-3ae83713b097 h1:nr8gLscG7DHFUIPuyLebhrtGcd6OM+LUjcAX3erF7Y4= -github.com/exoscale/egoscale v0.102.4-0.20240506093113-3ae83713b097/go.mod h1:20KZJQlNJktQon39FWSKXET1h+OicXsyLzNdjc7bNuY= +github.com/exoscale/egoscale v0.102.5-0.20240712161721-275fc20694fd h1:2rQ9GatI7MzMwfx1hX0i5znmjk8F9XCyJX/DTz9UCjE= +github.com/exoscale/egoscale v0.102.5-0.20240712161721-275fc20694fd/go.mod h1:xKtCzfF+1O6sKtMb7QANYrTher0EFhkmw8LQLu7Scm0= +github.com/exoscale/egoscale/v3 v3.1.1-0.20240712161721-275fc20694fd h1:RhnSciyRNzsa2qdAr7k8S7diePF8bx6Nyg/nmTQXMjI= +github.com/exoscale/egoscale/v3 v3.1.1-0.20240712161721-275fc20694fd/go.mod h1:lPsza7G+giSxdzvzaHSEcjEAYz/YTiu2bEEha9KVAc4= github.com/exoscale/openapi-cli-generator v1.1.0 h1:fYjmPqHR5vxlOBrbvde7eo7bISNQIFxsGn4A5/acwKA= github.com/exoscale/openapi-cli-generator v1.1.0/go.mod h1:TZBnbT7f3hJ5ImyUphJwRM+X5xF/zCQZ6o8a42gQeTs= github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= diff --git a/vendor/github.com/exoscale/egoscale/v2/staticcheck.conf b/vendor/github.com/exoscale/egoscale/v2/staticcheck.conf new file mode 100644 index 000000000..c83ec0768 --- /dev/null +++ b/vendor/github.com/exoscale/egoscale/v2/staticcheck.conf @@ -0,0 +1,2 @@ +# egoscale v2 is about to be deprecated so no linting is needed. +checks = ["-all"] diff --git a/vendor/github.com/exoscale/egoscale/v3/LICENSE b/vendor/github.com/exoscale/egoscale/v3/LICENSE new file mode 100644 index 000000000..327ecb823 --- /dev/null +++ b/vendor/github.com/exoscale/egoscale/v3/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 exoscale(tm) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/exoscale/egoscale/v3/README.md b/vendor/github.com/exoscale/egoscale/v3/README.md index 0fd26ce83..cae793dcd 100644 --- a/vendor/github.com/exoscale/egoscale/v3/README.md +++ b/vendor/github.com/exoscale/egoscale/v3/README.md @@ -1,4 +1,4 @@ -# Egoscale v3 (Alpha) +# Egoscale v3 Exoscale API Golang wrapper diff --git a/vendor/github.com/exoscale/egoscale/v3/api.go b/vendor/github.com/exoscale/egoscale/v3/api.go index 8efd97f43..5a5691942 100644 --- a/vendor/github.com/exoscale/egoscale/v3/api.go +++ b/vendor/github.com/exoscale/egoscale/v3/api.go @@ -7,7 +7,6 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" - "errors" "fmt" "io" "net/http" @@ -21,20 +20,6 @@ import ( "github.com/google/uuid" ) -var ( - // ErrNotFound represents an error indicating a non-existent resource. - ErrNotFound = errors.New("resource not found") - - // ErrTooManyFound represents an error indicating multiple results found for a single resource. - ErrTooManyFound = errors.New("multiple resources found") - - // ErrInvalidRequest represents an error indicating that the caller's request is invalid. - ErrInvalidRequest = errors.New("invalid request") - - // ErrAPIError represents an error indicating an API-side issue. - ErrAPIError = errors.New("API error") -) - type UUID string func (u UUID) String() string { @@ -256,40 +241,6 @@ func extractRequestParameters(req *http.Request) ([]string, string) { return names, values } -func handleHTTPErrorResp(resp *http.Response) error { - if resp.StatusCode >= 400 && resp.StatusCode <= 599 { - var res struct { - Message string `json:"message"` - } - - data, err := io.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("error reading response body: %s", err) - } - - if json.Valid(data) { - if err = json.Unmarshal(data, &res); err != nil { - return fmt.Errorf("error unmarshaling response: %s", err) - } - } else { - res.Message = string(data) - } - - switch { - case resp.StatusCode == http.StatusNotFound: - return ErrNotFound - - case resp.StatusCode >= 400 && resp.StatusCode < 500: - return fmt.Errorf("%w: %s", ErrInvalidRequest, res.Message) - - case resp.StatusCode >= 500: - return fmt.Errorf("%w: %s", ErrAPIError, res.Message) - } - } - - return nil -} - func dumpRequest(req *http.Request, operationID string) { if req != nil { if dump, err := httputil.DumpRequest(req, true); err == nil { diff --git a/vendor/github.com/exoscale/egoscale/v3/client.go b/vendor/github.com/exoscale/egoscale/v3/client.go index ed16d92a0..804a37800 100644 --- a/vendor/github.com/exoscale/egoscale/v3/client.go +++ b/vendor/github.com/exoscale/egoscale/v3/client.go @@ -11,7 +11,6 @@ import ( "time" "github.com/exoscale/egoscale/v3/credentials" - "github.com/exoscale/egoscale/version" "github.com/go-playground/validator/v10" ) @@ -47,13 +46,13 @@ func (c Client) GetZoneAPIEndpoint(ctx context.Context, zoneName ZoneName) (Endp if err != nil { return "", fmt.Errorf("get zone api endpoint: %w", err) } - for _, zone := range resp.Zones { - if zone.Name == zoneName { - return zone.APIEndpoint, nil - } + + zone, err := resp.FindZone(string(zoneName)) + if err != nil { + return "", fmt.Errorf("get zone api endpoint: %w", err) } - return "", fmt.Errorf("get zone api endpoint: zone name %s not found", zoneName) + return zone.APIEndpoint, nil } // Client represents an Exoscale API client. @@ -76,7 +75,7 @@ type RequestInterceptorFn func(ctx context.Context, req *http.Request) error // UserAgent is the "User-Agent" HTTP request header added to outgoing HTTP requests. var UserAgent = fmt.Sprintf("egoscale/%s (%s; %s/%s)", - version.Version, + Version, runtime.Version(), runtime.GOOS, runtime.GOARCH) diff --git a/vendor/github.com/exoscale/egoscale/v3/errors.go b/vendor/github.com/exoscale/egoscale/v3/errors.go new file mode 100644 index 000000000..39ba09dff --- /dev/null +++ b/vendor/github.com/exoscale/egoscale/v3/errors.go @@ -0,0 +1,125 @@ +package v3 + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "net/http" +) + +var ( + ErrBadRequest = errors.New(http.StatusText(http.StatusBadRequest)) + ErrUnauthorized = errors.New(http.StatusText(http.StatusUnauthorized)) + ErrPaymentRequired = errors.New(http.StatusText(http.StatusPaymentRequired)) + ErrForbidden = errors.New(http.StatusText(http.StatusForbidden)) + ErrNotFound = errors.New(http.StatusText(http.StatusNotFound)) + ErrMethodNotAllowed = errors.New(http.StatusText(http.StatusMethodNotAllowed)) + ErrNotAcceptable = errors.New(http.StatusText(http.StatusNotAcceptable)) + ErrProxyAuthRequired = errors.New(http.StatusText(http.StatusProxyAuthRequired)) + ErrRequestTimeout = errors.New(http.StatusText(http.StatusRequestTimeout)) + ErrConflict = errors.New(http.StatusText(http.StatusConflict)) + ErrGone = errors.New(http.StatusText(http.StatusGone)) + ErrLengthRequired = errors.New(http.StatusText(http.StatusLengthRequired)) + ErrPreconditionFailed = errors.New(http.StatusText(http.StatusPreconditionFailed)) + ErrRequestEntityTooLarge = errors.New(http.StatusText(http.StatusRequestEntityTooLarge)) + ErrRequestURITooLong = errors.New(http.StatusText(http.StatusRequestURITooLong)) + ErrUnsupportedMediaType = errors.New(http.StatusText(http.StatusUnsupportedMediaType)) + ErrRequestedRangeNotSatisfiable = errors.New(http.StatusText(http.StatusRequestedRangeNotSatisfiable)) + ErrExpectationFailed = errors.New(http.StatusText(http.StatusExpectationFailed)) + ErrTeapot = errors.New(http.StatusText(http.StatusTeapot)) + ErrMisdirectedRequest = errors.New(http.StatusText(http.StatusMisdirectedRequest)) + ErrUnprocessableEntity = errors.New(http.StatusText(http.StatusUnprocessableEntity)) + ErrLocked = errors.New(http.StatusText(http.StatusLocked)) + ErrFailedDependency = errors.New(http.StatusText(http.StatusFailedDependency)) + ErrTooEarly = errors.New(http.StatusText(http.StatusTooEarly)) + ErrUpgradeRequired = errors.New(http.StatusText(http.StatusUpgradeRequired)) + ErrPreconditionRequired = errors.New(http.StatusText(http.StatusPreconditionRequired)) + ErrTooManyRequests = errors.New(http.StatusText(http.StatusTooManyRequests)) + ErrRequestHeaderFieldsTooLarge = errors.New(http.StatusText(http.StatusRequestHeaderFieldsTooLarge)) + ErrUnavailableForLegalReasons = errors.New(http.StatusText(http.StatusUnavailableForLegalReasons)) + ErrInternalServerError = errors.New(http.StatusText(http.StatusInternalServerError)) + ErrNotImplemented = errors.New(http.StatusText(http.StatusNotImplemented)) + ErrBadGateway = errors.New(http.StatusText(http.StatusBadGateway)) + ErrServiceUnavailable = errors.New(http.StatusText(http.StatusServiceUnavailable)) + ErrGatewayTimeout = errors.New(http.StatusText(http.StatusGatewayTimeout)) + ErrHTTPVersionNotSupported = errors.New(http.StatusText(http.StatusHTTPVersionNotSupported)) + ErrVariantAlsoNegotiates = errors.New(http.StatusText(http.StatusVariantAlsoNegotiates)) + ErrInsufficientStorage = errors.New(http.StatusText(http.StatusInsufficientStorage)) + ErrLoopDetected = errors.New(http.StatusText(http.StatusLoopDetected)) + ErrNotExtended = errors.New(http.StatusText(http.StatusNotExtended)) + ErrNetworkAuthenticationRequired = errors.New(http.StatusText(http.StatusNetworkAuthenticationRequired)) +) + +var httpStatusCodeErrors = map[int]error{ + http.StatusBadRequest: ErrBadRequest, + http.StatusUnauthorized: ErrUnauthorized, + http.StatusPaymentRequired: ErrPaymentRequired, + http.StatusForbidden: ErrForbidden, + http.StatusNotFound: ErrNotFound, + http.StatusMethodNotAllowed: ErrMethodNotAllowed, + http.StatusNotAcceptable: ErrNotAcceptable, + http.StatusProxyAuthRequired: ErrProxyAuthRequired, + http.StatusRequestTimeout: ErrRequestTimeout, + http.StatusConflict: ErrConflict, + http.StatusGone: ErrGone, + http.StatusLengthRequired: ErrLengthRequired, + http.StatusPreconditionFailed: ErrPreconditionFailed, + http.StatusRequestEntityTooLarge: ErrRequestEntityTooLarge, + http.StatusRequestURITooLong: ErrRequestURITooLong, + http.StatusUnsupportedMediaType: ErrUnsupportedMediaType, + http.StatusRequestedRangeNotSatisfiable: ErrRequestedRangeNotSatisfiable, + http.StatusExpectationFailed: ErrExpectationFailed, + http.StatusTeapot: ErrTeapot, + http.StatusMisdirectedRequest: ErrMisdirectedRequest, + http.StatusUnprocessableEntity: ErrUnprocessableEntity, + http.StatusLocked: ErrLocked, + http.StatusFailedDependency: ErrFailedDependency, + http.StatusTooEarly: ErrTooEarly, + http.StatusUpgradeRequired: ErrUpgradeRequired, + http.StatusPreconditionRequired: ErrPreconditionRequired, + http.StatusTooManyRequests: ErrTooManyRequests, + http.StatusRequestHeaderFieldsTooLarge: ErrRequestHeaderFieldsTooLarge, + http.StatusUnavailableForLegalReasons: ErrUnavailableForLegalReasons, + http.StatusInternalServerError: ErrInternalServerError, + http.StatusNotImplemented: ErrNotImplemented, + http.StatusBadGateway: ErrBadGateway, + http.StatusServiceUnavailable: ErrServiceUnavailable, + http.StatusGatewayTimeout: ErrGatewayTimeout, + http.StatusHTTPVersionNotSupported: ErrHTTPVersionNotSupported, + http.StatusVariantAlsoNegotiates: ErrVariantAlsoNegotiates, + http.StatusInsufficientStorage: ErrInsufficientStorage, + http.StatusLoopDetected: ErrLoopDetected, + http.StatusNotExtended: ErrNotExtended, + http.StatusNetworkAuthenticationRequired: ErrNetworkAuthenticationRequired, +} + +func handleHTTPErrorResp(resp *http.Response) error { + if resp.StatusCode >= 400 && resp.StatusCode <= 599 { + var res struct { + Message string `json:"message"` + } + + data, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("error reading response body: %s", err) + } + + if json.Valid(data) { + if err = json.Unmarshal(data, &res); err != nil { + return fmt.Errorf("error unmarshaling response: %s", err) + } + } else { + res.Message = string(data) + } + + err, ok := httpStatusCodeErrors[resp.StatusCode] + if ok { + return fmt.Errorf("%w: %s", err, res.Message) + } + + return fmt.Errorf("unmapped HTTP error: status code %d, message: %s", resp.StatusCode, res.Message) + } + + return nil +} diff --git a/vendor/github.com/exoscale/egoscale/v3/operations.go b/vendor/github.com/exoscale/egoscale/v3/operations.go index ac4c7eae8..9bba6cb65 100644 --- a/vendor/github.com/exoscale/egoscale/v3/operations.go +++ b/vendor/github.com/exoscale/egoscale/v3/operations.go @@ -12,295 +12,6 @@ import ( "time" ) -type ListAccessKeysResponse struct { - AccessKeys []AccessKey `json:"access-keys,omitempty"` -} - -// List IAM Access Keys -func (c Client) ListAccessKeys(ctx context.Context) (*ListAccessKeysResponse, error) { - path := "/access-key" - - request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) - if err != nil { - return nil, fmt.Errorf("ListAccessKeys: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("ListAccessKeys: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("ListAccessKeys: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "list-access-keys") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("ListAccessKeys: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("ListAccessKeys: http response: %w", err) - } - - bodyresp := &ListAccessKeysResponse{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("ListAccessKeys: prepare Json response: %w", err) - } - - return bodyresp, nil -} - -// IAM Access Key -type CreateAccessKeyRequest struct { - // IAM Access Key name - Name string `json:"name,omitempty"` - // IAM Access Key operations - Operations []string `json:"operations,omitempty"` - // IAM Access Key Resources - Resources []AccessKeyResource `json:"resources,omitempty"` - // IAM Access Key tags - Tags []string `json:"tags,omitempty"` -} - -// This operation creates a legacy IAM Access Key, to create a key for use with IAM roles use the api-key endpoint.The corresponding secret is only available in the response returned by this operation, the caller must take care of storing it safely as there is no other way to retrieve it. -func (c Client) CreateAccessKey(ctx context.Context, req CreateAccessKeyRequest) (*AccessKey, error) { - path := "/access-key" - - body, err := prepareJSONBody(req) - if err != nil { - return nil, fmt.Errorf("CreateAccessKey: prepare Json body: %w", err) - } - - request, err := http.NewRequestWithContext(ctx, "POST", c.serverEndpoint+path, body) - if err != nil { - return nil, fmt.Errorf("CreateAccessKey: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - request.Header.Add("Content-Type", "application/json") - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("CreateAccessKey: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("CreateAccessKey: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "create-access-key") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("CreateAccessKey: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("CreateAccessKey: http response: %w", err) - } - - bodyresp := &AccessKey{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("CreateAccessKey: prepare Json response: %w", err) - } - - return bodyresp, nil -} - -type ListAccessKeyKnownOperationsResponse struct { - AccessKeyOperations []AccessKeyOperation `json:"access-key-operations,omitempty"` -} - -// Retrieve all known available IAM Access Key operations and associated tags -func (c Client) ListAccessKeyKnownOperations(ctx context.Context) (*ListAccessKeyKnownOperationsResponse, error) { - path := "/access-key-known-operations" - - request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) - if err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "list-access-key-known-operations") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: http response: %w", err) - } - - bodyresp := &ListAccessKeyKnownOperationsResponse{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("ListAccessKeyKnownOperations: prepare Json response: %w", err) - } - - return bodyresp, nil -} - -type ListAccessKeyOperationsResponse struct { - AccessKeyOperations []AccessKeyOperation `json:"access-key-operations,omitempty"` -} - -// Retrieve IAM Access Key operations and associated tags for the signing key -func (c Client) ListAccessKeyOperations(ctx context.Context) (*ListAccessKeyOperationsResponse, error) { - path := "/access-key-operations" - - request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) - if err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "list-access-key-operations") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: http response: %w", err) - } - - bodyresp := &ListAccessKeyOperationsResponse{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("ListAccessKeyOperations: prepare Json response: %w", err) - } - - return bodyresp, nil -} - -// This operation revokes the specified IAM Access Key. Access Keys created by the revoked Access Key will not be revoked. -func (c Client) RevokeAccessKey(ctx context.Context, key string) (*Operation, error) { - path := fmt.Sprintf("/access-key/%v", key) - - request, err := http.NewRequestWithContext(ctx, "DELETE", c.serverEndpoint+path, nil) - if err != nil { - return nil, fmt.Errorf("RevokeAccessKey: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("RevokeAccessKey: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("RevokeAccessKey: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "revoke-access-key") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("RevokeAccessKey: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("RevokeAccessKey: http response: %w", err) - } - - bodyresp := &Operation{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("RevokeAccessKey: prepare Json response: %w", err) - } - - return bodyresp, nil -} - -// Retrieve IAM Access Key details -func (c Client) GetAccessKey(ctx context.Context, key string) (*AccessKey, error) { - path := fmt.Sprintf("/access-key/%v", key) - - request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) - if err != nil { - return nil, fmt.Errorf("GetAccessKey: new request: %w", err) - } - request.Header.Add("User-Agent", UserAgent) - - if err := c.executeRequestInterceptors(ctx, request); err != nil { - return nil, fmt.Errorf("GetAccessKey: execute request editors: %w", err) - } - - if err := c.signRequest(request); err != nil { - return nil, fmt.Errorf("GetAccessKey: sign request: %w", err) - } - - if c.trace { - dumpRequest(request, "get-access-key") - } - - response, err := c.httpClient.Do(request) - if err != nil { - return nil, fmt.Errorf("GetAccessKey: http client do: %w", err) - } - - if c.trace { - dumpResponse(response) - } - - if err := handleHTTPErrorResp(response); err != nil { - return nil, fmt.Errorf("GetAccessKey: http response: %w", err) - } - - bodyresp := &AccessKey{} - if err := prepareJSONResponse(response, bodyresp); err != nil { - return nil, fmt.Errorf("GetAccessKey: prepare Json response: %w", err) - } - - return bodyresp, nil -} - type ListAntiAffinityGroupsResponse struct { AntiAffinityGroups []AntiAffinityGroup `json:"anti-affinity-groups,omitempty"` } @@ -308,7 +19,7 @@ type ListAntiAffinityGroupsResponse struct { // FindAntiAffinityGroup attempts to find an AntiAffinityGroup by name or ID. func (l ListAntiAffinityGroupsResponse) FindAntiAffinityGroup(nameOrID string) (AntiAffinityGroup, error) { for i, elem := range l.AntiAffinityGroups { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.AntiAffinityGroups[i], nil } } @@ -506,6 +217,17 @@ type ListAPIKeysResponse struct { APIKeys []IAMAPIKey `json:"api-keys,omitempty"` } +// FindIAMAPIKey attempts to find an IAMAPIKey by name or ID. +func (l ListAPIKeysResponse) FindIAMAPIKey(nameOrID string) (IAMAPIKey, error) { + for i, elem := range l.APIKeys { + if string(elem.Name) == nameOrID { + return l.APIKeys[i], nil + } + } + + return IAMAPIKey{}, fmt.Errorf("%q not found in ListAPIKeysResponse: %w", nameOrID, ErrNotFound) +} + // List API keys func (c Client) ListAPIKeys(ctx context.Context) (*ListAPIKeysResponse, error) { path := "/api-key" @@ -699,7 +421,7 @@ type ListBlockStorageVolumesResponse struct { // FindBlockStorageVolume attempts to find an BlockStorageVolume by name or ID. func (l ListBlockStorageVolumesResponse) FindBlockStorageVolume(nameOrID string) (BlockStorageVolume, error) { for i, elem := range l.BlockStorageVolumes { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.BlockStorageVolumes[i], nil } } @@ -772,7 +494,7 @@ type CreateBlockStorageVolumeRequest struct { Labels Labels `json:"labels,omitempty"` // Volume name Name string `json:"name,omitempty" validate:"omitempty,lte=255"` - // Volume size in GB. + // Volume size in GiB. // When a snapshot ID is supplied, this defaults to the size of the source volume, but can be set to a larger value. Size int64 `json:"size,omitempty" validate:"omitempty,gte=10"` } @@ -834,7 +556,7 @@ type ListBlockStorageSnapshotsResponse struct { // FindBlockStorageSnapshot attempts to find an BlockStorageSnapshot by name or ID. func (l ListBlockStorageSnapshotsResponse) FindBlockStorageSnapshot(nameOrID string) (BlockStorageSnapshot, error) { for i, elem := range l.BlockStorageSnapshots { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.BlockStorageSnapshots[i], nil } } @@ -1324,7 +1046,7 @@ func (c Client) DetachBlockStorageVolume(ctx context.Context, id UUID) (*Operati } type ResizeBlockStorageVolumeRequest struct { - // Volume size in GB + // Volume size in GiB Size int64 `json:"size" validate:"required,gte=11"` } @@ -1378,6 +1100,55 @@ func (c Client) ResizeBlockStorageVolume(ctx context.Context, id UUID, req Resiz return bodyresp, nil } +type GetConsoleProxyURLResponse struct { + Host string `json:"host,omitempty"` + Path string `json:"path,omitempty"` + URL string `json:"url,omitempty"` +} + +// Retrieve signed url valid for 60 seconds to connect via console-proxy websocket to VM VNC console. +func (c Client) GetConsoleProxyURL(ctx context.Context, id UUID) (*GetConsoleProxyURLResponse, error) { + path := fmt.Sprintf("/console/%v", id) + + request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) + if err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: new request: %w", err) + } + request.Header.Add("User-Agent", UserAgent) + + if err := c.executeRequestInterceptors(ctx, request); err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: execute request editors: %w", err) + } + + if err := c.signRequest(request); err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: sign request: %w", err) + } + + if c.trace { + dumpRequest(request, "get-console-proxy-url") + } + + response, err := c.httpClient.Do(request) + if err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: http client do: %w", err) + } + + if c.trace { + dumpResponse(response) + } + + if err := handleHTTPErrorResp(response); err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: http response: %w", err) + } + + bodyresp := &GetConsoleProxyURLResponse{} + if err := prepareJSONResponse(response, bodyresp); err != nil { + return nil, fmt.Errorf("GetConsoleProxyURL: prepare Json response: %w", err) + } + + return bodyresp, nil +} + type GetDBAASCACertificateResponse struct { Certificate string `json:"certificate,omitempty"` } @@ -1723,6 +1494,103 @@ func (c Client) StartDBAASGrafanaMaintenance(ctx context.Context, name string) ( return bodyresp, nil } +type ResetDBAASGrafanaUserPasswordRequest struct { + Password DBAASUserPassword `json:"password,omitempty" validate:"omitempty,gte=8,lte=256"` +} + +// If no password is provided one will be generated automatically. +func (c Client) ResetDBAASGrafanaUserPassword(ctx context.Context, serviceName string, username string, req ResetDBAASGrafanaUserPasswordRequest) (*Operation, error) { + path := fmt.Sprintf("/dbaas-grafana/%v/user/%v/password/reset", serviceName, username) + + body, err := prepareJSONBody(req) + if err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: prepare Json body: %w", err) + } + + request, err := http.NewRequestWithContext(ctx, "PUT", c.serverEndpoint+path, body) + if err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: new request: %w", err) + } + request.Header.Add("User-Agent", UserAgent) + + request.Header.Add("Content-Type", "application/json") + + if err := c.executeRequestInterceptors(ctx, request); err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: execute request editors: %w", err) + } + + if err := c.signRequest(request); err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: sign request: %w", err) + } + + if c.trace { + dumpRequest(request, "reset-dbaas-grafana-user-password") + } + + response, err := c.httpClient.Do(request) + if err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: http client do: %w", err) + } + + if c.trace { + dumpResponse(response) + } + + if err := handleHTTPErrorResp(response); err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: http response: %w", err) + } + + bodyresp := &Operation{} + if err := prepareJSONResponse(response, bodyresp); err != nil { + return nil, fmt.Errorf("ResetDBAASGrafanaUserPassword: prepare Json response: %w", err) + } + + return bodyresp, nil +} + +// Reveal the secrets of a DBaaS Grafana user +func (c Client) RevealDBAASGrafanaUserPassword(ctx context.Context, serviceName string, username string) (*DBAASUserGrafanaSecrets, error) { + path := fmt.Sprintf("/dbaas-grafana/%v/user/%v/password/reveal", serviceName, username) + + request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) + if err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: new request: %w", err) + } + request.Header.Add("User-Agent", UserAgent) + + if err := c.executeRequestInterceptors(ctx, request); err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: execute request editors: %w", err) + } + + if err := c.signRequest(request); err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: sign request: %w", err) + } + + if c.trace { + dumpRequest(request, "reveal-dbaas-grafana-user-password") + } + + response, err := c.httpClient.Do(request) + if err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: http client do: %w", err) + } + + if c.trace { + dumpResponse(response) + } + + if err := handleHTTPErrorResp(response); err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: http response: %w", err) + } + + bodyresp := &DBAASUserGrafanaSecrets{} + if err := prepareJSONResponse(response, bodyresp); err != nil { + return nil, fmt.Errorf("RevealDBAASGrafanaUserPassword: prepare Json response: %w", err) + } + + return bodyresp, nil +} + type CreateDBAASIntegrationRequest struct { DestService DBAASServiceName `json:"dest-service" validate:"required,gte=0,lte=63"` IntegrationType EnumIntegrationTypes `json:"integration-type" validate:"required"` @@ -4405,10 +4273,10 @@ type CreateDBAASServicePGRequest struct { Migration *CreateDBAASServicePGRequestMigration `json:"migration,omitempty"` // postgresql.conf configuration values PGSettings JSONSchemaPG `json:"pg-settings,omitempty"` - // PGBouncer connection pooling settings - PgbouncerSettings JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` - // PGLookout settings - PglookoutSettings JSONSchemaPglookout `json:"pglookout-settings,omitempty"` + // System-wide settings for pgbouncer. + PgbouncerSettings *JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` + // System-wide settings for pglookout. + PglookoutSettings *JSONSchemaPglookout `json:"pglookout-settings,omitempty"` // Subscription plan Plan string `json:"plan" validate:"required,gte=1,lte=128"` // ISO time of a backup to recover from for services that support arbitrary times @@ -4418,10 +4286,10 @@ type CreateDBAASServicePGRequest struct { SynchronousReplication EnumPGSynchronousReplication `json:"synchronous-replication,omitempty"` // Service is protected against termination and powering off TerminationProtection *bool `json:"termination-protection,omitempty"` - // TimescaleDB extension configuration values - TimescaledbSettings JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` - Variant EnumPGVariant `json:"variant,omitempty"` - Version DBAASPGTargetVersions `json:"version,omitempty"` + // System-wide settings for the timescaledb extension + TimescaledbSettings *JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` + Variant EnumPGVariant `json:"variant,omitempty"` + Version DBAASPGTargetVersions `json:"version,omitempty"` // Sets the maximum amount of memory to be used by a query operation (such as a sort or hash table) before writing to temporary disk files, in MB. Default is 1MB + 0.075% of total RAM (up to 32MB). WorkMem int64 `json:"work-mem,omitempty" validate:"omitempty,gte=1,lte=1024"` } @@ -4533,10 +4401,10 @@ type UpdateDBAASServicePGRequest struct { Migration *UpdateDBAASServicePGRequestMigration `json:"migration,omitempty"` // postgresql.conf configuration values PGSettings JSONSchemaPG `json:"pg-settings,omitempty"` - // PGBouncer connection pooling settings - PgbouncerSettings JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` - // PGLookout settings - PglookoutSettings JSONSchemaPglookout `json:"pglookout-settings,omitempty"` + // System-wide settings for pgbouncer. + PgbouncerSettings *JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` + // System-wide settings for pglookout. + PglookoutSettings *JSONSchemaPglookout `json:"pglookout-settings,omitempty"` // Subscription plan Plan string `json:"plan,omitempty" validate:"omitempty,gte=1,lte=128"` // Percentage of total RAM that the database server uses for shared memory buffers. Valid range is 20-60 (float), which corresponds to 20% - 60%. This setting adjusts the shared_buffers configuration value. @@ -4544,9 +4412,9 @@ type UpdateDBAASServicePGRequest struct { SynchronousReplication EnumPGSynchronousReplication `json:"synchronous-replication,omitempty"` // Service is protected against termination and powering off TerminationProtection *bool `json:"termination-protection,omitempty"` - // TimescaleDB extension configuration values - TimescaledbSettings JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` - Variant EnumPGVariant `json:"variant,omitempty"` + // System-wide settings for the timescaledb extension + TimescaledbSettings *JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` + Variant EnumPGVariant `json:"variant,omitempty"` // Version Version string `json:"version,omitempty"` // Sets the maximum amount of memory to be used by a query operation (such as a sort or hash table) before writing to temporary disk files, in MB. Default is 1MB + 0.075% of total RAM (up to 32MB). @@ -5834,6 +5702,17 @@ type ListDBAASServicesResponse struct { DBAASServices []DBAASServiceCommon `json:"dbaas-services,omitempty"` } +// FindDBAASServiceCommon attempts to find an DBAASServiceCommon by name or ID. +func (l ListDBAASServicesResponse) FindDBAASServiceCommon(nameOrID string) (DBAASServiceCommon, error) { + for i, elem := range l.DBAASServices { + if string(elem.Name) == nameOrID { + return l.DBAASServices[i], nil + } + } + + return DBAASServiceCommon{}, fmt.Errorf("%q not found in ListDBAASServicesResponse: %w", nameOrID, ErrNotFound) +} + // List DBaaS services func (c Client) ListDBAASServices(ctx context.Context) (*ListDBAASServicesResponse, error) { path := "/dbaas-service" @@ -6008,6 +5887,17 @@ type ListDBAASServiceTypesResponse struct { DBAASServiceTypes []DBAASServiceType `json:"dbaas-service-types,omitempty"` } +// FindDBAASServiceType attempts to find an DBAASServiceType by name or ID. +func (l ListDBAASServiceTypesResponse) FindDBAASServiceType(nameOrID string) (DBAASServiceType, error) { + for i, elem := range l.DBAASServiceTypes { + if string(elem.Name) == nameOrID { + return l.DBAASServiceTypes[i], nil + } + } + + return DBAASServiceType{}, fmt.Errorf("%q not found in ListDBAASServiceTypesResponse: %w", nameOrID, ErrNotFound) +} + // List available service types for DBaaS func (c Client) ListDBAASServiceTypes(ctx context.Context) (*ListDBAASServiceTypesResponse, error) { path := "/dbaas-service-type" @@ -6665,7 +6555,7 @@ type ListDeployTargetsResponse struct { // FindDeployTarget attempts to find an DeployTarget by name or ID. func (l ListDeployTargetsResponse) FindDeployTarget(nameOrID string) (DeployTarget, error) { for i, elem := range l.DeployTargets { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.DeployTargets[i], nil } } @@ -6763,6 +6653,17 @@ type ListDNSDomainsResponse struct { DNSDomains []DNSDomain `json:"dns-domains,omitempty"` } +// FindDNSDomain attempts to find an DNSDomain by name or ID. +func (l ListDNSDomainsResponse) FindDNSDomain(nameOrID string) (DNSDomain, error) { + for i, elem := range l.DNSDomains { + if elem.ID.String() == nameOrID { + return l.DNSDomains[i], nil + } + } + + return DNSDomain{}, fmt.Errorf("%q not found in ListDNSDomainsResponse: %w", nameOrID, ErrNotFound) +} + // List DNS domains func (c Client) ListDNSDomains(ctx context.Context) (*ListDNSDomainsResponse, error) { path := "/dns-domain" @@ -6869,7 +6770,7 @@ type ListDNSDomainRecordsResponse struct { // FindDNSDomainRecord attempts to find an DNSDomainRecord by name or ID. func (l ListDNSDomainRecordsResponse) FindDNSDomainRecord(nameOrID string) (DNSDomainRecord, error) { for i, elem := range l.DNSDomainRecords { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.DNSDomainRecords[i], nil } } @@ -7287,6 +7188,17 @@ type ListElasticIPSResponse struct { ElasticIPS []ElasticIP `json:"elastic-ips,omitempty"` } +// FindElasticIP attempts to find an ElasticIP by name or ID. +func (l ListElasticIPSResponse) FindElasticIP(nameOrID string) (ElasticIP, error) { + for i, elem := range l.ElasticIPS { + if elem.ID.String() == nameOrID { + return l.ElasticIPS[i], nil + } + } + + return ElasticIP{}, fmt.Errorf("%q not found in ListElasticIPSResponse: %w", nameOrID, ErrNotFound) +} + // List Elastic IPs func (c Client) ListElasticIPS(ctx context.Context) (*ListElasticIPSResponse, error) { path := "/elastic-ip" @@ -7867,7 +7779,7 @@ type ListIAMRolesResponse struct { // FindIAMRole attempts to find an IAMRole by name or ID. func (l ListIAMRolesResponse) FindIAMRole(nameOrID string) (IAMRole, error) { for i, elem := range l.IAMRoles { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.IAMRoles[i], nil } } @@ -8224,7 +8136,7 @@ type ListInstancesResponse struct { // FindListInstancesResponseInstances attempts to find an ListInstancesResponseInstances by name or ID. func (l ListInstancesResponse) FindListInstancesResponseInstances(nameOrID string) (ListInstancesResponseInstances, error) { for i, elem := range l.Instances { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.Instances[i], nil } } @@ -8316,8 +8228,8 @@ type CreateInstanceRequest struct { AutoStart *bool `json:"auto-start,omitempty"` // Deploy target DeployTarget *DeployTarget `json:"deploy-target,omitempty"` - // Instance disk size in GB - DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=50000"` + // Instance disk size in GiB + DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=51200"` // Compute instance type InstanceType *InstanceType `json:"instance-type" validate:"required"` // Enable IPv6. DEPRECATED: use `public-ip-assignments`. @@ -8395,7 +8307,7 @@ type ListInstancePoolsResponse struct { // FindInstancePool attempts to find an InstancePool by name or ID. func (l ListInstancePoolsResponse) FindInstancePool(nameOrID string) (InstancePool, error) { for i, elem := range l.InstancePools { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.InstancePools[i], nil } } @@ -8446,6 +8358,14 @@ func (c Client) ListInstancePools(ctx context.Context) (*ListInstancePoolsRespon return bodyresp, nil } +type CreateInstancePoolRequestPublicIPAssignment string + +const ( + CreateInstancePoolRequestPublicIPAssignmentInet4 CreateInstancePoolRequestPublicIPAssignment = "inet4" + CreateInstancePoolRequestPublicIPAssignmentDual CreateInstancePoolRequestPublicIPAssignment = "dual" + CreateInstancePoolRequestPublicIPAssignmentNone CreateInstancePoolRequestPublicIPAssignment = "none" +) + type CreateInstancePoolRequest struct { // Instance Pool Anti-affinity Groups AntiAffinityGroups []AntiAffinityGroup `json:"anti-affinity-groups,omitempty"` @@ -8453,8 +8373,8 @@ type CreateInstancePoolRequest struct { DeployTarget *DeployTarget `json:"deploy-target,omitempty"` // Instance Pool description Description string `json:"description,omitempty" validate:"omitempty,lte=255"` - // Instances disk size in GB - DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=50000"` + // Instances disk size in GiB + DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=51200"` // Instances Elastic IPs ElasticIPS []ElasticIP `json:"elastic-ips,omitempty"` // Prefix to apply to Instances names (default: pool) @@ -8469,8 +8389,9 @@ type CreateInstancePoolRequest struct { // Instance Pool name Name string `json:"name" validate:"required,gte=1,lte=255"` // Instance Pool Private Networks - PrivateNetworks []PrivateNetwork `json:"private-networks,omitempty"` - PublicIPAssignment PublicIPAssignment `json:"public-ip-assignment,omitempty"` + PrivateNetworks []PrivateNetwork `json:"private-networks,omitempty"` + // Determines public IP assignment of the Instances. Type `none` is final and can't be changed later on. + PublicIPAssignment CreateInstancePoolRequestPublicIPAssignment `json:"public-ip-assignment,omitempty"` // Instance Pool Security Groups SecurityGroups []SecurityGroup `json:"security-groups,omitempty"` // Number of Instances @@ -8621,6 +8542,13 @@ func (c Client) GetInstancePool(ctx context.Context, id UUID) (*InstancePool, er return bodyresp, nil } +type UpdateInstancePoolRequestPublicIPAssignment string + +const ( + UpdateInstancePoolRequestPublicIPAssignmentInet4 UpdateInstancePoolRequestPublicIPAssignment = "inet4" + UpdateInstancePoolRequestPublicIPAssignmentDual UpdateInstancePoolRequestPublicIPAssignment = "dual" +) + type UpdateInstancePoolRequest struct { // Instance Pool Anti-affinity Groups AntiAffinityGroups []AntiAffinityGroup `json:"anti-affinity-groups"` @@ -8628,8 +8556,8 @@ type UpdateInstancePoolRequest struct { DeployTarget *DeployTarget `json:"deploy-target"` // Instance Pool description Description string `json:"description,omitempty" validate:"omitempty,lte=255"` - // Instances disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=50000"` + // Instances disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=51200"` // Instances Elastic IPs ElasticIPS []ElasticIP `json:"elastic-ips"` // Prefix to apply to Instances names (default: pool) @@ -8644,8 +8572,9 @@ type UpdateInstancePoolRequest struct { // Instance Pool name Name string `json:"name,omitempty" validate:"omitempty,gte=1,lte=255"` // Instance Pool Private Networks - PrivateNetworks []PrivateNetwork `json:"private-networks"` - PublicIPAssignment PublicIPAssignment `json:"public-ip-assignment,omitempty"` + PrivateNetworks []PrivateNetwork `json:"private-networks"` + // Determines public IP assignment of the Instances. + PublicIPAssignment UpdateInstancePoolRequestPublicIPAssignment `json:"public-ip-assignment,omitempty"` // Instance Pool Security Groups SecurityGroups []SecurityGroup `json:"security-groups"` // SSH key @@ -8879,6 +8808,17 @@ type ListInstanceTypesResponse struct { InstanceTypes []InstanceType `json:"instance-types,omitempty"` } +// FindInstanceType attempts to find an InstanceType by name or ID. +func (l ListInstanceTypesResponse) FindInstanceType(nameOrID string) (InstanceType, error) { + for i, elem := range l.InstanceTypes { + if elem.ID.String() == nameOrID { + return l.InstanceTypes[i], nil + } + } + + return InstanceType{}, fmt.Errorf("%q not found in ListInstanceTypesResponse: %w", nameOrID, ErrNotFound) +} + // List Compute instance Types func (c Client) ListInstanceTypes(ctx context.Context) (*ListInstanceTypesResponse, error) { path := "/instance-type" @@ -9379,8 +9319,8 @@ func (c Client) RemoveInstanceProtection(ctx context.Context, id UUID) (*Operati } type ResetInstanceRequest struct { - // Instance disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=50000"` + // Instance disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=51200"` // Instance template Template *Template `json:"template,omitempty"` } @@ -9479,8 +9419,8 @@ func (c Client) ResetInstancePassword(ctx context.Context, id UUID) (*Operation, } type ResizeInstanceDiskRequest struct { - // Instance disk size in GB - DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=50000"` + // Instance disk size in GiB + DiskSize int64 `json:"disk-size" validate:"required,gte=10,lte=51200"` } // This operation resizes a Compute instance's disk volume. Note: the disk can only grow, cannot be shrunk. @@ -9756,7 +9696,7 @@ type ListLoadBalancersResponse struct { // FindLoadBalancer attempts to find an LoadBalancer by name or ID. func (l ListLoadBalancersResponse) FindLoadBalancer(nameOrID string) (LoadBalancer, error) { for i, elem := range l.LoadBalancers { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.LoadBalancers[i], nil } } @@ -10020,6 +9960,7 @@ type AddServiceToLoadBalancerRequestStrategy string const ( AddServiceToLoadBalancerRequestStrategyRoundRobin AddServiceToLoadBalancerRequestStrategy = "round-robin" + AddServiceToLoadBalancerRequestStrategyMaglevHash AddServiceToLoadBalancerRequestStrategy = "maglev-hash" AddServiceToLoadBalancerRequestStrategySourceHash AddServiceToLoadBalancerRequestStrategy = "source-hash" ) @@ -10189,6 +10130,7 @@ type UpdateLoadBalancerServiceRequestStrategy string const ( UpdateLoadBalancerServiceRequestStrategyRoundRobin UpdateLoadBalancerServiceRequestStrategy = "round-robin" + UpdateLoadBalancerServiceRequestStrategyMaglevHash UpdateLoadBalancerServiceRequestStrategy = "maglev-hash" UpdateLoadBalancerServiceRequestStrategySourceHash UpdateLoadBalancerServiceRequestStrategy = "source-hash" ) @@ -10401,6 +10343,49 @@ func (c Client) GetOperation(ctx context.Context, id UUID) (*Operation, error) { return bodyresp, nil } +// Retrieve an organization +func (c Client) GetOrganization(ctx context.Context) (*Organization, error) { + path := "/organization" + + request, err := http.NewRequestWithContext(ctx, "GET", c.serverEndpoint+path, nil) + if err != nil { + return nil, fmt.Errorf("GetOrganization: new request: %w", err) + } + request.Header.Add("User-Agent", UserAgent) + + if err := c.executeRequestInterceptors(ctx, request); err != nil { + return nil, fmt.Errorf("GetOrganization: execute request editors: %w", err) + } + + if err := c.signRequest(request); err != nil { + return nil, fmt.Errorf("GetOrganization: sign request: %w", err) + } + + if c.trace { + dumpRequest(request, "get-organization") + } + + response, err := c.httpClient.Do(request) + if err != nil { + return nil, fmt.Errorf("GetOrganization: http client do: %w", err) + } + + if c.trace { + dumpResponse(response) + } + + if err := handleHTTPErrorResp(response); err != nil { + return nil, fmt.Errorf("GetOrganization: http response: %w", err) + } + + bodyresp := &Organization{} + if err := prepareJSONResponse(response, bodyresp); err != nil { + return nil, fmt.Errorf("GetOrganization: prepare Json response: %w", err) + } + + return bodyresp, nil +} + type ListPrivateNetworksResponse struct { PrivateNetworks []PrivateNetwork `json:"private-networks,omitempty"` } @@ -10408,7 +10393,7 @@ type ListPrivateNetworksResponse struct { // FindPrivateNetwork attempts to find an PrivateNetwork by name or ID. func (l ListPrivateNetworksResponse) FindPrivateNetwork(nameOrID string) (PrivateNetwork, error) { for i, elem := range l.PrivateNetworks { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.PrivateNetworks[i], nil } } @@ -11278,7 +11263,7 @@ type ListSecurityGroupsResponse struct { // FindSecurityGroup attempts to find an SecurityGroup by name or ID. func (l ListSecurityGroupsResponse) FindSecurityGroup(nameOrID string) (SecurityGroup, error) { for i, elem := range l.SecurityGroups { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.SecurityGroups[i], nil } } @@ -11863,7 +11848,7 @@ type ListSKSClustersResponse struct { // FindSKSCluster attempts to find an SKSCluster by name or ID. func (l ListSKSClustersResponse) FindSKSCluster(nameOrID string) (SKSCluster, error) { for i, elem := range l.SKSClusters { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.SKSClusters[i], nil } } @@ -12417,8 +12402,8 @@ type CreateSKSNodepoolRequest struct { DeployTarget *DeployTarget `json:"deploy-target,omitempty"` // Nodepool description Description string `json:"description,omitempty" validate:"omitempty,lte=255"` - // Nodepool instances disk size in GB - DiskSize int64 `json:"disk-size" validate:"required,gte=20,lte=50000"` + // Nodepool instances disk size in GiB + DiskSize int64 `json:"disk-size" validate:"required,gte=20,lte=51200"` // Prefix to apply to instances names (default: pool) InstancePrefix string `json:"instance-prefix,omitempty" validate:"omitempty,gte=1,lte=30"` // Compute instance type @@ -12580,8 +12565,8 @@ type UpdateSKSNodepoolRequest struct { DeployTarget *DeployTarget `json:"deploy-target"` // Nodepool description Description string `json:"description,omitempty" validate:"omitempty,lte=255"` - // Nodepool instances disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=20,lte=50000"` + // Nodepool instances disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=20,lte=51200"` // Prefix to apply to managed instances names (default: pool) InstancePrefix string `json:"instance-prefix,omitempty" validate:"omitempty,gte=1,lte=30"` // Compute instance type @@ -13050,7 +13035,7 @@ type ListSnapshotsResponse struct { // FindSnapshot attempts to find an Snapshot by name or ID. func (l ListSnapshotsResponse) FindSnapshot(nameOrID string) (Snapshot, error) { for i, elem := range l.Snapshots { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.Snapshots[i], nil } } @@ -13297,6 +13282,17 @@ type ListSOSBucketsUsageResponse struct { SOSBucketsUsage []SOSBucketUsage `json:"sos-buckets-usage,omitempty"` } +// FindSOSBucketUsage attempts to find an SOSBucketUsage by name or ID. +func (l ListSOSBucketsUsageResponse) FindSOSBucketUsage(nameOrID string) (SOSBucketUsage, error) { + for i, elem := range l.SOSBucketsUsage { + if string(elem.Name) == nameOrID { + return l.SOSBucketsUsage[i], nil + } + } + + return SOSBucketUsage{}, fmt.Errorf("%q not found in ListSOSBucketsUsageResponse: %w", nameOrID, ErrNotFound) +} + // List SOS Buckets Usage func (c Client) ListSOSBucketsUsage(ctx context.Context) (*ListSOSBucketsUsageResponse, error) { path := "/sos-buckets-usage" @@ -13407,6 +13403,17 @@ type ListSSHKeysResponse struct { SSHKeys []SSHKey `json:"ssh-keys,omitempty"` } +// FindSSHKey attempts to find an SSHKey by name or ID. +func (l ListSSHKeysResponse) FindSSHKey(nameOrID string) (SSHKey, error) { + for i, elem := range l.SSHKeys { + if string(elem.Name) == nameOrID { + return l.SSHKeys[i], nil + } + } + + return SSHKey{}, fmt.Errorf("%q not found in ListSSHKeysResponse: %w", nameOrID, ErrNotFound) +} + // List SSH keys func (c Client) ListSSHKeys(ctx context.Context) (*ListSSHKeysResponse, error) { path := "/ssh-key" @@ -13600,7 +13607,7 @@ type ListTemplatesResponse struct { // FindTemplate attempts to find an Template by name or ID. func (l ListTemplatesResponse) FindTemplate(nameOrID string) (Template, error) { for i, elem := range l.Templates { - if elem.Name == nameOrID || elem.ID.String() == nameOrID { + if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { return l.Templates[i], nil } } @@ -13966,6 +13973,17 @@ type ListZonesResponse struct { Zones []Zone `json:"zones,omitempty"` } +// FindZone attempts to find an Zone by name or ID. +func (l ListZonesResponse) FindZone(nameOrID string) (Zone, error) { + for i, elem := range l.Zones { + if string(elem.Name) == nameOrID { + return l.Zones[i], nil + } + } + + return Zone{}, fmt.Errorf("%q not found in ListZonesResponse: %w", nameOrID, ErrNotFound) +} + // List Zones func (c Client) ListZones(ctx context.Context) (*ListZonesResponse, error) { path := "/zone" diff --git a/vendor/github.com/exoscale/egoscale/v3/schemas.go b/vendor/github.com/exoscale/egoscale/v3/schemas.go index 862dcdd42..5fee16027 100644 --- a/vendor/github.com/exoscale/egoscale/v3/schemas.go +++ b/vendor/github.com/exoscale/egoscale/v3/schemas.go @@ -165,24 +165,6 @@ type BlockStorageVolumeTarget struct { ID UUID `json:"id,omitempty"` } -type CdnConfigurationStatus string - -const ( - CdnConfigurationStatusDeactivated CdnConfigurationStatus = "deactivated" - CdnConfigurationStatusPending CdnConfigurationStatus = "pending" - CdnConfigurationStatusActivated CdnConfigurationStatus = "activated" -) - -// CDN configuration -type CdnConfiguration struct { - // CDN configuration bucket name - Bucket string `json:"bucket,omitempty"` - // FQDN that serves the bucket contents - Fqdn string `json:"fqdn,omitempty"` - // CDN configuration status - Status CdnConfigurationStatus `json:"status,omitempty"` -} - // DBaaS plan backup config type DBAASBackupConfig struct { // Interval of taking a frequent backup in service types supporting different backup schedules @@ -1091,10 +1073,10 @@ type DBAASServicePG struct { Notifications []DBAASServiceNotification `json:"notifications,omitempty"` // postgresql.conf configuration values PGSettings JSONSchemaPG `json:"pg-settings,omitempty"` - // PGBouncer connection pooling settings - PgbouncerSettings JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` - // PGLookout settings - PglookoutSettings JSONSchemaPglookout `json:"pglookout-settings,omitempty"` + // System-wide settings for pgbouncer. + PgbouncerSettings *JSONSchemaPgbouncer `json:"pgbouncer-settings,omitempty"` + // System-wide settings for pglookout. + PglookoutSettings *JSONSchemaPglookout `json:"pglookout-settings,omitempty"` // Subscription plan Plan string `json:"plan" validate:"required"` // Percentage of total RAM that the database server uses for shared memory buffers. Valid range is 20-60 (float), which corresponds to 20% - 60%. This setting adjusts the shared_buffers configuration value. @@ -1103,9 +1085,9 @@ type DBAASServicePG struct { SynchronousReplication EnumPGSynchronousReplication `json:"synchronous-replication,omitempty"` // Service is protected against termination and powering off TerminationProtection *bool `json:"termination-protection,omitempty"` - // TimescaleDB extension configuration values - TimescaledbSettings JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` - Type DBAASServiceTypeName `json:"type" validate:"required,gte=0,lte=64"` + // System-wide settings for the timescaledb extension + TimescaledbSettings *JSONSchemaTimescaledb `json:"timescaledb-settings,omitempty"` + Type DBAASServiceTypeName `json:"type" validate:"required,gte=0,lte=64"` // Service last update timestamp (ISO 8601) UpdatedAT time.Time `json:"updated-at,omitempty"` // URI for connecting to the service (may be absent) @@ -1249,6 +1231,14 @@ type DBAASTask struct { TaskType string `json:"task-type,omitempty"` } +// Grafana User secrets +type DBAASUserGrafanaSecrets struct { + // Grafana password + Password string `json:"password,omitempty"` + // Grafana username + Username string `json:"username,omitempty"` +} + // Kafka User secrets type DBAASUserKafkaSecrets struct { // Kafka certificate @@ -1547,6 +1537,8 @@ type Event struct { IAMAPIKey *IAMAPIKey `json:"iam-api-key,omitempty"` // IAM Role IAMRole *IAMRole `json:"iam-role,omitempty"` + // User + IAMUser *User `json:"iam-user,omitempty"` // Operation message Message string `json:"message,omitempty"` // URI path parameters (free form map) @@ -1661,8 +1653,8 @@ type Instance struct { CreatedAT time.Time `json:"created-at,omitempty"` // Deploy target DeployTarget *DeployTarget `json:"deploy-target,omitempty"` - // Instance disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=50000"` + // Instance disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=51200"` // Instance Elastic IPs ElasticIPS []ElasticIP `json:"elastic-ips,omitempty"` // Instance ID @@ -1724,8 +1716,8 @@ type InstancePool struct { DeployTarget *DeployTarget `json:"deploy-target,omitempty"` // Instance Pool description Description string `json:"description,omitempty" validate:"omitempty,gte=1,lte=255"` - // Instances disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=50000"` + // Instances disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=10,lte=51200"` // Instances Elastic IPs ElasticIPS []ElasticIP `json:"elastic-ips,omitempty"` // Instance Pool ID @@ -1913,10 +1905,8 @@ type JSONSchemaGrafana struct { MetricsEnabled *bool `json:"metrics_enabled,omitempty"` // Enforce user lookup based on email instead of the unique ID provided by the IdP OauthAllowInsecureEmailLookup *bool `json:"oauth_allow_insecure_email_lookup,omitempty"` - // Allow access to selected service components through Privatelink - PrivatelinkAccess map[string]any `json:"privatelink_access,omitempty"` - // Name of the basebackup to restore in forked service - RecoveryBasebackupName string `json:"recovery_basebackup_name,omitempty" validate:"omitempty,lte=128"` + // Store logs for the service so that they are available in the HTTP API and console. + ServiceLog *bool `json:"service_log,omitempty"` // SMTP server settings SMTPServer map[string]any `json:"smtp_server,omitempty"` // Enable or disable Grafana unified alerting functionality. By default this is enabled and any legacy alerts will be migrated on upgrade to Grafana 9+. To stay on legacy alerting, set unified_alerting_enabled to false and alerting_enabled to true. See https://grafana.com/docs/grafana/latest/alerting/set-up/migrating-alerts/ for more details. @@ -1947,11 +1937,41 @@ type JSONSchemaOpensearch map[string]any // postgresql.conf configuration values type JSONSchemaPG map[string]any -// PGBouncer connection pooling settings -type JSONSchemaPgbouncer map[string]any +type JSONSchemaPgbouncerAutodbPoolMode string -// PGLookout settings -type JSONSchemaPglookout map[string]any +const ( + JSONSchemaPgbouncerAutodbPoolModeTransaction JSONSchemaPgbouncerAutodbPoolMode = "transaction" + JSONSchemaPgbouncerAutodbPoolModeSession JSONSchemaPgbouncerAutodbPoolMode = "session" + JSONSchemaPgbouncerAutodbPoolModeStatement JSONSchemaPgbouncerAutodbPoolMode = "statement" +) + +// System-wide settings for pgbouncer. +type JSONSchemaPgbouncer struct { + // If the automatically created database pools have been unused this many seconds, they are freed. If 0 then timeout is disabled. [seconds] + AutodbIdleTimeout int `json:"autodb_idle_timeout,omitempty" validate:"omitempty,gte=0,lte=86400"` + // Do not allow more than this many server connections per database (regardless of user). Setting it to 0 means unlimited. + AutodbMaxDBConnections int `json:"autodb_max_db_connections,omitempty" validate:"omitempty,gte=0,lte=2.147483647e+09"` + // PGBouncer pool mode + AutodbPoolMode JSONSchemaPgbouncerAutodbPoolMode `json:"autodb_pool_mode,omitempty"` + // If non-zero then create automatically a pool of that size per user when a pool doesn't exist. + AutodbPoolSize int `json:"autodb_pool_size,omitempty" validate:"omitempty,gte=0,lte=10000"` + // List of parameters to ignore when given in startup packet + IgnoreStartupParameters []string `json:"ignore_startup_parameters,omitempty"` + // Add more server connections to pool if below this number. Improves behavior when usual load comes suddenly back after period of total inactivity. The value is effectively capped at the pool size. + MinPoolSize int `json:"min_pool_size,omitempty" validate:"omitempty,gte=0,lte=10000"` + // If a server connection has been idle more than this many seconds it will be dropped. If 0 then timeout is disabled. [seconds] + ServerIdleTimeout int `json:"server_idle_timeout,omitempty" validate:"omitempty,gte=0,lte=86400"` + // The pooler will close an unused server connection that has been connected longer than this. [seconds] + ServerLifetime int `json:"server_lifetime,omitempty" validate:"omitempty,gte=60,lte=86400"` + // Run server_reset_query (DISCARD ALL) in all pooling modes + ServerResetQueryAlways *bool `json:"server_reset_query_always,omitempty"` +} + +// System-wide settings for pglookout. +type JSONSchemaPglookout struct { + // Number of seconds of master unavailability before triggering database failover to standby + MaxFailoverReplicationTimeLag int `json:"max_failover_replication_time_lag,omitempty" validate:"omitempty,gte=10,lte=9.223372036854776e+18"` +} type JSONSchemaRedisAclChannelsDefault string @@ -2009,8 +2029,11 @@ type JSONSchemaRedis struct { // Schema Registry configuration type JSONSchemaSchemaRegistry map[string]any -// TimescaleDB extension configuration values -type JSONSchemaTimescaledb map[string]any +// System-wide settings for the timescaledb extension +type JSONSchemaTimescaledb struct { + // The number of background workers for timescaledb operations. You should configure this setting to the sum of your number of databases and the total number of concurrent background workers you want running at any given point in time. + MaxBackgroundWorkers int `json:"max_background_workers,omitempty" validate:"omitempty,gte=1,lte=4096"` +} // Kubelet image GC options type KubeletImageGC struct { @@ -2087,6 +2110,7 @@ type LoadBalancerServiceStrategy string const ( LoadBalancerServiceStrategyRoundRobin LoadBalancerServiceStrategy = "round-robin" + LoadBalancerServiceStrategyMaglevHash LoadBalancerServiceStrategy = "maglev-hash" LoadBalancerServiceStrategySourceHash LoadBalancerServiceStrategy = "source-hash" ) @@ -2206,6 +2230,26 @@ type Operation struct { State OperationState `json:"state,omitempty"` } +// Organization +type Organization struct { + // Organization address + Address string `json:"address,omitempty"` + // Organization balance + Balance float64 `json:"balance,omitempty"` + // Organization city + City string `json:"city,omitempty"` + // Organization country + Country string `json:"country,omitempty"` + // Organization currency + Currency string `json:"currency,omitempty"` + // Organization ID + ID UUID `json:"id,omitempty"` + // Organization name + Name string `json:"name,omitempty"` + // Organization postcode + Postcode string `json:"postcode,omitempty"` +} + // Private Network type PrivateNetwork struct { // Private Network description @@ -2223,6 +2267,8 @@ type PrivateNetwork struct { Netmask net.IP `json:"netmask,omitempty"` // Private Network start IP address StartIP net.IP `json:"start-ip,omitempty"` + // Private Network VXLAN ID + Vni int64 `json:"vni,omitempty" validate:"omitempty,gt=0"` } // Private Network leased IP address @@ -2435,8 +2481,8 @@ type SKSNodepool struct { DeployTarget *DeployTarget `json:"deploy-target,omitempty"` // Nodepool description Description string `json:"description,omitempty" validate:"omitempty,lte=255"` - // Nodepool instances disk size in GB - DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=20,lte=50000"` + // Nodepool instances disk size in GiB + DiskSize int64 `json:"disk-size,omitempty" validate:"omitempty,gte=20,lte=51200"` // Nodepool ID ID UUID `json:"id,omitempty"` // Instance Pool @@ -2533,8 +2579,8 @@ type Snapshot struct { Instance *Instance `json:"instance,omitempty"` // Snapshot name Name string `json:"name,omitempty" validate:"omitempty,gte=1,lte=255"` - // Snapshot size in GB - Size int64 `json:"size,omitempty" validate:"omitempty,gte=10,lte=50000"` + // Snapshot size in GiB + Size int64 `json:"size,omitempty" validate:"omitempty,gte=10,lte=51200"` // Snapshot state State SnapshotState `json:"state,omitempty"` } @@ -2610,6 +2656,22 @@ type Template struct { Zones []ZoneName `json:"zones,omitempty"` } +// User +type User struct { + // User Email + Email string `json:"email" validate:"required"` + // User ID + ID UUID `json:"id,omitempty"` + // True if the user has not yet created an Exoscale account + Pending *bool `json:"pending,omitempty"` + // IAM Role + Role *IAMRole `json:"role" validate:"required"` + // SSO enabled + Sso *bool `json:"sso,omitempty"` + // Two Factor Authentication enabled + TwoFactorAuthentication *bool `json:"two-factor-authentication,omitempty"` +} + // Zone type Zone struct { // Zone API endpoint diff --git a/vendor/github.com/exoscale/egoscale/v3/version.go b/vendor/github.com/exoscale/egoscale/v3/version.go new file mode 100644 index 000000000..909a039a1 --- /dev/null +++ b/vendor/github.com/exoscale/egoscale/v3/version.go @@ -0,0 +1,4 @@ +package v3 + +// Version represents the current egoscale v3 version. +const Version = "v3.1.0" diff --git a/vendor/modules.txt b/vendor/modules.txt index f7bbfbf6f..0b33812eb 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -214,14 +214,16 @@ github.com/dlclark/regexp2/syntax # github.com/dustin/go-humanize v1.0.1 ## explicit; go 1.16 github.com/dustin/go-humanize -# github.com/exoscale/egoscale v0.102.4-0.20240506093113-3ae83713b097 -## explicit; go 1.21 +# github.com/exoscale/egoscale v0.102.5-0.20240712161721-275fc20694fd +## explicit; go 1.22 github.com/exoscale/egoscale/v2 github.com/exoscale/egoscale/v2/api github.com/exoscale/egoscale/v2/oapi +github.com/exoscale/egoscale/version +# github.com/exoscale/egoscale/v3 v3.1.1-0.20240712161721-275fc20694fd +## explicit; go 1.22 github.com/exoscale/egoscale/v3 github.com/exoscale/egoscale/v3/credentials -github.com/exoscale/egoscale/version # github.com/exoscale/openapi-cli-generator v1.1.0 ## explicit; go 1.12 github.com/exoscale/openapi-cli-generator/cli From 451f91d1869afb589619a1c8ed3aba04b14c02cd Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Mon, 15 Jul 2024 13:07:11 +0000 Subject: [PATCH 2/9] Fix instance type Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- cmd/instance_create.go | 16 +++++++++++----- utils/utils.go | 20 ++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/cmd/instance_create.go b/cmd/instance_create.go index a70869d44..25be2e798 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -19,6 +19,7 @@ import ( "github.com/exoscale/cli/pkg/output" exossh "github.com/exoscale/cli/pkg/ssh" "github.com/exoscale/cli/pkg/userdata" + "github.com/exoscale/cli/utils" v3 "github.com/exoscale/egoscale/v3" ) @@ -131,11 +132,16 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin return fmt.Errorf("error listing instance type: %w", err) } - instanceType, err := instanceTypes.FindInstanceType(c.InstanceType) - if err != nil { - return fmt.Errorf("error retrieving instance type: %w", err) + // c.InstanceType is never empty + instanceType := utils.ParseInstanceType(c.InstanceType) + for i, it := range instanceTypes.InstanceTypes { + if it.Family == instanceType.Family && it.Size == instanceType.Size { + instanceReq.InstanceType = &instanceTypes.InstanceTypes[i] + } + } + if instanceReq.InstanceType == nil { + return fmt.Errorf("error retrieving instance type %s: not found", c.InstanceType) } - instanceReq.InstanceType = &instanceType privateNetworks := make([]v3.PrivateNetwork, len(c.PrivateNetworks)) if l := len(c.PrivateNetworks); l > 0 { @@ -280,7 +286,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin return fmt.Errorf("error writing SSH private key file: %w", err) } - op, err := client.DeleteSSHKey(ctx, sshKeys[0].Name) + op, err := client.DeleteSSHKey(ctx, instanceReq.SSHKeys[0].Name) if err != nil { return fmt.Errorf("error deleting SSH key: %w", err) } diff --git a/utils/utils.go b/utils/utils.go index 404bdb500..734b66dd2 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/go-multierror" exoapi "github.com/exoscale/egoscale/v2/api" + v3 "github.com/exoscale/egoscale/v3" "github.com/exoscale/cli/pkg/account" v2 "github.com/exoscale/egoscale/v2" @@ -236,3 +237,22 @@ func ForEachZone(zones []string, f func(zone string) error) error { return meg.Wait().ErrorOrNil() } + +// ParseInstanceType returns an v3.InstanceType with family and name. +func ParseInstanceType(instanceType string) v3.InstanceType { + var typeFamily, typeSize string + + parts := strings.SplitN(instanceType, ".", 2) + if l := len(parts); l > 0 { + if l == 1 { + typeFamily, typeSize = "standard", strings.ToLower(parts[0]) + } else { + typeFamily, typeSize = strings.ToLower(parts[0]), strings.ToLower(parts[1]) + } + } + + return v3.InstanceType{ + Family: v3.InstanceTypeFamily(typeFamily), + Size: v3.InstanceTypeSize(typeSize), + } +} From 3dab229018c7895f3276775d0583437c288a35cd Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Mon, 22 Jul 2024 13:04:17 +0000 Subject: [PATCH 3/9] Uodate vendor Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 +- .../exoscale/egoscale/v3/operations.go | 100 +++++++++--------- vendor/modules.txt | 2 +- 4 files changed, 54 insertions(+), 54 deletions(-) diff --git a/go.mod b/go.mod index 8d7114748..0329b951f 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/aws/smithy-go v1.1.0 github.com/dustin/go-humanize v1.0.1 github.com/exoscale/egoscale v0.102.4 - github.com/exoscale/egoscale/v3 v3.1.0 + github.com/exoscale/egoscale/v3 v3.1.1 github.com/exoscale/openapi-cli-generator v1.1.0 github.com/fatih/camelcase v1.0.0 github.com/google/uuid v1.4.0 diff --git a/go.sum b/go.sum index 00994b315..62f86e807 100644 --- a/go.sum +++ b/go.sum @@ -197,8 +197,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7 github.com/envoyproxy/protoc-gen-validate v0.6.2/go.mod h1:2t7qjJNvHPx8IjnBOzl9E9/baC+qXE/TeeyBRzgJDws= github.com/exoscale/egoscale v0.102.4 h1:GBKsZMIOzwBfSu+4ZmWka3Ejf2JLiaBDHp4CQUgvp2E= github.com/exoscale/egoscale v0.102.4/go.mod h1:ROSmPtle0wvf91iLZb09++N/9BH2Jo9XxIpAEumvocA= -github.com/exoscale/egoscale/v3 v3.1.0 h1:8MSA0j4TZbUiE6iIzTmoY0URa3RoGGuHhX5oamCql4o= -github.com/exoscale/egoscale/v3 v3.1.0/go.mod h1:lPsza7G+giSxdzvzaHSEcjEAYz/YTiu2bEEha9KVAc4= +github.com/exoscale/egoscale/v3 v3.1.1 h1:NwTlXE2sKe2kBWm+c3bsHV+aWDFiEJ9JQpS6X3j4wbc= +github.com/exoscale/egoscale/v3 v3.1.1/go.mod h1:lPsza7G+giSxdzvzaHSEcjEAYz/YTiu2bEEha9KVAc4= github.com/exoscale/openapi-cli-generator v1.1.0 h1:fYjmPqHR5vxlOBrbvde7eo7bISNQIFxsGn4A5/acwKA= github.com/exoscale/openapi-cli-generator v1.1.0/go.mod h1:TZBnbT7f3hJ5ImyUphJwRM+X5xF/zCQZ6o8a42gQeTs= github.com/fatih/camelcase v1.0.0 h1:hxNvNX/xYBp0ovncs8WyWZrOrpBNub/JfaMvbURyft8= diff --git a/vendor/github.com/exoscale/egoscale/v3/operations.go b/vendor/github.com/exoscale/egoscale/v3/operations.go index 9bba6cb65..8a103355b 100644 --- a/vendor/github.com/exoscale/egoscale/v3/operations.go +++ b/vendor/github.com/exoscale/egoscale/v3/operations.go @@ -16,7 +16,7 @@ type ListAntiAffinityGroupsResponse struct { AntiAffinityGroups []AntiAffinityGroup `json:"anti-affinity-groups,omitempty"` } -// FindAntiAffinityGroup attempts to find an AntiAffinityGroup by name or ID. +// FindAntiAffinityGroup attempts to find an AntiAffinityGroup by nameOrID. func (l ListAntiAffinityGroupsResponse) FindAntiAffinityGroup(nameOrID string) (AntiAffinityGroup, error) { for i, elem := range l.AntiAffinityGroups { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -217,15 +217,15 @@ type ListAPIKeysResponse struct { APIKeys []IAMAPIKey `json:"api-keys,omitempty"` } -// FindIAMAPIKey attempts to find an IAMAPIKey by name or ID. -func (l ListAPIKeysResponse) FindIAMAPIKey(nameOrID string) (IAMAPIKey, error) { +// FindIAMAPIKey attempts to find an IAMAPIKey by name. +func (l ListAPIKeysResponse) FindIAMAPIKey(name string) (IAMAPIKey, error) { for i, elem := range l.APIKeys { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.APIKeys[i], nil } } - return IAMAPIKey{}, fmt.Errorf("%q not found in ListAPIKeysResponse: %w", nameOrID, ErrNotFound) + return IAMAPIKey{}, fmt.Errorf("%q not found in ListAPIKeysResponse: %w", name, ErrNotFound) } // List API keys @@ -418,7 +418,7 @@ type ListBlockStorageVolumesResponse struct { BlockStorageVolumes []BlockStorageVolume `json:"block-storage-volumes,omitempty"` } -// FindBlockStorageVolume attempts to find an BlockStorageVolume by name or ID. +// FindBlockStorageVolume attempts to find an BlockStorageVolume by nameOrID. func (l ListBlockStorageVolumesResponse) FindBlockStorageVolume(nameOrID string) (BlockStorageVolume, error) { for i, elem := range l.BlockStorageVolumes { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -553,7 +553,7 @@ type ListBlockStorageSnapshotsResponse struct { BlockStorageSnapshots []BlockStorageSnapshot `json:"block-storage-snapshots,omitempty"` } -// FindBlockStorageSnapshot attempts to find an BlockStorageSnapshot by name or ID. +// FindBlockStorageSnapshot attempts to find an BlockStorageSnapshot by nameOrID. func (l ListBlockStorageSnapshotsResponse) FindBlockStorageSnapshot(nameOrID string) (BlockStorageSnapshot, error) { for i, elem := range l.BlockStorageSnapshots { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -5702,15 +5702,15 @@ type ListDBAASServicesResponse struct { DBAASServices []DBAASServiceCommon `json:"dbaas-services,omitempty"` } -// FindDBAASServiceCommon attempts to find an DBAASServiceCommon by name or ID. -func (l ListDBAASServicesResponse) FindDBAASServiceCommon(nameOrID string) (DBAASServiceCommon, error) { +// FindDBAASServiceCommon attempts to find an DBAASServiceCommon by name. +func (l ListDBAASServicesResponse) FindDBAASServiceCommon(name string) (DBAASServiceCommon, error) { for i, elem := range l.DBAASServices { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.DBAASServices[i], nil } } - return DBAASServiceCommon{}, fmt.Errorf("%q not found in ListDBAASServicesResponse: %w", nameOrID, ErrNotFound) + return DBAASServiceCommon{}, fmt.Errorf("%q not found in ListDBAASServicesResponse: %w", name, ErrNotFound) } // List DBaaS services @@ -5887,15 +5887,15 @@ type ListDBAASServiceTypesResponse struct { DBAASServiceTypes []DBAASServiceType `json:"dbaas-service-types,omitempty"` } -// FindDBAASServiceType attempts to find an DBAASServiceType by name or ID. -func (l ListDBAASServiceTypesResponse) FindDBAASServiceType(nameOrID string) (DBAASServiceType, error) { +// FindDBAASServiceType attempts to find an DBAASServiceType by name. +func (l ListDBAASServiceTypesResponse) FindDBAASServiceType(name string) (DBAASServiceType, error) { for i, elem := range l.DBAASServiceTypes { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.DBAASServiceTypes[i], nil } } - return DBAASServiceType{}, fmt.Errorf("%q not found in ListDBAASServiceTypesResponse: %w", nameOrID, ErrNotFound) + return DBAASServiceType{}, fmt.Errorf("%q not found in ListDBAASServiceTypesResponse: %w", name, ErrNotFound) } // List available service types for DBaaS @@ -6552,7 +6552,7 @@ type ListDeployTargetsResponse struct { DeployTargets []DeployTarget `json:"deploy-targets,omitempty"` } -// FindDeployTarget attempts to find an DeployTarget by name or ID. +// FindDeployTarget attempts to find an DeployTarget by nameOrID. func (l ListDeployTargetsResponse) FindDeployTarget(nameOrID string) (DeployTarget, error) { for i, elem := range l.DeployTargets { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -6653,15 +6653,15 @@ type ListDNSDomainsResponse struct { DNSDomains []DNSDomain `json:"dns-domains,omitempty"` } -// FindDNSDomain attempts to find an DNSDomain by name or ID. -func (l ListDNSDomainsResponse) FindDNSDomain(nameOrID string) (DNSDomain, error) { +// FindDNSDomain attempts to find an DNSDomain by ID. +func (l ListDNSDomainsResponse) FindDNSDomain(ID string) (DNSDomain, error) { for i, elem := range l.DNSDomains { - if elem.ID.String() == nameOrID { + if elem.ID.String() == ID { return l.DNSDomains[i], nil } } - return DNSDomain{}, fmt.Errorf("%q not found in ListDNSDomainsResponse: %w", nameOrID, ErrNotFound) + return DNSDomain{}, fmt.Errorf("%q not found in ListDNSDomainsResponse: %w", ID, ErrNotFound) } // List DNS domains @@ -6767,7 +6767,7 @@ type ListDNSDomainRecordsResponse struct { DNSDomainRecords []DNSDomainRecord `json:"dns-domain-records,omitempty"` } -// FindDNSDomainRecord attempts to find an DNSDomainRecord by name or ID. +// FindDNSDomainRecord attempts to find an DNSDomainRecord by nameOrID. func (l ListDNSDomainRecordsResponse) FindDNSDomainRecord(nameOrID string) (DNSDomainRecord, error) { for i, elem := range l.DNSDomainRecords { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -7188,15 +7188,15 @@ type ListElasticIPSResponse struct { ElasticIPS []ElasticIP `json:"elastic-ips,omitempty"` } -// FindElasticIP attempts to find an ElasticIP by name or ID. -func (l ListElasticIPSResponse) FindElasticIP(nameOrID string) (ElasticIP, error) { +// FindElasticIP attempts to find an ElasticIP by ID. +func (l ListElasticIPSResponse) FindElasticIP(ID string) (ElasticIP, error) { for i, elem := range l.ElasticIPS { - if elem.ID.String() == nameOrID { + if elem.ID.String() == ID { return l.ElasticIPS[i], nil } } - return ElasticIP{}, fmt.Errorf("%q not found in ListElasticIPSResponse: %w", nameOrID, ErrNotFound) + return ElasticIP{}, fmt.Errorf("%q not found in ListElasticIPSResponse: %w", ID, ErrNotFound) } // List Elastic IPs @@ -7776,7 +7776,7 @@ type ListIAMRolesResponse struct { IAMRoles []IAMRole `json:"iam-roles,omitempty"` } -// FindIAMRole attempts to find an IAMRole by name or ID. +// FindIAMRole attempts to find an IAMRole by nameOrID. func (l ListIAMRolesResponse) FindIAMRole(nameOrID string) (IAMRole, error) { for i, elem := range l.IAMRoles { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -8133,7 +8133,7 @@ type ListInstancesResponse struct { Instances []ListInstancesResponseInstances `json:"instances,omitempty"` } -// FindListInstancesResponseInstances attempts to find an ListInstancesResponseInstances by name or ID. +// FindListInstancesResponseInstances attempts to find an ListInstancesResponseInstances by nameOrID. func (l ListInstancesResponse) FindListInstancesResponseInstances(nameOrID string) (ListInstancesResponseInstances, error) { for i, elem := range l.Instances { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -8304,7 +8304,7 @@ type ListInstancePoolsResponse struct { InstancePools []InstancePool `json:"instance-pools,omitempty"` } -// FindInstancePool attempts to find an InstancePool by name or ID. +// FindInstancePool attempts to find an InstancePool by nameOrID. func (l ListInstancePoolsResponse) FindInstancePool(nameOrID string) (InstancePool, error) { for i, elem := range l.InstancePools { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -8808,15 +8808,15 @@ type ListInstanceTypesResponse struct { InstanceTypes []InstanceType `json:"instance-types,omitempty"` } -// FindInstanceType attempts to find an InstanceType by name or ID. -func (l ListInstanceTypesResponse) FindInstanceType(nameOrID string) (InstanceType, error) { +// FindInstanceType attempts to find an InstanceType by ID. +func (l ListInstanceTypesResponse) FindInstanceType(ID string) (InstanceType, error) { for i, elem := range l.InstanceTypes { - if elem.ID.String() == nameOrID { + if elem.ID.String() == ID { return l.InstanceTypes[i], nil } } - return InstanceType{}, fmt.Errorf("%q not found in ListInstanceTypesResponse: %w", nameOrID, ErrNotFound) + return InstanceType{}, fmt.Errorf("%q not found in ListInstanceTypesResponse: %w", ID, ErrNotFound) } // List Compute instance Types @@ -9693,7 +9693,7 @@ type ListLoadBalancersResponse struct { LoadBalancers []LoadBalancer `json:"load-balancers,omitempty"` } -// FindLoadBalancer attempts to find an LoadBalancer by name or ID. +// FindLoadBalancer attempts to find an LoadBalancer by nameOrID. func (l ListLoadBalancersResponse) FindLoadBalancer(nameOrID string) (LoadBalancer, error) { for i, elem := range l.LoadBalancers { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -10390,7 +10390,7 @@ type ListPrivateNetworksResponse struct { PrivateNetworks []PrivateNetwork `json:"private-networks,omitempty"` } -// FindPrivateNetwork attempts to find an PrivateNetwork by name or ID. +// FindPrivateNetwork attempts to find an PrivateNetwork by nameOrID. func (l ListPrivateNetworksResponse) FindPrivateNetwork(nameOrID string) (PrivateNetwork, error) { for i, elem := range l.PrivateNetworks { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -11260,7 +11260,7 @@ type ListSecurityGroupsResponse struct { SecurityGroups []SecurityGroup `json:"security-groups,omitempty"` } -// FindSecurityGroup attempts to find an SecurityGroup by name or ID. +// FindSecurityGroup attempts to find an SecurityGroup by nameOrID. func (l ListSecurityGroupsResponse) FindSecurityGroup(nameOrID string) (SecurityGroup, error) { for i, elem := range l.SecurityGroups { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -11845,7 +11845,7 @@ type ListSKSClustersResponse struct { SKSClusters []SKSCluster `json:"sks-clusters,omitempty"` } -// FindSKSCluster attempts to find an SKSCluster by name or ID. +// FindSKSCluster attempts to find an SKSCluster by nameOrID. func (l ListSKSClustersResponse) FindSKSCluster(nameOrID string) (SKSCluster, error) { for i, elem := range l.SKSClusters { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -13032,7 +13032,7 @@ type ListSnapshotsResponse struct { Snapshots []Snapshot `json:"snapshots,omitempty"` } -// FindSnapshot attempts to find an Snapshot by name or ID. +// FindSnapshot attempts to find an Snapshot by nameOrID. func (l ListSnapshotsResponse) FindSnapshot(nameOrID string) (Snapshot, error) { for i, elem := range l.Snapshots { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -13282,15 +13282,15 @@ type ListSOSBucketsUsageResponse struct { SOSBucketsUsage []SOSBucketUsage `json:"sos-buckets-usage,omitempty"` } -// FindSOSBucketUsage attempts to find an SOSBucketUsage by name or ID. -func (l ListSOSBucketsUsageResponse) FindSOSBucketUsage(nameOrID string) (SOSBucketUsage, error) { +// FindSOSBucketUsage attempts to find an SOSBucketUsage by name. +func (l ListSOSBucketsUsageResponse) FindSOSBucketUsage(name string) (SOSBucketUsage, error) { for i, elem := range l.SOSBucketsUsage { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.SOSBucketsUsage[i], nil } } - return SOSBucketUsage{}, fmt.Errorf("%q not found in ListSOSBucketsUsageResponse: %w", nameOrID, ErrNotFound) + return SOSBucketUsage{}, fmt.Errorf("%q not found in ListSOSBucketsUsageResponse: %w", name, ErrNotFound) } // List SOS Buckets Usage @@ -13403,15 +13403,15 @@ type ListSSHKeysResponse struct { SSHKeys []SSHKey `json:"ssh-keys,omitempty"` } -// FindSSHKey attempts to find an SSHKey by name or ID. -func (l ListSSHKeysResponse) FindSSHKey(nameOrID string) (SSHKey, error) { +// FindSSHKey attempts to find an SSHKey by name. +func (l ListSSHKeysResponse) FindSSHKey(name string) (SSHKey, error) { for i, elem := range l.SSHKeys { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.SSHKeys[i], nil } } - return SSHKey{}, fmt.Errorf("%q not found in ListSSHKeysResponse: %w", nameOrID, ErrNotFound) + return SSHKey{}, fmt.Errorf("%q not found in ListSSHKeysResponse: %w", name, ErrNotFound) } // List SSH keys @@ -13604,7 +13604,7 @@ type ListTemplatesResponse struct { Templates []Template `json:"templates,omitempty"` } -// FindTemplate attempts to find an Template by name or ID. +// FindTemplate attempts to find an Template by nameOrID. func (l ListTemplatesResponse) FindTemplate(nameOrID string) (Template, error) { for i, elem := range l.Templates { if string(elem.Name) == nameOrID || elem.ID.String() == nameOrID { @@ -13973,15 +13973,15 @@ type ListZonesResponse struct { Zones []Zone `json:"zones,omitempty"` } -// FindZone attempts to find an Zone by name or ID. -func (l ListZonesResponse) FindZone(nameOrID string) (Zone, error) { +// FindZone attempts to find an Zone by name. +func (l ListZonesResponse) FindZone(name string) (Zone, error) { for i, elem := range l.Zones { - if string(elem.Name) == nameOrID { + if string(elem.Name) == name { return l.Zones[i], nil } } - return Zone{}, fmt.Errorf("%q not found in ListZonesResponse: %w", nameOrID, ErrNotFound) + return Zone{}, fmt.Errorf("%q not found in ListZonesResponse: %w", name, ErrNotFound) } // List Zones diff --git a/vendor/modules.txt b/vendor/modules.txt index da07b495c..ea3975ac2 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -220,7 +220,7 @@ github.com/exoscale/egoscale/v2 github.com/exoscale/egoscale/v2/api github.com/exoscale/egoscale/v2/oapi github.com/exoscale/egoscale/version -# github.com/exoscale/egoscale/v3 v3.1.0 +# github.com/exoscale/egoscale/v3 v3.1.1 ## explicit; go 1.22 github.com/exoscale/egoscale/v3 github.com/exoscale/egoscale/v3/credentials From ea877ce56985998afa6f7479c9cd23ed5526c243 Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Mon, 22 Jul 2024 13:06:40 +0000 Subject: [PATCH 4/9] changelog Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6438b2f71..ec444aa00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +### Improvements + +- Instance Create: Migrate to egoscale v3 and add multiple sshkeys #620 + ## 1.78.4 ### Improvements From 1b9d243fba6a71d3787ed799c2b3ffd6283aab4f Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Tue, 23 Jul 2024 12:10:44 +0000 Subject: [PATCH 5/9] break Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- cmd/instance_create.go | 1 + 1 file changed, 1 insertion(+) diff --git a/cmd/instance_create.go b/cmd/instance_create.go index 25be2e798..dcf729937 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -137,6 +137,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin for i, it := range instanceTypes.InstanceTypes { if it.Family == instanceType.Family && it.Size == instanceType.Size { instanceReq.InstanceType = &instanceTypes.InstanceTypes[i] + break } } if instanceReq.InstanceType == nil { From 33cb46b3476f955d4c04690c4c01c1c178e4d44d Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Tue, 23 Jul 2024 14:11:48 +0200 Subject: [PATCH 6/9] Update cmd/instance_create.go Co-authored-by: Predrag Janosevic --- cmd/instance_create.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/instance_create.go b/cmd/instance_create.go index dcf729937..a01bc7ceb 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -40,7 +40,7 @@ type instanceCreateCmd struct { Labels map[string]string `cli-flag:"label" cli-usage:"instance label (format: key=value)"` PrivateNetworks []string `cli-flag:"private-network" cli-usage:"instance Private Network NAME|ID (can be specified multiple times)"` PrivateInstance bool `cli-flag:"private-instance" cli-usage:"enable private instance to be created"` - SSHKeys []string `cli-flag:"ssh-key" cli-usage:"SSH keys to deploy on the instance"` + SSHKeys []string `cli-flag:"ssh-key" cli-usage:"SSH key to deploy on the instance (can be specified multiple times)"` SecurityGroups []string `cli-flag:"security-group" cli-usage:"instance Security Group NAME|ID (can be specified multiple times)"` Template string `cli-usage:"instance template NAME|ID"` TemplateVisibility string `cli-usage:"instance template visibility (public|private)"` From eeccc70689056d0b68d4414ab845a72e91b91af4 Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Tue, 23 Jul 2024 12:23:59 +0000 Subject: [PATCH 7/9] Add test Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- utils/utils_test.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 utils/utils_test.go diff --git a/utils/utils_test.go b/utils/utils_test.go new file mode 100644 index 000000000..2141e2b43 --- /dev/null +++ b/utils/utils_test.go @@ -0,0 +1,30 @@ +package utils + +import ( + "testing" + + v3 "github.com/exoscale/egoscale/v3" + "github.com/stretchr/testify/assert" +) + +func TestParseInstanceType(t *testing.T) { + testCases := []struct { + instanceType string + expectedFamily v3.InstanceTypeFamily + expectedSize v3.InstanceTypeSize + }{ + {"standard.large", v3.InstanceTypeFamily("standard"), v3.InstanceTypeSize("large")}, + {"gpu2.mega", v3.InstanceTypeFamily("gpu2"), v3.InstanceTypeSize("mega")}, + {"colossus", v3.InstanceTypeFamily("standard"), v3.InstanceTypeSize("colossus")}, + {"", v3.InstanceTypeFamily("standard"), v3.InstanceTypeSize("")}, + {"invalid-format", v3.InstanceTypeFamily("standard"), v3.InstanceTypeSize("invalid-format")}, + } + + for _, tc := range testCases { + t.Run(tc.instanceType, func(t *testing.T) { + result := ParseInstanceType(tc.instanceType) + assert.Equal(t, tc.expectedFamily, result.Family) + assert.Equal(t, tc.expectedSize, result.Size) + }) + } +} From e096d1bdd3883a7eda5ad8a29682623dbfc80674 Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Wed, 24 Jul 2024 09:15:41 +0000 Subject: [PATCH 8/9] Fix instance creation Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- cmd/instance_create.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/cmd/instance_create.go b/cmd/instance_create.go index a01bc7ceb..f4828396e 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -99,7 +99,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin } if l := len(c.AntiAffinityGroups); l > 0 { - antiAffinityGroupIDs := make([]v3.AntiAffinityGroup, l) + instanceReq.AntiAffinityGroups = make([]v3.AntiAffinityGroup, l) af, err := client.ListAntiAffinityGroups(ctx) if err != nil { return fmt.Errorf("error listing Anti-Affinity Group: %w", err) @@ -109,10 +109,8 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin if err != nil { return fmt.Errorf("error retrieving Anti-Affinity Group: %w", err) } - antiAffinityGroupIDs[i] = antiAffinityGroup + instanceReq.AntiAffinityGroups[i] = v3.AntiAffinityGroup{ID: antiAffinityGroup.ID} } - - instanceReq.AntiAffinityGroups = antiAffinityGroupIDs } if c.DeployTarget != "" { @@ -171,7 +169,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin if err != nil { return fmt.Errorf("error retrieving Security Group: %w", err) } - instanceReq.SecurityGroups[i] = securityGroup + instanceReq.SecurityGroups[i] = v3.SecurityGroup{ID: securityGroup.ID} } } From 8e4a3217b1d97ed7699dadcbb330bf3c255f8b44 Mon Sep 17 00:00:00 2001 From: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> Date: Wed, 24 Jul 2024 09:23:25 +0000 Subject: [PATCH 9/9] Add todo Signed-off-by: Pierre-Emmanuel Jacquier <15922119+pierre-emmanuelJ@users.noreply.github.com> --- cmd/instance_create.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/instance_create.go b/cmd/instance_create.go index f4828396e..c2d3e4b0d 100644 --- a/cmd/instance_create.go +++ b/cmd/instance_create.go @@ -299,7 +299,7 @@ func (c *instanceCreateCmd) cmdRun(_ *cobra.Command, _ []string) error { //nolin return (&instanceShowCmd{ cliCommandSettings: c.cliCommandSettings, Instance: instanceID.String(), - // migrate instanceShow to v3 to pass v3.ZoneName + // TODO migrate instanceShow to v3 to pass v3.ZoneName Zone: string(c.Zone), }).cmdRun(nil, nil) }